"use client";

import { useState, useEffect } from "react";

const t = {
  en: {
    loading: "Loading quotation...",
    notFound: "Quotation Not Found",
    notFoundDesc: "This quotation link is invalid or has expired.",
    quotation: "Quotation",
    date: "Date",
    validUntil: "Valid Until",
    dueDate: "Due Date",
    billTo: "Bill To",
    item: "Item",
    qty: "Qty",
    unitPrice: "Unit Price",
    total: "Total",
    subtotal: "Subtotal",
    discount: "Discount",
    tax: "Tax",
    penalty: "Late Penalty",
    grandTotal: "Grand Total",
    status: "Status",
    paymentStatus: "Payment Status",
    amountPaid: "Amount Paid",
    remaining: "Remaining Balance",
    accept: "Accept Quotation",
    decline: "Decline",
    payNow: "Pay Now",
    accepted: "Accepted",
    declined: "Declined",
    expired: "Expired",
    cancelled: "Cancelled",
    declineReason: "Reason for declining (optional)",
    declineConfirm: "Confirm Decline",
    cancel: "Cancel",
    paymentHistory: "Payment History",
    method: "Method",
    reference: "Reference",
    paidOn: "Paid On",
    amount: "Amount",
    processing: "Processing...",
    error: "Something went wrong. Please try again.",
    notes: "Notes",
    daysOverdue: "days overdue",
    UNPAID: "Unpaid",
    PARTIAL: "Partially Paid",
    PAID: "Paid",
    OVERDUE: "Overdue",
    DRAFT: "Draft",
    SENT: "Sent",
    VIEWED: "Viewed",
    ACCEPTED: "Accepted",
    DECLINED: "Declined",
    EXPIRED: "Expired",
    CANCELLED: "Cancelled",
    STRIPE: "Card",
    MANUAL_CASH: "Cash",
    MANUAL_BANK_TRANSFER: "Bank Transfer",
    MANUAL_CHECK: "Check",
    MANUAL_OTHER: "Other",
    poweredBy: "Powered by Mawidi",
  },
  ar: {
    loading: "جاري تحميل عرض السعر...",
    notFound: "عرض السعر غير موجود",
    notFoundDesc: "هذا الرابط غير صالح أو منتهي الصلاحية.",
    quotation: "عرض سعر",
    date: "التاريخ",
    validUntil: "صالح حتى",
    dueDate: "تاريخ الاستحقاق",
    billTo: "فاتورة إلى",
    item: "البند",
    qty: "الكمية",
    unitPrice: "سعر الوحدة",
    total: "الإجمالي",
    subtotal: "المجموع الفرعي",
    discount: "الخصم",
    tax: "الضريبة",
    penalty: "غرامة التأخير",
    grandTotal: "المجموع الكلي",
    status: "الحالة",
    paymentStatus: "حالة الدفع",
    amountPaid: "المبلغ المدفوع",
    remaining: "الرصيد المتبقي",
    accept: "قبول عرض السعر",
    decline: "رفض",
    payNow: "ادفع الآن",
    accepted: "مقبول",
    declined: "مرفوض",
    expired: "منتهي",
    cancelled: "ملغي",
    declineReason: "سبب الرفض (اختياري)",
    declineConfirm: "تأكيد الرفض",
    cancel: "إلغاء",
    paymentHistory: "سجل المدفوعات",
    method: "الطريقة",
    reference: "المرجع",
    paidOn: "تاريخ الدفع",
    amount: "المبلغ",
    processing: "جاري المعالجة...",
    error: "حدث خطأ. يرجى المحاولة مرة أخرى.",
    notes: "ملاحظات",
    daysOverdue: "يوم تأخير",
    UNPAID: "غير مدفوع",
    PARTIAL: "مدفوع جزئياً",
    PAID: "مدفوع",
    OVERDUE: "متأخر",
    DRAFT: "مسودة",
    SENT: "مُرسل",
    VIEWED: "تم العرض",
    ACCEPTED: "مقبول",
    DECLINED: "مرفوض",
    EXPIRED: "منتهي",
    CANCELLED: "ملغي",
    STRIPE: "بطاقة",
    MANUAL_CASH: "نقداً",
    MANUAL_BANK_TRANSFER: "تحويل بنكي",
    MANUAL_CHECK: "شيك",
    MANUAL_OTHER: "أخرى",
    poweredBy: "مدعوم من Mawidi",
  },
};

