"use client";

import { useState, useEffect, useCallback } from "react";
import { QuotationForm } from "./QuotationForm";
// Using plain fetch — API endpoints bypass CSRF in development
import { PaymentStatusBadge } from "./PaymentStatusBadge";
import { OverduePenaltyIndicator } from "./OverduePenaltyIndicator";
import { RecordPaymentModal } from "./RecordPaymentModal";
import { QuotationDetailDrawer } from "./QuotationDetailDrawer";

const t = {
  en: {
    title: "Quotations",
    create: "New Quotation",
    search: "Search quotations...",
    all: "All",
    draft: "Draft",
    sent: "Sent",
    accepted: "Accepted",
    declined: "Declined",
    expired: "Expired",
    noQuotations: "No quotations yet",
    noQuotationsDesc: "Create your first quotation to get started.",
    number: "Number",
    titleCol: "Title",
    customer: "Customer",
    total: "Total",
    status: "Status",
    payment: "Payment",
    date: "Date",
    actions: "Actions",
    edit: "Edit",
    send: "Send",
    duplicate: "Duplicate",
    delete: "Delete",
    recordPayment: "Record Payment",
    copyLink: "Copy Link",
    viewDetails: "Details",
    loading: "Loading...",
    prev: "Previous",
    next: "Next",
    page: "Page",
    of: "of",
    linkCopied: "Portal link copied!",
    resend: "Resend",
    resending: "Sending...",
    paymentFilter: "Payment:",
    allPayments: "All",
    unpaid: "Unpaid",
    partial: "Partial",
    paid: "Paid",
    overdue: "Overdue",
  },
  ar: {
    title: "عروض الأسعار",
    create: "عرض سعر جديد",
    search: "البحث في عروض الأسعار...",
    all: "الكل",
    draft: "مسودة",
    sent: "مُرسل",
    accepted: "مقبول",
    declined: "مرفوض",
    expired: "منتهي",
    noQuotations: "لا توجد عروض أسعار بعد",
    noQuotationsDesc: "أنشئ أول عرض سعر للبدء.",
    number: "الرقم",
    titleCol: "العنوان",
    customer: "العميل",
    total: "الإجمالي",
    status: "الحالة",
    payment: "الدفع",
    date: "التاريخ",
    actions: "الإجراءات",
    edit: "تعديل",
    send: "إرسال",
    duplicate: "نسخ",
    delete: "حذف",
    recordPayment: "تسجيل دفعة",
    copyLink: "نسخ الرابط",
    viewDetails: "التفاصيل",
    loading: "جاري التحميل...",
    prev: "السابق",
    next: "التالي",
    page: "صفحة",
    of: "من",
    linkCopied: "تم نسخ رابط البوابة!",
    resend: "إعادة إرسال",
    resending: "جاري الإرسال...",
    paymentFilter: "الدفع:",
    allPayments: "الكل",
    unpaid: "غير مدفوع",
    partial: "جزئي",
    paid: "مدفوع",
    overdue: "متأخر",
  },
};

interface Quotation {
  id: string;
  quotationNumber: string;
  title: string;
  status: string;
  paymentStatus: string;
  total: number;
  amountPaid: number;
  penaltyAmount: number;
  dueDate: string | null;
  portalToken: string | null;
  currency: string;
  createdAt: string;
  customerId?: string | null;
  customer?: {
    id: string;
    name: string;
    phone?: string;
    email?: string | null;
  } | null;
  taxRate?: number;
  discountRate?: number;
  validUntil?: string | null;
  notes?: string | null;
  items: Array<{
    id: string;
    description: string;
    quantity: number;
    unitPrice: number;
    total: number;
  }>;
}

