"use client";

import { useState } from "react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const t = {
  en: {
    title: "Record Payment",
    amount: "Amount",
    method: "Payment Method",
    reference: "Reference / Transaction ID",
    date: "Payment Date",
    notes: "Notes",
    remaining: "Remaining Balance",
    record: "Record Payment",
    recording: "Recording...",
    cancel: "Cancel",
    STRIPE: "Card (Stripe)",
    MANUAL_CASH: "Cash",
    MANUAL_BANK_TRANSFER: "Bank Transfer",
    MANUAL_CHECK: "Check",
    MANUAL_OTHER: "Other",
    error: "Failed to record payment",
  },
  ar: {
    title: "تسجيل دفعة",
    amount: "المبلغ",
    method: "طريقة الدفع",
    reference: "المرجع / رقم المعاملة",
    date: "تاريخ الدفع",
    notes: "ملاحظات",
    remaining: "الرصيد المتبقي",
    record: "تسجيل الدفعة",
    recording: "جاري التسجيل...",
    cancel: "إلغاء",
    STRIPE: "بطاقة (Stripe)",
    MANUAL_CASH: "نقداً",
    MANUAL_BANK_TRANSFER: "تحويل بنكي",
    MANUAL_CHECK: "شيك",
    MANUAL_OTHER: "أخرى",
    error: "فشل في تسجيل الدفعة",
  },
};

interface RecordPaymentModalProps {
  quotationId: string;
  quotationTotal: number;
  amountPaid: number;
  currency: string;
  lang: string;
  onClose: () => void;
  onSuccess: () => void;
}

export function RecordPaymentModal({
  quotationId,
  quotationTotal,
  amountPaid,
  currency,
  lang,
  onClose,
  onSuccess,
}: RecordPaymentModalProps) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;
  const remaining = quotationTotal - amountPaid;

  const [amount, setAmount] = useState(remaining > 0 ? remaining : 0);
  const [method, setMethod] = useState("MANUAL_CASH");
  const [reference, setReference] = useState("");
  const [paidAt, setPaidAt] = useState(new Date().toISOString().split("T")[0]);
  const [notes, setNotes] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const methods = [
    "MANUAL_CASH",
    "MANUAL_BANK_TRANSFER",
    "MANUAL_CHECK",
    "MANUAL_OTHER",
  ];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (amount <= 0) return;

    setSaving(true);
    setError(null);
    try {
      const res = await fetchWithCSRF(
        `/api/dashboard/quotations/${quotationId}/payments`,
        {
          method: "POST",
          body: JSON.stringify({
            amount,
            method,
            reference: reference || undefined,
            paidAt: new Date(paidAt).toISOString(),
            manualNotes: notes || undefined,
          }),
        },
      );

      if (res.ok) {
        onSuccess();
      } else {
        const data = await res.json();
        setError(data.error || labels.error);
      }
    } catch {
      setError(labels.error);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div
        dir={isAr ? "rtl" : "ltr"}
        className="bg-white rounded-xl shadow-xl max-w-md w-full"
      >
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
          <h3 className="text-lg font-semibold text-gray-900">
            {labels.title}
          </h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600"
          >
            &times;
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          <div className="text-sm text-gray-500 bg-gray-50 px-3 py-2 rounded-lg">
            {labels.remaining}:{" "}
            <span className="font-semibold text-gray-900">
              {currency} {remaining.toLocaleString()}
            </span>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {labels.amount}
            </label>
            <div className="relative">
              <span className="absolute inset-y-0 start-0 flex items-center ps-3 text-gray-500 text-sm">
                {currency}
              </span>
              <input
                type="number"
                min="0.01"
                step="0.01"
                max={remaining}
                value={amount}
                onChange={(e) => setAmount(parseFloat(e.target.value) || 0)}
                required
                className="w-full ps-16 pe-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {labels.method}
            </label>
            <select
              value={method}
              onChange={(e) => setMethod(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              {methods.map((m) => (
                <option key={m} value={m}>
                  {labels[m as keyof typeof labels] || m}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {labels.reference}
            </label>
            <input
              type="text"
              value={reference}
              onChange={(e) => setReference(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {labels.date}
            </label>
            <input
              type="date"
              value={paidAt}
              onChange={(e) => setPaidAt(e.target.value)}
              required
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {labels.notes}
            </label>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              rows={2}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          {error && (
            <p className="text-sm text-red-600 bg-red-50 px-3 py-2 rounded">
              {error}
            </p>
          )}

          <div className="flex gap-3 justify-end pt-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 rounded-lg text-sm text-gray-700 hover:bg-gray-50"
            >
              {labels.cancel}
            </button>
            <button
              type="submit"
              disabled={saving || amount <= 0}
              className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm hover:bg-green-700 disabled:opacity-50"
            >
              {saving ? labels.recording : labels.record}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
