"use client";

/**
 * Call History Panel
 *
 * Dashboard component for viewing voice call history
 * with transcripts and analytics
 */

import React, { useState, useEffect, useCallback } from "react";
import logger from "@/lib/logger";
import {
  Phone,
  PhoneIncoming,
  PhoneOutgoing,
  Clock,
  Calendar,
  ChevronRight,
  X,
  User,
  FileText,
  TrendingUp,
  AlertCircle,
  Loader2,
  Filter,
} from "lucide-react";

interface CallSummary {
  id: string;
  twilioCallSid: string;
  direction: "inbound" | "outbound";
  status: string;
  fromNumber: string;
  toNumber: string;
  durationSeconds: number | null;
  initiatedAt: string;
  answeredAt: string | null;
  endedAt: string | null;
  summary: string | null;
  sentiment: string | null;
  appointmentBooked: boolean;
  transferredToHuman: boolean;
}

interface CallDetails {
  id: string;
  direction: string;
  status: string;
  fromNumber: string;
  fromNumberFormatted: string;
  toNumber: string;
  toNumberFormatted: string;
  durationSeconds: number | null;
  initiatedAt: string;
  answeredAt: string | null;
  endedAt: string | null;
  transcript: Array<{
    role: string;
    content: string;
    timestamp?: string;
  }> | null;
  transcriptText: string | null;
  summary: string | null;
  sentiment: string | null;
  topics: string[] | null;
  appointmentBooked: boolean;
  bookingId: string | null;
  transferredToHuman: boolean;
  escalationReason: string | null;
  qualityScore: number | null;
  estimatedCost: number | null;
}

interface CallHistoryPanelProps {
  userId: string;
  lang?: "en" | "ar";
}

const translations = {
  en: {
    title: "Call History",
    subtitle: "View your voice call history and transcripts",
    noHistory: "No call history",
    noHistoryDesc:
      "Your voice call history will appear here once you start receiving calls.",
    loading: "Loading...",
    error: "Error loading call history",
    retry: "Retry",
    inbound: "Inbound",
    outbound: "Outbound",
    duration: "Duration",
    transcript: "Transcript",
    summary: "Summary",
    sentiment: "Sentiment",
    topics: "Topics",
    actions: "Actions Taken",
    appointmentBooked: "Appointment Booked",
    transferredToHuman: "Transferred to Human",
    escalationReason: "Escalation Reason",
    qualityScore: "Quality Score",
    estimatedCost: "Estimated Cost",
    close: "Close",
    filter: "Filter",
    allCalls: "All Calls",
    completed: "Completed",
    missed: "Missed",
    positive: "Positive",
    neutral: "Neutral",
    negative: "Negative",
    unknown: "Unknown",
    agent: "Agent",
    caller: "Caller",
  },
  ar: {
    title: "سجل المكالمات",
    subtitle: "عرض سجل المكالمات الصوتية والنصوص",
    noHistory: "لا يوجد سجل مكالمات",
    noHistoryDesc:
      "سيظهر سجل المكالمات الصوتية هنا بمجرد بدء استقبال المكالمات.",
    loading: "جاري التحميل...",
    error: "خطأ في تحميل سجل المكالمات",
    retry: "إعادة المحاولة",
    inbound: "وارد",
    outbound: "صادر",
    duration: "المدة",
    transcript: "النص",
    summary: "الملخص",
    sentiment: "المشاعر",
    topics: "المواضيع",
    actions: "الإجراءات المتخذة",
    appointmentBooked: "تم حجز موعد",
    transferredToHuman: "تم التحويل لموظف",
    escalationReason: "سبب التصعيد",
    qualityScore: "درجة الجودة",
    estimatedCost: "التكلفة المقدرة",
    close: "إغلاق",
    filter: "تصفية",
    allCalls: "كل المكالمات",
    completed: "مكتملة",
    missed: "فائتة",
    positive: "إيجابي",
    neutral: "محايد",
    negative: "سلبي",
    unknown: "غير معروف",
    agent: "الوكيل",
    caller: "المتصل",
  },
};

