"use client";

import { useState, useEffect } from "react";
import { PaymentStatusBadge } from "./PaymentStatusBadge";
import { PaymentHistorySection } from "./PaymentHistorySection";
import { OverduePenaltyIndicator } from "./OverduePenaltyIndicator";

const t = {
  en: {
    loading: "Loading...",
    error: "Failed to load details",
    quotation: "Quotation Details",
    number: "Number",
    title: "Title",
    status: "Status",
    paymentStatus: "Payment",
    customer: "Customer",
    date: "Created",
    validUntil: "Valid Until",
    dueDate: "Due Date",
    subtotal: "Subtotal",
    discount: "Discount",
    tax: "Tax",
    penalty: "Penalty",
    total: "Total",
    amountPaid: "Paid",
    remaining: "Remaining",
    items: "Line Items",
    description: "Description",
    qty: "Qty",
    unitPrice: "Price",
    itemTotal: "Total",
    notes: "Notes",
    close: "Close",
    penalties: "Penalty History",
    penaltyDate: "Applied",
    penaltyAmount: "Amount",
    penaltyDays: "Days Overdue",
  },
  ar: {
    loading: "جاري التحميل...",
    error: "فشل في تحميل التفاصيل",
    quotation: "تفاصيل عرض السعر",
    number: "الرقم",
    title: "العنوان",
    status: "الحالة",
    paymentStatus: "الدفع",
    customer: "العميل",
    date: "التاريخ",
    validUntil: "صالح حتى",
    dueDate: "تاريخ الاستحقاق",
    subtotal: "المجموع الفرعي",
    discount: "الخصم",
    tax: "الضريبة",
    penalty: "الغرامة",
    total: "الإجمالي",
    amountPaid: "المدفوع",
    remaining: "المتبقي",
    items: "البنود",
    description: "الوصف",
    qty: "الكمية",
    unitPrice: "السعر",
    itemTotal: "الإجمالي",
    notes: "ملاحظات",
    close: "إغلاق",
    penalties: "سجل الغرامات",
    penaltyDate: "التطبيق",
    penaltyAmount: "المبلغ",
    penaltyDays: "أيام التأخير",
  },
};

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",
};

interface QuotationDetailDrawerProps {
  quotationId: string;
  lang: string;
  onClose: () => void;
}

interface QuotationDetail {
  id: string;
  quotationNumber: string;
  title: string;
  status: string;
  paymentStatus: string;
  currency: string;
  subtotal: number;
  taxRate: number;
  taxAmount: number;
  discountRate: number;
  discountAmount: number;
  total: number;
  amountPaid: number;
  penaltyAmount: number;
  dueDate: string | null;
  validUntil: string | null;
  notes: string | null;
  createdAt: string;
  customer: { name: string; email?: string } | null;
  items: Array<{
    id: string;
    description: string;
    quantity: number;
    unitPrice: number;
    total: number;
  }>;
  payments: Array<{
    id: string;
    amount: number;
    currency: string;
    method: string;
    reference?: string | null;
    paidAt: string;
  }>;
  penalties: Array<{
    id: string;
    amount: number;
    daysOverdue: number;
    appliedAt: string;
  }>;
}

