"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  FileText,
  RefreshCw,
  CheckCircle2,
  XCircle,
  Clock,
  Loader2,
  Database,
  AlertCircle,
} from "lucide-react";

interface KBDocument {
  documentId: string;
  documentName: string;
  syncStatus: string;
  lastSyncAt: string | null;
  syncError: string | null;
}

interface KBSyncSectionProps {
  lang: Lang;
}

function SyncStatusIcon({ status }: { status: string }) {
  switch (status) {
    case "synced":
      return <CheckCircle2 className="w-4 h-4 text-green-500" />;
    case "failed":
      return <XCircle className="w-4 h-4 text-red-500" />;
    case "pending":
      return <Clock className="w-4 h-4 text-amber-500" />;
    default:
      return <AlertCircle className="w-4 h-4 text-slate-400" />;
  }
}

export default function KBSyncSection({ lang }: KBSyncSectionProps) {
  const isAr = lang === "ar";
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);
  const [documents, setDocuments] = useState<KBDocument[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [syncResult, setSyncResult] = useState<{
    synced: number;
    failed: number;
  } | null>(null);

  const fetchStatus = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/voice-agent/kb-sync", {
        credentials: "include",
      });
      if (!res.ok) throw new Error("Failed to load");
      const data = await res.json();
      if (data.success) {
        setDocuments(data.documents || []);
      }
    } catch {
      setError(isAr ? "فشل في تحميل الحالة" : "Failed to load sync status");
    } finally {
      setLoading(false);
    }
  }, [isAr]);

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

  const handleSync = async () => {
    setSyncing(true);
    setSyncResult(null);
    setError(null);

    try {
      const res = await fetchWithCSRF("/api/voice-agent/kb-sync", {
        method: "POST",
      });

      if (!res.ok) {
        const data = await res.json().catch(() => null);
        throw new Error(data?.error || "Sync failed");
      }

      const data = await res.json();
      setSyncResult({ synced: data.synced || 0, failed: data.failed || 0 });
      // Refresh the list
      await fetchStatus();
    } catch (err: unknown) {
      setError(
        err instanceof Error
          ? err.message
          : isAr
            ? "فشل في المزامنة"
            : "Sync failed",
      );
    } finally {
      setSyncing(false);
    }
  };

  const syncedCount = documents.filter((d) => d.syncStatus === "synced").length;
  const failedCount = documents.filter((d) => d.syncStatus === "failed").length;
  const pendingCount = documents.filter(
    (d) => d.syncStatus !== "synced" && d.syncStatus !== "failed",
  ).length;

  return (
    <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-amber-50 flex items-center justify-center">
            <Database className="w-5 h-5 text-amber-600" />
          </div>
          <div>
            <h3 className="font-semibold text-slate-900">
              {isAr ? "مزامنة قاعدة المعرفة" : "Knowledge Base Sync"}
            </h3>
            <p className="text-xs text-slate-400">
              {isAr
                ? "مزامنة مستندات عملك مع الوكيل الصوتي"
                : "Sync your business documents with the voice agent"}
            </p>
          </div>
        </div>
        <button
          onClick={handleSync}
          disabled={syncing || loading}
          className="inline-flex items-center gap-2 px-4 py-2.5 bg-brand-green hover:bg-brand-greenHover text-white rounded-xl text-sm font-medium transition-colors disabled:opacity-50"
        >
          {syncing ? (
            <Loader2 className="w-4 h-4 animate-spin" />
          ) : (
            <RefreshCw className="w-4 h-4" />
          )}
          {syncing
            ? isAr
              ? "جاري المزامنة..."
              : "Syncing..."
            : isAr
              ? "مزامنة الكل"
              : "Sync All"}
        </button>
      </div>

      {/* Summary badges */}
      {!loading && documents.length > 0 && (
        <div className="flex items-center gap-3 mb-4">
          <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-green-50 text-green-700 text-xs font-medium">
            <CheckCircle2 className="w-3 h-3" />
            {syncedCount} {isAr ? "متزامن" : "synced"}
          </span>
          {failedCount > 0 && (
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-red-50 text-red-700 text-xs font-medium">
              <XCircle className="w-3 h-3" />
              {failedCount} {isAr ? "فاشل" : "failed"}
            </span>
          )}
          {pendingCount > 0 && (
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-amber-50 text-amber-700 text-xs font-medium">
              <Clock className="w-3 h-3" />
              {pendingCount} {isAr ? "معلّق" : "pending"}
            </span>
          )}
        </div>
      )}

      {/* Sync result banner */}
      {syncResult && (
        <div className="mb-4 p-3 rounded-xl bg-green-50 border border-green-200 text-green-700 text-sm">
          {isAr
            ? `تمت المزامنة: ${syncResult.synced} مستند، فشل: ${syncResult.failed}`
            : `Synced: ${syncResult.synced} documents, Failed: ${syncResult.failed}`}
        </div>
      )}

      {error && (
        <div className="mb-4 p-3 rounded-xl bg-red-50 border border-red-200 text-red-600 text-sm">
          {error}
        </div>
      )}

      {/* Documents list */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-6 h-6 animate-spin text-brand-green" />
        </div>
      ) : documents.length === 0 ? (
        <div className="text-center py-12">
          <FileText className="w-10 h-10 text-slate-200 mx-auto mb-3" />
          <p className="text-sm text-slate-400">
            {isAr
              ? "لا توجد مستندات في قاعدة المعرفة"
              : "No documents in knowledge base"}
          </p>
          <p className="text-xs text-slate-300 mt-1">
            {isAr
              ? "ارفع مستندات من صفحة قاعدة المعرفة أولاً"
              : "Upload documents from the Knowledge Base page first"}
          </p>
        </div>
      ) : (
        <div className="space-y-2">
          {documents.map((doc) => (
            <div
              key={doc.documentId}
              className="flex items-center justify-between p-3 rounded-xl bg-slate-50"
            >
              <div className="flex items-center gap-3 min-w-0">
                <SyncStatusIcon status={doc.syncStatus} />
                <div className="min-w-0">
                  <p className="text-sm font-medium text-slate-800 truncate">
                    {doc.documentName}
                  </p>
                  {doc.syncError && (
                    <p className="text-[11px] text-red-400 truncate">
                      {doc.syncError}
                    </p>
                  )}
                </div>
              </div>
              <div className="text-xs text-slate-400 flex-shrink-0 ml-4">
                {doc.lastSyncAt
                  ? new Date(doc.lastSyncAt).toLocaleDateString(
                      isAr ? "ar-QA" : "en-US",
                      {
                        month: "short",
                        day: "numeric",
                        hour: "2-digit",
                        minute: "2-digit",
                      },
                    )
                  : isAr
                    ? "لم تتم المزامنة"
                    : "Not synced"}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