interface QuotationItem {
  id: string;
  description: string;
  quantity: number;
  unitPrice: number;
  total: number;
  sortOrder: number;
}

interface Payment {
  id: string;
  amount: number;
  currency: string;
  method: string;
  reference: string | null;
  paidAt: string;
}

interface QuotationData {
  id: string;
  quotationNumber: string;
  title: string;
  notes: string | null;
  status: string;
  currency: string;
  subtotal: number;
  taxRate: number;
  taxAmount: number;
  discountRate: number;
  discountAmount: number;
  total: number;
  validUntil: string | null;
  sentAt: string | null;
  viewedAt: string | null;
  respondedAt: string | null;
  paymentStatus: string;
  amountPaid: number;
  dueDate: string | null;
  penaltyAmount: number;
  penaltyAppliedAt: string | null;
  createdAt: string;
  customer: {
    id: string;
    name: string;
    email: string | null;
    phone: string | null;
  } | null;
  items: QuotationItem[];
  payments: Payment[];
}

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

const paymentStatusColors: Record<string, string> = {
  UNPAID: "bg-gray-100 text-gray-700",
  PARTIAL: "bg-orange-100 text-orange-700",
  PAID: "bg-green-100 text-green-700",
  OVERDUE: "bg-red-100 text-red-700",
};

