"use client";

import { useState, useEffect, useCallback } from "react";

const t = {
  en: {
    title: "Trash",
    empty: "No deleted quotations",
    emptyDesc: "Quotations you delete will appear here.",
    number: "Number",
    titleCol: "Title",
    customer: "Customer",
    total: "Total",
    date: "Deleted",
    actions: "Actions",
    restore: "Restore",
    deletePermanently: "Delete Forever",
    confirmPermanent:
      "This will permanently delete this quotation. This cannot be undone. Are you sure?",
    restoring: "Restoring...",
    deleting: "Deleting...",
    loading: "Loading...",
  },
  ar: {
    title: "المحذوفات",
    empty: "لا توجد عروض أسعار محذوفة",
    emptyDesc: "عروض الأسعار التي تحذفها ستظهر هنا.",
    number: "الرقم",
    titleCol: "العنوان",
    customer: "العميل",
    total: "الإجمالي",
    date: "تاريخ الحذف",
    actions: "الإجراءات",
    restore: "استعادة",
    deletePermanently: "حذف نهائي",
    confirmPermanent:
      "سيتم حذف عرض السعر نهائياً. لا يمكن التراجع عن هذا الإجراء. هل أنت متأكد؟",
    restoring: "جاري الاستعادة...",
    deleting: "جاري الحذف...",
    loading: "جاري التحميل...",
  },
};

interface TrashQuotation {
  id: string;
  quotationNumber: string;
  title: string;
  total: number;
  currency: string;
  updatedAt: string | number;
  customer?: {
    name: string;
  } | null;
}

export function TrashQuotationsList({ lang }: { lang: string }) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;

  const [quotations, setQuotations] = useState<TrashQuotation[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionId, setActionId] = useState<string | null>(null);

  const fetchTrash = useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch(
        "/api/dashboard/quotations?status=CANCELLED",
      );
      const data = await res.json();
      if (data.success) {
        setQuotations(
          (data.quotations || []).map((q: Record<string, unknown>) => ({
            ...q,
            id: q._id || q.id,
          })),
        );
      }
    } catch (err) {
      console.error("Failed to fetch trash quotations:", err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleRestore = async (id: string) => {
    setActionId(id);
    try {
      const res = await fetch(`/api/dashboard/quotations/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ status: "DRAFT" }),
      });
      if (res.ok) {
        fetchTrash();
      }
    } catch (err) {
      console.error("Failed to restore quotation:", err);
    } finally {
      setActionId(null);
    }
  };

  const handlePermanentDelete = async (id: string) => {
    if (!confirm(labels.confirmPermanent)) return;
    setActionId(id);
    try {
      const res = await fetch(
        `/api/dashboard/quotations/${id}?permanent=true`,
        {
          method: "DELETE",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
        },
      );
      if (res.ok) {
        fetchTrash();
      }
    } catch (err) {
      console.error("Failed to permanently delete quotation:", err);
    } finally {
      setActionId(null);
    }
  };

  const formatDate = (d: string | number) => {
    const date = typeof d === "number" ? new Date(d) : new Date(d);
    return date.toLocaleDateString(isAr ? "ar-QA" : "en-QA");
  };

  if (loading) {
    return (
      <div className="py-12 text-center text-gray-500">{labels.loading}</div>
    );
  }

  if (quotations.length === 0) {
    return (
      <div className="py-12 text-center">
        <div className="rounded-full bg-gray-100 p-4 mb-4 mx-auto w-fit">
          <svg
            className="w-10 h-10 text-gray-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={1.5}
              d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
            />
          </svg>
        </div>
        <p className="text-gray-900 font-medium">{labels.empty}</p>
        <p className="text-gray-500 text-sm mt-1">{labels.emptyDesc}</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <h2 className="text-lg font-semibold text-gray-900">{labels.title}</h2>

      <div className="overflow-x-auto border border-gray-200 rounded-lg">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.number}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.titleCol}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.customer}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.total}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.date}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.actions}
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {quotations.map((q) => (
              <tr key={q.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 text-sm font-mono text-gray-600">
                  {q.quotationNumber}
                </td>
                <td className="px-4 py-3 text-sm text-gray-900">
                  {q.title}
                </td>
                <td className="px-4 py-3 text-sm text-gray-500">
                  {q.customer?.name || "—"}
                </td>
                <td className="px-4 py-3 text-sm font-medium text-gray-900">
                  {q.currency} {q.total.toLocaleString()}
                </td>
                <td className="px-4 py-3 text-sm text-gray-500">
                  {formatDate(q.updatedAt)}
                </td>
                <td className="px-4 py-3">
                  <div className="flex gap-3">
                    <button
                      onClick={() => handleRestore(q.id)}
                      disabled={actionId === q.id}
                      className="text-xs text-blue-600 hover:underline disabled:opacity-50"
                    >
                      {actionId === q.id ? labels.restoring : labels.restore}
                    </button>
                    <button
                      onClick={() => handlePermanentDelete(q.id)}
                      disabled={actionId === q.id}
                      className="text-xs text-red-600 hover:underline disabled:opacity-50"
                    >
                      {actionId === q.id
                        ? labels.deleting
                        : labels.deletePermanently}
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
