"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import {
  Search,
  ChevronLeft,
  ChevronRight,
  Loader2,
  Phone,
  User,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Filter,
  Clock,
} from "lucide-react";

interface ConversationRow {
  id: string;
  customerPhone: string | null;
  customerName: string | null;
  status: string;
  duration: number;
  outcome: string;
  bookingCreated: boolean;
  sentiment: string;
  escalated: boolean;
  createdAt: string;
}

interface Pagination {
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

interface CallsTableProps {
  lang: Lang;
  onSelectCall: (callId: string) => void;
}

const STATUS_FILTERS = [
  { value: "", en: "All", ar: "الكل" },
  { value: "resolved", en: "Completed", ar: "مكتملة" },
  { value: "active", en: "Active", ar: "نشطة" },
  { value: "failed", en: "Failed", ar: "فاشلة" },
];

function formatDuration(seconds: number): string {
  if (seconds < 60) return `${seconds}s`;
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs.toString().padStart(2, "0")}`;
}

function SentimentBadge({
  sentiment,
  isAr,
}: {
  sentiment: string;
  isAr: boolean;
}) {
  const styles: Record<string, string> = {
    positive: "bg-green-50 text-green-700",
    neutral: "bg-slate-50 text-slate-600",
    negative: "bg-red-50 text-red-700",
  };
  const labels: Record<string, { en: string; ar: string }> = {
    positive: { en: "Positive", ar: "إيجابي" },
    neutral: { en: "Neutral", ar: "محايد" },
    negative: { en: "Negative", ar: "سلبي" },
  };

  return (
    <span
      className={`inline-flex px-2 py-0.5 rounded-full text-[10px] font-medium ${styles[sentiment] || styles.neutral}`}
    >
      {labels[sentiment]?.[isAr ? "ar" : "en"] || sentiment}
    </span>
  );
}

export default function CallsTable({ lang, onSelectCall }: CallsTableProps) {
  const isAr = lang === "ar";
  const [loading, setLoading] = useState(true);
  const [conversations, setConversations] = useState<ConversationRow[]>([]);
  const [pagination, setPagination] = useState<Pagination>({
    page: 1,
    pageSize: 20,
    total: 0,
    totalPages: 0,
  });
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("");

  const fetchConversations = useCallback(
    async (page: number) => {
      setLoading(true);
      try {
        const params = new URLSearchParams({
          page: String(page),
          pageSize: "20",
        });
        if (statusFilter) params.set("status", statusFilter);
        if (search) params.set("search", search);

        const res = await fetch(`/api/voice-agent/conversations?${params}`, {
          credentials: "include",
        });

        if (!res.ok) throw new Error("Failed to load");

        const data = await res.json();
        if (data.success) {
          setConversations(data.conversations);
          setPagination(data.pagination);
        }
      } catch {
        // Keep existing state on error
      } finally {
        setLoading(false);
      }
    },
    [search, statusFilter],
  );

  useEffect(() => {
    fetchConversations(1);
  }, [fetchConversations]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchConversations(1);
  };

  return (
    <div className="bg-white rounded-2xl border border-slate-200 shadow-sm">
      {/* Header / Filters */}
      <div className="p-5 border-b border-slate-100">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <h3 className="font-semibold text-slate-900">
            {isAr ? "سجل المكالمات" : "Call History"}
            {pagination.total > 0 && (
              <span className="text-sm font-normal text-slate-400 ml-2">
                ({pagination.total})
              </span>
            )}
          </h3>
          <div className="flex items-center gap-2">
            {/* Status filter */}
            <div className="flex items-center gap-1 bg-slate-50 rounded-xl p-1">
              <Filter className="w-3.5 h-3.5 text-slate-400 ml-2" />
              {STATUS_FILTERS.map((f) => (
                <button
                  key={f.value}
                  onClick={() => setStatusFilter(f.value)}
                  className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                    statusFilter === f.value
                      ? "bg-white text-slate-800 shadow-sm"
                      : "text-slate-500 hover:text-slate-700"
                  }`}
                >
                  {isAr ? f.ar : f.en}
                </button>
              ))}
            </div>

            {/* Search */}
            <form onSubmit={handleSearch} className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder={isAr ? "بحث..." : "Search..."}
                className="pl-9 pr-3 py-2 rounded-xl border border-slate-200 text-sm focus:border-brand-green focus:ring-1 focus:ring-brand-green outline-none w-48"
              />
            </form>
          </div>
        </div>
      </div>

      {/* Table */}
      {loading ? (
        <div className="flex items-center justify-center py-16">
          <Loader2 className="w-6 h-6 animate-spin text-brand-green" />
          <span className="ml-2 text-sm text-slate-500">
            {isAr ? "جاري التحميل..." : "Loading..."}
          </span>
        </div>
      ) : conversations.length === 0 ? (
        <div className="text-center py-16">
          <Phone className="w-10 h-10 text-slate-200 mx-auto mb-3" />
          <p className="text-sm text-slate-400">
            {isAr ? "لا توجد مكالمات" : "No calls found"}
          </p>
        </div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100">
                <th className="text-start text-xs font-medium text-slate-500 px-5 py-3">
                  {isAr ? "المتصل" : "Caller"}
                </th>
                <th className="text-start text-xs font-medium text-slate-500 px-3 py-3">
                  {isAr ? "الحالة" : "Status"}
                </th>
                <th className="text-start text-xs font-medium text-slate-500 px-3 py-3">
                  {isAr ? "المدة" : "Duration"}
                </th>
                <th className="text-start text-xs font-medium text-slate-500 px-3 py-3">
                  {isAr ? "المشاعر" : "Sentiment"}
                </th>
                <th className="text-start text-xs font-medium text-slate-500 px-3 py-3">
                  {isAr ? "النتيجة" : "Outcome"}
                </th>
                <th className="text-start text-xs font-medium text-slate-500 px-3 py-3">
                  {isAr ? "التاريخ" : "Date"}
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {conversations.map((conv) => (
                <tr
                  key={conv.id}
                  onClick={() => onSelectCall(conv.id)}
                  className="hover:bg-slate-50 cursor-pointer transition-colors"
                >
                  <td className="px-5 py-3">
                    <div className="flex items-center gap-2.5">
                      <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center flex-shrink-0">
                        <User className="w-3.5 h-3.5 text-slate-500" />
                      </div>
                      <div>
                        <p className="text-sm font-medium text-slate-800 truncate max-w-[160px]">
                          {conv.customerName ||
                            conv.customerPhone ||
                            (isAr ? "مجهول" : "Unknown")}
                        </p>
                        {conv.customerName && conv.customerPhone && (
                          <p className="text-[11px] text-slate-400 font-mono">
                            {conv.customerPhone}
                          </p>
                        )}
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-3">
                    <span
                      className={`inline-flex items-center gap-1 text-xs font-medium ${
                        conv.status === "resolved"
                          ? "text-green-600"
                          : conv.status === "failed"
                            ? "text-red-500"
                            : "text-amber-600"
                      }`}
                    >
                      {conv.status === "resolved" ? (
                        <CheckCircle2 className="w-3.5 h-3.5" />
                      ) : conv.status === "failed" ? (
                        <XCircle className="w-3.5 h-3.5" />
                      ) : (
                        <Clock className="w-3.5 h-3.5" />
                      )}
                      {conv.status === "resolved"
                        ? isAr
                          ? "مكتمل"
                          : "Completed"
                        : conv.status === "failed"
                          ? isAr
                            ? "فشل"
                            : "Failed"
                          : isAr
                            ? "نشط"
                            : "Active"}
                    </span>
                  </td>
                  <td className="px-3 py-3 text-sm text-slate-600 font-mono">
                    {formatDuration(conv.duration)}
                  </td>
                  <td className="px-3 py-3">
                    <SentimentBadge sentiment={conv.sentiment} isAr={isAr} />
                  </td>
                  <td className="px-3 py-3">
                    <div className="flex items-center gap-1.5">
                      {conv.bookingCreated && (
                        <span className="px-2 py-0.5 rounded-full bg-brand-green/10 text-brand-green text-[10px] font-medium">
                          {isAr ? "محجوز" : "Booked"}
                        </span>
                      )}
                      {conv.escalated && (
                        <span className="px-2 py-0.5 rounded-full bg-amber-50 text-amber-700 text-[10px] font-medium flex items-center gap-0.5">
                          <AlertTriangle className="w-2.5 h-2.5" />
                          {isAr ? "تصعيد" : "Escalated"}
                        </span>
                      )}
                      {!conv.bookingCreated && !conv.escalated && (
                        <span className="text-xs text-slate-400">-</span>
                      )}
                    </div>
                  </td>
                  <td className="px-3 py-3 text-xs text-slate-500">
                    {new Date(conv.createdAt).toLocaleDateString(
                      isAr ? "ar-QA" : "en-US",
                      {
                        month: "short",
                        day: "numeric",
                        hour: "2-digit",
                        minute: "2-digit",
                      },
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Pagination */}
      {pagination.totalPages > 1 && (
        <div className="flex items-center justify-between px-5 py-3 border-t border-slate-100">
          <span className="text-xs text-slate-400">
            {isAr
              ? `صفحة ${pagination.page} من ${pagination.totalPages}`
              : `Page ${pagination.page} of ${pagination.totalPages}`}
          </span>
          <div className="flex items-center gap-1">
            <button
              onClick={() => fetchConversations(pagination.page - 1)}
              disabled={pagination.page <= 1}
              className="p-2 rounded-lg hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
            >
              <ChevronLeft className="w-4 h-4 text-slate-600" />
            </button>
            <button
              onClick={() => fetchConversations(pagination.page + 1)}
              disabled={pagination.page >= pagination.totalPages}
              className="p-2 rounded-lg hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
            >
              <ChevronRight className="w-4 h-4 text-slate-600" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