export default function QuotationPortalClient({ token }: { token: string }) {
  const [quotation, setQuotation] = useState<QuotationData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [actionLoading, setActionLoading] = useState(false);
  const [showDeclineForm, setShowDeclineForm] = useState(false);
  const [declineReason, setDeclineReason] = useState("");

  // Detect language from browser
  const browserLang =
    typeof navigator !== "undefined" && navigator.language?.startsWith("ar")
      ? "ar"
      : "en";
  const [lang] = useState(browserLang);
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;

  const formatCurrency = (amount: number, currency: string) => {
    return new Intl.NumberFormat(isAr ? "ar-QA" : "en-QA", {
      style: "currency",
      currency,
    }).format(amount);
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString(isAr ? "ar-QA" : "en-QA", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  useEffect(() => {
    const fetchQuotation = async () => {
      try {
        const res = await fetch(`/api/quotations/portal/${token}`);
        const data = await res.json();
        if (data.success) {
          setQuotation(data.quotation);
        } else {
          setError(data.error || "Not found");
        }
      } catch {
        setError("Failed to load");
      } finally {
        setLoading(false);
      }
    };
    fetchQuotation();
  }, [token]);

  const handleAccept = async () => {
    setActionLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/quotations/portal/${token}/accept`, {
        method: "POST",
      });
      const data = await res.json();
      if (data.success) {
        setQuotation((prev) =>
          prev
            ? {
                ...prev,
                status: "ACCEPTED",
                respondedAt: new Date().toISOString(),
              }
            : prev,
        );
      } else {
        setError(data.error);
      }
    } catch {
      setError(labels.error);
    } finally {
      setActionLoading(false);
    }
  };

  const handleDecline = async () => {
    setActionLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/quotations/portal/${token}/decline`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ reason: declineReason || undefined }),
      });
      const data = await res.json();
      if (data.success) {
        setQuotation((prev) =>
          prev
            ? {
                ...prev,
                status: "DECLINED",
                respondedAt: new Date().toISOString(),
              }
            : prev,
        );
        setShowDeclineForm(false);
      } else {
        setError(data.error);
      }
    } catch {
      setError(labels.error);
    } finally {
      setActionLoading(false);
    }
  };

  const handlePay = async () => {
    setActionLoading(true);
    setError(null);
    try {
      const baseUrl = window.location.origin;
      const res = await fetch(`/api/quotations/portal/${token}/pay`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          successUrl: `${baseUrl}/quotation/${token}?payment=success`,
          cancelUrl: `${baseUrl}/quotation/${token}?payment=cancelled`,
        }),
      });
      const data = await res.json();
      if (data.success && data.checkoutUrl) {
        window.location.href = data.checkoutUrl;
      } else {
        setError(data.error);
      }
    } catch {
      setError(labels.error);
    } finally {
      setActionLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-green-500 mx-auto mb-4" />
          <p className="text-gray-500">{labels.loading}</p>
        </div>
      </div>
    );
  }

  if (!quotation) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center max-w-md">
          <div className="rounded-full bg-red-50 p-4 mx-auto w-16 h-16 flex items-center justify-center mb-4">
            <svg
              className="w-8 h-8 text-red-500"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </div>
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            {labels.notFound}
          </h2>
          <p className="text-gray-500">{labels.notFoundDesc}</p>
        </div>
      </div>
    );
  }

  const canRespond =
    quotation.status === "SENT" || quotation.status === "VIEWED";
  const canPay =
    quotation.status === "ACCEPTED" &&
    (quotation.paymentStatus === "UNPAID" ||
      quotation.paymentStatus === "PARTIAL" ||
      quotation.paymentStatus === "OVERDUE");
  const remainingBalance =
    quotation.total + quotation.penaltyAmount - quotation.amountPaid;

  const daysOverdue =
    quotation.dueDate && new Date(quotation.dueDate) < new Date()
      ? Math.floor(
          (Date.now() - new Date(quotation.dueDate).getTime()) /
            (1000 * 60 * 60 * 24),
        )
      : 0;

  return (
    <div
      dir={isAr ? "rtl" : "ltr"}
      className="min-h-screen bg-gray-50 py-8 px-4"
    >
      <div className="max-w-3xl mx-auto">
        {/* Header */}
        <div className="bg-white rounded-t-xl border border-gray-200 p-6 sm:p-8">
          <div className="flex items-start justify-between flex-wrap gap-4">
            <div>
              <div className="flex items-center gap-2 mb-1">
                <div className="w-8 h-8 bg-green-500 rounded-lg flex items-center justify-center">
                  <span className="text-white font-bold text-sm">M</span>
                </div>
                <span className="font-semibold text-gray-900">Mawidi</span>
              </div>
              <h1 className="text-2xl font-bold text-gray-900 mt-3">
                {labels.quotation} #{quotation.quotationNumber}
              </h1>
              <p className="text-gray-500 mt-1">{quotation.title}</p>
            </div>
            <div className="flex gap-2">
              <span
                className={`inline-flex px-3 py-1 rounded-full text-xs font-medium ${statusColors[quotation.status] || ""}`}
              >
                {labels[quotation.status as keyof typeof labels] ||
                  quotation.status}
              </span>
              <span
                className={`inline-flex px-3 py-1 rounded-full text-xs font-medium ${paymentStatusColors[quotation.paymentStatus] || ""}`}
              >
                {labels[quotation.paymentStatus as keyof typeof labels] ||
                  quotation.paymentStatus}
              </span>
            </div>
          </div>

          {/* Metadata Row */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-6 pt-6 border-t border-gray-100">
            <div>
              <p className="text-xs text-gray-500 uppercase tracking-wider">
                {labels.date}
              </p>
              <p className="text-sm font-medium text-gray-900 mt-1">
                {formatDate(quotation.createdAt)}
              </p>
            </div>
            {quotation.validUntil && (
              <div>
                <p className="text-xs text-gray-500 uppercase tracking-wider">
                  {labels.validUntil}
                </p>
                <p className="text-sm font-medium text-gray-900 mt-1">
                  {formatDate(quotation.validUntil)}
                </p>
              </div>
            )}
            {quotation.dueDate && (
              <div>
                <p className="text-xs text-gray-500 uppercase tracking-wider">
                  {labels.dueDate}
                </p>
                <p
                  className={`text-sm font-medium mt-1 ${daysOverdue > 0 ? "text-red-600" : "text-gray-900"}`}
                >
                  {formatDate(quotation.dueDate)}
                  {daysOverdue > 0 && (
                    <span className="text-xs ms-1">
                      ({daysOverdue} {labels.daysOverdue})
                    </span>
                  )}
                </p>
              </div>
            )}
            {quotation.customer && (
              <div>
                <p className="text-xs text-gray-500 uppercase tracking-wider">
                  {labels.billTo}
                </p>
                <p className="text-sm font-medium text-gray-900 mt-1">
                  {quotation.customer.name}
                </p>
                {quotation.customer.email && (
                  <p className="text-xs text-gray-500">
                    {quotation.customer.email}
                  </p>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Penalty Banner */}
        {quotation.penaltyAmount > 0 && (
          <div className="bg-red-50 border-x border-red-200 px-6 sm:px-8 py-3">
            <div className="flex items-center gap-2 text-red-700">
              <svg
                className="w-5 h-5 flex-shrink-0"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
                />
              </svg>
              <span className="text-sm font-medium">
                {labels.penalty}:{" "}
                {formatCurrency(quotation.penaltyAmount, quotation.currency)}
                {daysOverdue > 0 && ` (${daysOverdue} ${labels.daysOverdue})`}
              </span>
            </div>
          </div>
        )}

        {/* Line Items Table */}
        <div className="bg-white border-x border-gray-200">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-50 border-y border-gray-200">
                  <th className="text-start px-6 sm:px-8 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                    {labels.item}
                  </th>
                  <th className="text-center px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                    {labels.qty}
                  </th>
                  <th className="text-end px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                    {labels.unitPrice}
                  </th>
                  <th className="text-end px-6 sm:px-8 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                    {labels.total}
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {quotation.items.map((item) => (
                  <tr key={item.id}>
                    <td className="px-6 sm:px-8 py-4 text-sm text-gray-900">
                      {item.description}
                    </td>
                    <td className="px-4 py-4 text-sm text-gray-500 text-center">
                      {item.quantity}
                    </td>
                    <td className="px-4 py-4 text-sm text-gray-500 text-end">
                      {formatCurrency(item.unitPrice, quotation.currency)}
                    </td>
                    <td className="px-6 sm:px-8 py-4 text-sm font-medium text-gray-900 text-end">
                      {formatCurrency(item.total, quotation.currency)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Totals */}
        <div className="bg-white border-x border-gray-200 px-6 sm:px-8 py-6">
          <div className="max-w-xs ms-auto space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">{labels.subtotal}</span>
              <span className="text-gray-900">
                {formatCurrency(quotation.subtotal, quotation.currency)}
              </span>
            </div>
            {quotation.discountAmount > 0 && (
              <div className="flex justify-between text-sm text-red-600">
                <span>
                  {labels.discount} ({quotation.discountRate}%)
                </span>
                <span>
                  -
                  {formatCurrency(quotation.discountAmount, quotation.currency)}
                </span>
              </div>
            )}
            {quotation.taxAmount > 0 && (
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">
                  {labels.tax} ({quotation.taxRate}%)
                </span>
                <span className="text-gray-900">
                  {formatCurrency(quotation.taxAmount, quotation.currency)}
                </span>
              </div>
            )}
            {quotation.penaltyAmount > 0 && (
              <div className="flex justify-between text-sm text-red-600 font-medium">
                <span>{labels.penalty}</span>
                <span>
                  +{formatCurrency(quotation.penaltyAmount, quotation.currency)}
                </span>
              </div>
            )}
            <div className="flex justify-between text-lg font-bold pt-3 border-t border-gray-200">
              <span>{labels.grandTotal}</span>
              <span className="text-green-600">
                {formatCurrency(
                  quotation.total + quotation.penaltyAmount,
                  quotation.currency,
                )}
              </span>
            </div>
            {quotation.amountPaid > 0 && (
              <>
                <div className="flex justify-between text-sm text-green-600">
                  <span>{labels.amountPaid}</span>
                  <span>
                    -{formatCurrency(quotation.amountPaid, quotation.currency)}
                  </span>
                </div>
                <div className="flex justify-between text-sm font-semibold">
                  <span>{labels.remaining}</span>
                  <span>
                    {formatCurrency(remainingBalance, quotation.currency)}
                  </span>
                </div>
              </>
            )}
          </div>
        </div>

        {/* Notes */}
        {quotation.notes && (
          <div className="bg-white border-x border-gray-200 px-6 sm:px-8 pb-6">
            <div className="bg-gray-50 rounded-lg p-4">
              <p className="text-xs text-gray-500 uppercase tracking-wider mb-2">
                {labels.notes}
              </p>
              <p className="text-sm text-gray-700 whitespace-pre-wrap">
                {quotation.notes}
              </p>
            </div>
          </div>
        )}

        {/* Error Message */}
        {error && (
          <div className="bg-red-50 border-x border-red-200 px-6 sm:px-8 py-3">
            <p className="text-sm text-red-700">{error}</p>
          </div>
        )}

        {/* Actions */}
        {(canRespond || canPay) && (
          <div className="bg-white border-x border-gray-200 px-6 sm:px-8 py-6 border-t border-gray-100">
            {canRespond && !showDeclineForm && (
              <div className="flex gap-3 justify-center">
                <button
                  type="button"
                  onClick={handleAccept}
                  disabled={actionLoading}
                  className="px-8 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors font-medium disabled:opacity-50"
                >
                  {actionLoading ? labels.processing : labels.accept}
                </button>
                <button
                  type="button"
                  onClick={() => setShowDeclineForm(true)}
                  disabled={actionLoading}
                  className="px-8 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium disabled:opacity-50"
                >
                  {labels.decline}
                </button>
              </div>
            )}

            {showDeclineForm && (
              <div className="max-w-md mx-auto space-y-3">
                <textarea
                  value={declineReason}
                  onChange={(e) => setDeclineReason(e.target.value)}
                  placeholder={labels.declineReason}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-red-500 focus:border-red-500"
                />
                <div className="flex gap-3 justify-center">
                  <button
                    type="button"
                    onClick={handleDecline}
                    disabled={actionLoading}
                    className="px-6 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors text-sm font-medium disabled:opacity-50"
                  >
                    {actionLoading ? labels.processing : labels.declineConfirm}
                  </button>
                  <button
                    type="button"
                    onClick={() => setShowDeclineForm(false)}
                    className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 text-sm"
                  >
                    {labels.cancel}
                  </button>
                </div>
              </div>
            )}

            {canPay && (
              <div className="text-center">
                <button
                  type="button"
                  onClick={handlePay}
                  disabled={actionLoading}
                  className="px-8 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors font-medium disabled:opacity-50"
                >
                  {actionLoading
                    ? labels.processing
                    : `${labels.payNow} - ${formatCurrency(remainingBalance, quotation.currency)}`}
                </button>
              </div>
            )}
          </div>
        )}

        {/* Payment History */}
        {quotation.payments.length > 0 && (
          <div className="bg-white border-x border-gray-200 px-6 sm:px-8 py-6 border-t border-gray-100">
            <h3 className="text-sm font-semibold text-gray-900 mb-3">
              {labels.paymentHistory}
            </h3>
            <div className="space-y-2">
              {quotation.payments.map((payment) => (
                <div
                  key={payment.id}
                  className="flex items-center justify-between py-2 px-3 bg-gray-50 rounded-lg text-sm"
                >
                  <div>
                    <span className="font-medium text-gray-900">
                      {formatCurrency(payment.amount, payment.currency)}
                    </span>
                    <span className="text-gray-500 mx-2">
                      {labels[payment.method as keyof typeof labels] ||
                        payment.method}
                    </span>
                    {payment.reference && (
                      <span className="text-gray-400">{payment.reference}</span>
                    )}
                  </div>
                  <span className="text-gray-500 text-xs">
                    {formatDate(payment.paidAt)}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Footer */}
        <div className="bg-gray-50 rounded-b-xl border border-gray-200 border-t-0 px-6 sm:px-8 py-4 text-center">
          <p className="text-xs text-gray-400">{labels.poweredBy}</p>
        </div>
      </div>
    </div>
  );
}