export function CallHistoryPanel({
  userId: _userId,
  lang = "en",
}: CallHistoryPanelProps) {
  const t = translations[lang];
  const [calls, setCalls] = useState<CallSummary[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedCall, setSelectedCall] = useState<CallDetails | null>(null);
  const [isLoadingDetails, setIsLoadingDetails] = useState(false);
  const [filter, setFilter] = useState<"all" | "inbound" | "outbound">("all");
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);

  const fetchCalls = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);

      const params = new URLSearchParams({
        page: page.toString(),
        pageSize: "20",
      });

      if (filter !== "all") {
        params.set("direction", filter);
      }

      const response = await fetch(`/api/voice/calls?${params}`);
      if (!response.ok) {
        throw new Error("Failed to fetch call history");
      }

      const data = await response.json();
      setCalls(data.calls || []);
      setHasMore(data.hasMore || false);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setIsLoading(false);
    }
  }, [page, filter]);

  useEffect(() => {
    fetchCalls();
  }, [fetchCalls]);

  const fetchCallDetails = async (callId: string) => {
    try {
      setIsLoadingDetails(true);

      const response = await fetch(`/api/voice/calls/${callId}`);
      if (!response.ok) {
        throw new Error("Failed to fetch call details");
      }

      const data = await response.json();
      setSelectedCall(data.call);
    } catch (err) {
      logger.error("Error fetching call details", { error: err, callId });
    } finally {
      setIsLoadingDetails(false);
    }
  };

  const formatDuration = (seconds: number | null): string => {
    if (!seconds) return "0:00";
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  };

  const formatDateTime = (dateStr: string): string => {
    const date = new Date(dateStr);
    return date.toLocaleString(lang === "ar" ? "ar-SA" : "en-US", {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const getSentimentBadge = (sentiment: string | null) => {
    const config = {
      positive: { color: "bg-green-100 text-green-800", label: t.positive },
      neutral: { color: "bg-gray-100 text-gray-800", label: t.neutral },
      negative: { color: "bg-red-100 text-red-800", label: t.negative },
    };

    const s = sentiment?.toLowerCase() || "neutral";
    const c = config[s as keyof typeof config] || config.neutral;

    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${c.color}`}>
        {c.label}
      </span>
    );
  };

  if (isLoading && calls.length === 0) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <div className="flex items-center justify-center py-8">
          <Loader2 className="h-6 w-6 animate-spin text-brand-500" />
          <span className="ml-2 text-gray-600 dark:text-gray-400">
            {t.loading}
          </span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <div className="flex flex-col items-center justify-center py-8">
          <AlertCircle className="h-8 w-8 text-red-500 mb-2" />
          <p className="text-red-600 dark:text-red-400 mb-4">{t.error}</p>
          <button
            onClick={fetchCalls}
            className="px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors"
          >
            {t.retry}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow">
      {/* Header */}
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              <Phone className="h-5 w-5 text-brand-500" />
              {t.title}
            </h3>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              {t.subtitle}
            </p>
          </div>

          {/* Filter */}
          <div className="flex items-center gap-2">
            <Filter className="h-4 w-4 text-gray-400" />
            <select
              value={filter}
              onChange={(e) => setFilter(e.target.value as typeof filter)}
              className="px-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="all">{t.allCalls}</option>
              <option value="inbound">{t.inbound}</option>
              <option value="outbound">{t.outbound}</option>
            </select>
          </div>
        </div>
      </div>

      {/* Content */}
      {calls.length === 0 ? (
        <div className="px-6 py-12 text-center">
          <Phone className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h4 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            {t.noHistory}
          </h4>
          <p className="text-gray-600 dark:text-gray-400 max-w-md mx-auto">
            {t.noHistoryDesc}
          </p>
        </div>
      ) : (
        <div className="divide-y divide-gray-200 dark:divide-gray-700">
          {calls.map((call) => (
            <div
              key={call.id}
              onClick={() => fetchCallDetails(call.id)}
              className="px-6 py-4 hover:bg-gray-50 dark:hover:bg-gray-700/30 cursor-pointer transition-colors"
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  {/* Direction Icon */}
                  <div
                    className={`p-2 rounded-full ${
                      call.direction === "inbound"
                        ? "bg-green-100 text-green-600"
                        : "bg-blue-100 text-blue-600"
                    }`}
                  >
                    {call.direction === "inbound" ? (
                      <PhoneIncoming className="h-5 w-5" />
                    ) : (
                      <PhoneOutgoing className="h-5 w-5" />
                    )}
                  </div>

                  {/* Call Info */}
                  <div>
                    <div className="font-medium text-gray-900 dark:text-white">
                      {call.direction === "inbound"
                        ? call.fromNumber
                        : call.toNumber}
                    </div>
                    <div className="flex items-center gap-3 text-sm text-gray-500 dark:text-gray-400">
                      <span className="flex items-center gap-1">
                        <Calendar className="h-3 w-3" />
                        {formatDateTime(call.initiatedAt)}
                      </span>
                      <span className="flex items-center gap-1">
                        <Clock className="h-3 w-3" />
                        {formatDuration(call.durationSeconds)}
                      </span>
                    </div>
                  </div>
                </div>

                {/* Right Side */}
                <div className="flex items-center gap-3">
                  {/* Badges */}
                  <div className="flex items-center gap-2">
                    {call.appointmentBooked && (
                      <span className="px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs font-medium">
                        📅 Booked
                      </span>
                    )}
                    {call.transferredToHuman && (
                      <span className="px-2 py-1 bg-yellow-100 text-yellow-800 rounded-full text-xs font-medium">
                        👤 Transferred
                      </span>
                    )}
                    {call.sentiment && getSentimentBadge(call.sentiment)}
                  </div>

                  <ChevronRight className="h-5 w-5 text-gray-400" />
                </div>
              </div>

              {/* Summary Preview */}
              {call.summary && (
                <p className="mt-2 text-sm text-gray-600 dark:text-gray-400 line-clamp-1 ml-14">
                  {call.summary}
                </p>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Pagination */}
      {(hasMore || page > 1) && (
        <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-between">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page === 1}
            className="px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg disabled:opacity-50"
          >
            Previous
          </button>
          <span className="text-sm text-gray-500 dark:text-gray-400">
            Page {page}
          </span>
          <button
            onClick={() => setPage((p) => p + 1)}
            disabled={!hasMore}
            className="px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg disabled:opacity-50"
          >
            Next
          </button>
        </div>
      )}

      {/* Call Details Modal */}
      {selectedCall && (
        <CallDetailsModal
          call={selectedCall}
          onClose={() => setSelectedCall(null)}
          isLoading={isLoadingDetails}
          lang={lang}
          t={t}
        />
      )}
    </div>
  );
}

interface CallDetailsModalProps {
  call: CallDetails;
  onClose: () => void;
  isLoading: boolean;
  lang: "en" | "ar";
  t: (typeof translations)["en"];
}

function CallDetailsModal({
  call,
  onClose,
  isLoading,
  lang: _lang,
  t,
}: CallDetailsModalProps) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div
              className={`p-2 rounded-full ${
                call.direction === "inbound"
                  ? "bg-green-100 text-green-600"
                  : "bg-blue-100 text-blue-600"
              }`}
            >
              {call.direction === "inbound" ? (
                <PhoneIncoming className="h-5 w-5" />
              ) : (
                <PhoneOutgoing className="h-5 w-5" />
              )}
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                {call.direction === "inbound"
                  ? call.fromNumberFormatted
                  : call.toNumberFormatted}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t[call.direction as keyof typeof t]} • {call.status}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-6 w-6 animate-spin text-brand-500" />
            </div>
          ) : (
            <div className="space-y-6">
              {/* Stats Row */}
              <div className="grid grid-cols-3 gap-4">
                <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                  <div className="flex items-center gap-2 text-gray-500 dark:text-gray-400 text-sm mb-1">
                    <Clock className="h-4 w-4" />
                    {t.duration}
                  </div>
                  <div className="text-xl font-semibold text-gray-900 dark:text-white">
                    {call.durationSeconds
                      ? `${Math.floor(call.durationSeconds / 60)}:${(
                          call.durationSeconds % 60
                        )
                          .toString()
                          .padStart(2, "0")}`
                      : "0:00"}
                  </div>
                </div>

                {call.qualityScore !== null && (
                  <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                    <div className="flex items-center gap-2 text-gray-500 dark:text-gray-400 text-sm mb-1">
                      <TrendingUp className="h-4 w-4" />
                      {t.qualityScore}
                    </div>
                    <div className="text-xl font-semibold text-gray-900 dark:text-white">
                      {call.qualityScore}%
                    </div>
                  </div>
                )}

                {call.estimatedCost !== null && (
                  <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                    <div className="flex items-center gap-2 text-gray-500 dark:text-gray-400 text-sm mb-1">
                      💰 {t.estimatedCost}
                    </div>
                    <div className="text-xl font-semibold text-gray-900 dark:text-white">
                      ${call.estimatedCost.toFixed(2)}
                    </div>
                  </div>
                )}
              </div>

              {/* Actions Badges */}
              {(call.appointmentBooked || call.transferredToHuman) && (
                <div className="flex flex-wrap gap-2">
                  {call.appointmentBooked && (
                    <span className="px-3 py-1.5 bg-green-100 text-green-800 rounded-lg text-sm font-medium flex items-center gap-1">
                      📅 {t.appointmentBooked}
                    </span>
                  )}
                  {call.transferredToHuman && (
                    <span className="px-3 py-1.5 bg-yellow-100 text-yellow-800 rounded-lg text-sm font-medium flex items-center gap-1">
                      👤 {t.transferredToHuman}
                    </span>
                  )}
                </div>
              )}

              {/* Summary */}
              {call.summary && (
                <div>
                  <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-2">
                    <FileText className="h-4 w-4" />
                    {t.summary}
                  </h4>
                  <p className="text-gray-600 dark:text-gray-400 bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                    {call.summary}
                  </p>
                </div>
              )}

              {/* Topics */}
              {call.topics && call.topics.length > 0 && (
                <div>
                  <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    {t.topics}
                  </h4>
                  <div className="flex flex-wrap gap-2">
                    {call.topics.map((topic, i) => (
                      <span
                        key={i}
                        className="px-2 py-1 bg-brand-100 text-brand-800 rounded-full text-xs"
                      >
                        {topic}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* Transcript */}
              {call.transcript && call.transcript.length > 0 && (
                <div>
                  <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-2">
                    <User className="h-4 w-4" />
                    {t.transcript}
                  </h4>
                  <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4 space-y-3 max-h-64 overflow-y-auto">
                    {call.transcript.map((entry, i) => (
                      <div
                        key={i}
                        className={`flex gap-3 ${
                          entry.role === "assistant"
                            ? "justify-start"
                            : "justify-end"
                        }`}
                      >
                        <div
                          className={`max-w-[80%] rounded-lg px-4 py-2 ${
                            entry.role === "assistant"
                              ? "bg-white dark:bg-gray-600 text-gray-900 dark:text-white"
                              : "bg-brand-500 text-white"
                          }`}
                        >
                          <div className="text-xs opacity-70 mb-1">
                            {entry.role === "assistant" ? t.agent : t.caller}
                          </div>
                          <p className="text-sm">{entry.content}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Escalation Reason */}
              {call.escalationReason && (
                <div className="bg-yellow-50 dark:bg-yellow-900/20 rounded-lg p-4">
                  <h4 className="text-sm font-medium text-yellow-800 dark:text-yellow-300 mb-1">
                    {t.escalationReason}
                  </h4>
                  <p className="text-yellow-700 dark:text-yellow-400">
                    {call.escalationReason}
                  </p>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end">
          <button
            onClick={onClose}
            className="px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
          >
            {t.close}
          </button>
        </div>
      </div>
    </div>
  );
}

export default CallHistoryPanel;