export function QuotationDetailDrawer({
  quotationId,
  lang,
  onClose,
}: QuotationDetailDrawerProps) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;
  const [data, setData] = useState<QuotationDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    let cancelled = false;
    const fetchData = async () => {
      setData(null);
      setError(false);
      setLoading(true);
      try {
        const res = await fetch(
          `/api/dashboard/quotations/${quotationId}?include=payments,penalties`,
        );
        const json = await res.json();
        if (cancelled) return;
        if (json.success) {
          setData(json.quotation);
        } else {
          setError(true);
        }
      } catch {
        if (!cancelled) setError(true);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };
    fetchData();
    return () => {
      cancelled = true;
    };
  }, [quotationId]);

  const formatDate = (dateStr: string) =>
    new Date(dateStr).toLocaleDateString(isAr ? "ar-QA" : "en-QA");

  const remaining = data
    ? data.total + (data.penaltyAmount ?? 0) - (data.amountPaid ?? 0)
    : 0;

  const daysOverdue =
    data?.dueDate && new Date(data.dueDate) < new Date()
      ? Math.floor((Date.now() - new Date(data.dueDate).getTime()) / 86400000)
      : 0;

  return (
    <>
      {/* Backdrop */}
      <div className="fixed inset-0 bg-black/30 z-40" onClick={onClose} />

      {/* Drawer */}
      <div
        dir={isAr ? "rtl" : "ltr"}
        className={`fixed top-0 ${isAr ? "left-0" : "right-0"} h-full w-full max-w-lg bg-white shadow-xl z-50 overflow-y-auto`}
      >
        {/* Header */}
        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between z-10">
          <h2 className="text-lg font-semibold text-gray-900">
            {labels.quotation}
          </h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 text-xl"
          >
            &times;
          </button>
        </div>

        <div className="p-6">
          {loading && (
            <div className="text-center py-12 text-gray-500">
              {labels.loading}
            </div>
          )}

          {error && (
            <div className="text-center py-12 text-red-500">{labels.error}</div>
          )}

          {data && (
            <div className="space-y-6">
              {/* Meta */}
              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="text-sm text-gray-500">{labels.number}</span>
                  <span className="text-sm font-mono font-medium">
                    {data.quotationNumber}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-sm text-gray-500">{labels.title}</span>
                  <span className="text-sm font-medium">{data.title}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-gray-500">{labels.status}</span>
                  <span
                    className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[data.status] || ""}`}
                  >
                    {data.status}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-gray-500">
                    {labels.paymentStatus}
                  </span>
                  <PaymentStatusBadge status={data.paymentStatus} lang={lang} />
                </div>
                {data.customer && (
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-500">
                      {labels.customer}
                    </span>
                    <span className="text-sm">{data.customer.name}</span>
                  </div>
                )}
                <div className="flex justify-between">
                  <span className="text-sm text-gray-500">{labels.date}</span>
                  <span className="text-sm">{formatDate(data.createdAt)}</span>
                </div>
                {data.validUntil && (
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-500">
                      {labels.validUntil}
                    </span>
                    <span className="text-sm">
                      {formatDate(data.validUntil)}
                    </span>
                  </div>
                )}
                {data.dueDate && (
                  <div className="flex justify-between">
                    <span className="text-sm text-gray-500">
                      {labels.dueDate}
                    </span>
                    <span
                      className={`text-sm ${daysOverdue > 0 ? "text-red-600 font-medium" : ""}`}
                    >
                      {formatDate(data.dueDate)}
                    </span>
                  </div>
                )}
              </div>

              {/* Penalty indicator */}
              {(data.penaltyAmount ?? 0) > 0 && (
                <OverduePenaltyIndicator
                  penaltyAmount={data.penaltyAmount}
                  currency={data.currency}
                  daysOverdue={daysOverdue}
                  lang={lang}
                />
              )}

              {/* Items */}
              <div>
                <h3 className="text-sm font-semibold text-gray-900 mb-2">
                  {labels.items}
                </h3>
                <div className="border border-gray-200 rounded-lg overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="text-start px-3 py-2 text-xs text-gray-500">
                          {labels.description}
                        </th>
                        <th className="text-center px-2 py-2 text-xs text-gray-500">
                          {labels.qty}
                        </th>
                        <th className="text-end px-2 py-2 text-xs text-gray-500">
                          {labels.unitPrice}
                        </th>
                        <th className="text-end px-3 py-2 text-xs text-gray-500">
                          {labels.itemTotal}
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {data.items.map((item) => (
                        <tr key={item.id}>
                          <td className="px-3 py-2 text-gray-900">
                            {item.description}
                          </td>
                          <td className="px-2 py-2 text-center text-gray-500">
                            {item.quantity}
                          </td>
                          <td className="px-2 py-2 text-end text-gray-500">
                            {item.unitPrice.toLocaleString()}
                          </td>
                          <td className="px-3 py-2 text-end font-medium">
                            {item.total.toLocaleString()}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Totals */}
              <div className="border-t pt-4 space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-500">{labels.subtotal}</span>
                  <span>
                    {data.currency} {data.subtotal.toLocaleString()}
                  </span>
                </div>
                {data.discountAmount > 0 && (
                  <div className="flex justify-between text-sm text-red-600">
                    <span>
                      {labels.discount} ({data.discountRate}%)
                    </span>
                    <span>-{data.discountAmount.toLocaleString()}</span>
                  </div>
                )}
                {data.taxAmount > 0 && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-500">
                      {labels.tax} ({data.taxRate}%)
                    </span>
                    <span>{data.taxAmount.toLocaleString()}</span>
                  </div>
                )}
                {(data.penaltyAmount ?? 0) > 0 && (
                  <div className="flex justify-between text-sm text-red-600 font-medium">
                    <span>{labels.penalty}</span>
                    <span>+{(data.penaltyAmount ?? 0).toLocaleString()}</span>
                  </div>
                )}
                <div className="flex justify-between font-semibold pt-2 border-t">
                  <span>{labels.total}</span>
                  <span>
                    {data.currency}{" "}
                    {(data.total + (data.penaltyAmount ?? 0)).toLocaleString()}
                  </span>
                </div>
                {(data.amountPaid ?? 0) > 0 && (
                  <>
                    <div className="flex justify-between text-sm text-green-600">
                      <span>{labels.amountPaid}</span>
                      <span>-{data.amountPaid.toLocaleString()}</span>
                    </div>
                    <div className="flex justify-between text-sm font-semibold">
                      <span>{labels.remaining}</span>
                      <span>
                        {data.currency} {remaining.toLocaleString()}
                      </span>
                    </div>
                  </>
                )}
              </div>

              {/* Notes */}
              {data.notes && (
                <div className="bg-gray-50 rounded-lg p-4">
                  <h4 className="text-xs text-gray-500 uppercase tracking-wider mb-1">
                    {labels.notes}
                  </h4>
                  <p className="text-sm text-gray-700 whitespace-pre-wrap">
                    {data.notes}
                  </p>
                </div>
              )}

              {/* Payment History */}
              {(data.payments?.length ?? 0) > 0 && (
                <PaymentHistorySection
                  payments={data.payments}
                  currency={data.currency}
                  lang={lang}
                />
              )}

              {/* Penalty History */}
              {data.penalties && data.penalties.length > 0 && (
                <div>
                  <h4 className="text-sm font-semibold text-gray-900 mb-2">
                    {labels.penalties}
                  </h4>
                  <div className="space-y-1">
                    {data.penalties.map((p) => (
                      <div
                        key={p.id}
                        className="flex items-center justify-between py-2 px-3 bg-red-50 rounded text-xs"
                      >
                        <div className="flex gap-3">
                          <span className="text-red-700 font-medium">
                            +{data.currency} {p.amount.toLocaleString()}
                          </span>
                          <span className="text-red-500">
                            {p.daysOverdue} {labels.penaltyDays}
                          </span>
                        </div>
                        <span className="text-red-400">
                          {formatDate(p.appliedAt)}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </>
  );
}