const statusColors: Record<string, string> = {
  DRAFT: "bg-gray-100 text-gray-700",
  SENT: "bg-blue-100 text-blue-700",
  VIEWED: "bg-purple-100 text-purple-700",
  ACCEPTED: "bg-green-100 text-green-700",
  DECLINED: "bg-red-100 text-red-700",
  EXPIRED: "bg-yellow-100 text-yellow-700",
  CANCELLED: "bg-gray-100 text-gray-500",
};

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

  const [quotations, setQuotations] = useState<Quotation[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingQuotation, setEditingQuotation] = useState<Quotation | null>(
    null,
  );
  const [filter, setFilter] = useState<string>("");
  const [paymentFilter, setPaymentFilter] = useState<string>("");
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  // Modal/Drawer state
  const [paymentModalQuotation, setPaymentModalQuotation] =
    useState<Quotation | null>(null);
  const [detailDrawerId, setDetailDrawerId] = useState<string | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [resendingId, setResendingId] = useState<string | null>(null);

  const fetchQuotations = useCallback(async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({ page: String(page), limit: "20" });
      if (filter) params.set("status", filter);
      if (paymentFilter) params.set("paymentStatus", paymentFilter);
      if (search) params.set("search", search);

      const res = await fetch(`/api/dashboard/quotations?${params}`);
      const data = await res.json();
      if (data.success) {
        // Filter out CANCELLED quotations — they appear in Trash tab
        const active = (data.quotations || []).filter(
          (q: Quotation) => q.status !== "CANCELLED",
        );
        setQuotations(active);
        setTotalPages(data.totalPages ?? 1);
      }
    } catch (err) {
      console.error("Failed to fetch quotations:", err);
    } finally {
      setLoading(false);
    }
  }, [page, filter, paymentFilter, search]);

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

  const handleEdit = async (q: Quotation) => {
    try {
      const res = await fetch(`/api/dashboard/quotations/${q.id}`, {
        credentials: "include",
      });
      if (res.ok) {
        const data = await res.json();
        if (data.success && data.quotation) {
          const full = data.quotation;
          setEditingQuotation({
            ...q,
            items: (full.items || []).map((item: Record<string, unknown>) => ({
              id: (item._id || item.id) as string,
              description: item.description as string,
              quantity: item.quantity as number,
              unitPrice: item.unitPrice as number,
              total: item.total as number,
            })),
            customer: full.customer
              ? {
                  id: (full.customer._id || full.customer.id) as string,
                  name: full.customer.name as string,
                  phone: full.customer.phone as string | undefined,
                  email: full.customer.email as string | null | undefined,
                }
              : q.customer,
          });
          return;
        }
      }
      // Fallback: open without items
      setEditingQuotation(q);
    } catch {
      setEditingQuotation(q);
    }
  };

  const apiCall = async (url: string, method: string) => {
    return fetch(url, {
      method,
      headers: { "Content-Type": "application/json" },
      credentials: "include",
    });
  };

  const handleSend = async (id: string) => {
    try {
      const res = await apiCall(`/api/dashboard/quotations/${id}/send`, "POST");
      if (res.ok) {
        fetchQuotations();
      } else {
        const data = await res.json().catch(() => ({}));
        alert((data as { error?: string }).error || "Failed to send");
      }
    } catch (err) {
      console.error("Failed to send:", err);
    }
  };

  const handleDuplicate = async (id: string) => {
    try {
      const res = await apiCall(`/api/dashboard/quotations/${id}/duplicate`, "POST");
      if (res.ok) fetchQuotations();
    } catch (err) {
      console.error("Failed to duplicate:", err);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm(isAr ? "هل أنت متأكد؟" : "Are you sure?")) return;
    try {
      const res = await apiCall(`/api/dashboard/quotations/${id}`, "DELETE");
      if (res.ok) fetchQuotations();
    } catch (err) {
      console.error("Failed to delete:", err);
    }
  };

  const handleResend = async (id: string) => {
    setResendingId(id);
    try {
      await apiCall(`/api/dashboard/quotations/${id}/send`, "POST");
      fetchQuotations();
    } catch (err) {
      console.error("Failed to resend:", err);
    } finally {
      setResendingId(null);
    }
  };

  const handleCopyPortalLink = (q: Quotation) => {
    if (!q.portalToken) return;
    const url = `${window.location.origin}/quotation/${q.portalToken}`;
    navigator.clipboard.writeText(url);
    setCopiedId(q.id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const handleFormClose = () => {
    setShowForm(false);
    setEditingQuotation(null);
    fetchQuotations();
  };

  const statusFilters = [
    "",
    "DRAFT",
    "SENT",
    "ACCEPTED",
    "DECLINED",
    "EXPIRED",
  ];
  const statusLabels: Record<string, string> = {
    "": labels.all,
    DRAFT: labels.draft,
    SENT: labels.sent,
    ACCEPTED: labels.accepted,
    DECLINED: labels.declined,
    EXPIRED: labels.expired,
  };

  const paymentFilters = ["", "UNPAID", "PARTIAL", "PAID", "OVERDUE"];
  const paymentLabels: Record<string, string> = {
    "": labels.allPayments,
    UNPAID: labels.unpaid,
    PARTIAL: labels.partial,
    PAID: labels.paid,
    OVERDUE: labels.overdue,
  };

  if (showForm || editingQuotation) {
    return (
      <QuotationForm
        lang={lang}
        quotation={editingQuotation}
        onClose={handleFormClose}
      />
    );
  }

  const getDaysOverdue = (q: Quotation) => {
    if (!q.dueDate || new Date(q.dueDate) >= new Date()) return 0;
    return Math.floor((Date.now() - new Date(q.dueDate).getTime()) / 86400000);
  };

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <h2 className="text-lg font-semibold text-gray-900">{labels.title}</h2>
        <button
          onClick={() => setShowForm(true)}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium"
        >
          + {labels.create}
        </button>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-3 flex-wrap">
        <input
          type="text"
          placeholder={labels.search}
          value={search}
          onChange={(e) => {
            setSearch(e.target.value);
            setPage(1);
          }}
          className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 w-64"
        />
        <div className="flex gap-1">
          {statusFilters.map((s) => (
            <button
              key={s}
              onClick={() => {
                setFilter(s);
                setPage(1);
              }}
              className={`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${
                filter === s
                  ? "bg-blue-100 text-blue-700"
                  : "bg-gray-100 text-gray-600 hover:bg-gray-200"
              }`}
            >
              {statusLabels[s]}
            </button>
          ))}
        </div>
      </div>

      {/* Payment Status Filters */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-xs text-gray-500 font-medium">
          {labels.paymentFilter}
        </span>
        <div className="flex gap-1">
          {paymentFilters.map((pf) => (
            <button
              key={pf}
              onClick={() => {
                setPaymentFilter(pf);
                setPage(1);
              }}
              className={`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${
                paymentFilter === pf
                  ? "bg-green-100 text-green-700"
                  : "bg-gray-100 text-gray-600 hover:bg-gray-200"
              }`}
            >
              {paymentLabels[pf]}
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      {loading ? (
        <div className="py-12 text-center text-gray-500">{labels.loading}</div>
      ) : quotations.length === 0 ? (
        <div className="py-12 text-center">
          <p className="text-gray-900 font-medium">{labels.noQuotations}</p>
          <p className="text-gray-500 text-sm mt-1">
            {labels.noQuotationsDesc}
          </p>
        </div>
      ) : (
        <>
          <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.status}
                  </th>
                  <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                    {labels.payment}
                  </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) => {
                  const daysOverdue = getDaysOverdue(q);
                  return (
                    <tr
                      key={q.id}
                      className="hover:bg-gray-50 cursor-pointer"
                      onClick={() => setDetailDrawerId(q.id)}
                    >
                      <td className="px-4 py-3 text-sm font-mono text-blue-600 hover:underline">
                        {q.quotationNumber}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-900">
                        <div>
                          {q.title}
                          {q.penaltyAmount > 0 && (
                            <div className="mt-1">
                              <OverduePenaltyIndicator
                                penaltyAmount={q.penaltyAmount}
                                currency={q.currency}
                                daysOverdue={daysOverdue}
                                lang={lang}
                              />
                            </div>
                          )}
                        </div>
                      </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">
                        <span
                          className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[q.status] || ""}`}
                        >
                          {q.status}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <PaymentStatusBadge
                          status={q.paymentStatus}
                          lang={lang}
                        />
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-500">
                        {new Date(q.createdAt).toLocaleDateString(
                          isAr ? "ar-QA" : "en-QA",
                        )}
                      </td>
                      <td
                        className="px-4 py-3"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <div className="flex gap-2 flex-wrap">
                          <button
                            onClick={() => handleEdit(q)}
                            className="text-xs text-blue-600 hover:underline"
                          >
                            {labels.edit}
                          </button>
                          {q.status !== "CANCELLED" && (
                            <button
                              onClick={() => handleSend(q.id)}
                              className="text-xs text-green-600 hover:underline"
                            >
                              {q.status === "DRAFT" ? labels.send : (isAr ? "إعادة إرسال" : "Resend")}
                            </button>
                          )}
                          <button
                            onClick={() => handleDuplicate(q.id)}
                            className="text-xs text-purple-600 hover:underline"
                          >
                            {labels.duplicate}
                          </button>
                          <button
                            onClick={() => setPaymentModalQuotation(q)}
                            className="text-xs text-emerald-600 hover:underline"
                          >
                            {labels.recordPayment}
                          </button>
                          {q.portalToken && (
                            <button
                              onClick={() => handleCopyPortalLink(q)}
                              className="text-xs text-indigo-600 hover:underline"
                            >
                              {copiedId === q.id
                                ? labels.linkCopied
                                : labels.copyLink}
                            </button>
                          )}
                          {/* Resend handled by Send button above */}
                          <button
                            onClick={() => setDetailDrawerId(q.id)}
                            className="text-xs text-gray-600 hover:underline"
                          >
                            {labels.viewDetails}
                          </button>
                          <button
                            onClick={() => handleDelete(q.id)}
                            className="text-xs text-red-600 hover:underline"
                          >
                            {labels.delete}
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-4">
              <button
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
                className="px-3 py-1.5 border border-gray-300 rounded text-sm disabled:opacity-50"
              >
                {labels.prev}
              </button>
              <span className="text-sm text-gray-600">
                {labels.page} {page} {labels.of} {totalPages}
              </span>
              <button
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
                className="px-3 py-1.5 border border-gray-300 rounded text-sm disabled:opacity-50"
              >
                {labels.next}
              </button>
            </div>
          )}
        </>
      )}

      {/* Record Payment Modal */}
      {paymentModalQuotation && (
        <RecordPaymentModal
          quotationId={paymentModalQuotation.id}
          quotationTotal={paymentModalQuotation.total}
          amountPaid={paymentModalQuotation.amountPaid}
          currency={paymentModalQuotation.currency}
          lang={lang}
          onClose={() => setPaymentModalQuotation(null)}
          onSuccess={() => {
            setPaymentModalQuotation(null);
            fetchQuotations();
          }}
        />
      )}

      {/* Detail Drawer */}
      {detailDrawerId && (
        <QuotationDetailDrawer
          quotationId={detailDrawerId}
          lang={lang}
          onClose={() => setDetailDrawerId(null)}
        />
      )}
    </div>
  );
}
