"use client";

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

interface Category {
  id: string;
  name: string;
  nameAr: string | null;
  color: string;
}

interface ExpenseData {
  id?: string;
  categoryId: string;
  amount: number;
  currency: string;
  vendor: string;
  description: string;
  date: string;
  notes: string;
  isRecurring: boolean;
  recurringFrequency: string;
  tags: string[];
}

const t = {
  en: {
    addExpense: "Add Expense",
    editExpense: "Edit Expense",
    category: "Category",
    amount: "Amount",
    currency: "Currency",
    vendor: "Vendor / Payee",
    description: "Description",
    date: "Date",
    notes: "Notes",
    recurring: "Recurring",
    frequency: "Frequency",
    weekly: "Weekly",
    monthly: "Monthly",
    quarterly: "Quarterly",
    yearly: "Yearly",
    tags: "Tags",
    tagsPlaceholder: "Comma-separated tags",
    save: "Save",
    cancel: "Cancel",
    saving: "Saving...",
    selectCategory: "Select category",
  },
  ar: {
    addExpense: "إضافة مصروف",
    editExpense: "تعديل مصروف",
    category: "الفئة",
    amount: "المبلغ",
    currency: "العملة",
    vendor: "المورد / المستفيد",
    description: "الوصف",
    date: "التاريخ",
    notes: "ملاحظات",
    recurring: "متكرر",
    frequency: "التكرار",
    weekly: "أسبوعياً",
    monthly: "شهرياً",
    quarterly: "ربع سنوي",
    yearly: "سنوياً",
    tags: "العلامات",
    tagsPlaceholder: "علامات مفصولة بفواصل",
    save: "حفظ",
    cancel: "إلغاء",
    saving: "جاري الحفظ...",
    selectCategory: "اختر الفئة",
  },
};

interface ExpenseFormProps {
  lang: string;
  expense?: ExpenseData | null;
  categories: Category[];
  onSave: (data: ExpenseData) => Promise<void>;
  onCancel: () => void;
}

export default function ExpenseForm({
  lang,
  expense,
  categories,
  onSave,
  onCancel,
}: ExpenseFormProps) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;

  const [form, setForm] = useState<ExpenseData>({
    categoryId: "",
    amount: 0,
    currency: "QAR",
    vendor: "",
    description: "",
    date: new Date().toISOString().slice(0, 10),
    notes: "",
    isRecurring: false,
    recurringFrequency: "monthly",
    tags: [],
  });
  const [tagInput, setTagInput] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (expense) {
      setForm({
        ...expense,
        date: expense.date
          ? expense.date.slice(0, 10)
          : new Date().toISOString().slice(0, 10),
      });
      setTagInput(expense.tags?.join(", ") ?? "");
    }
  }, [expense]);

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      setSaving(true);
      try {
        const tags = tagInput
          .split(",")
          .map((t) => t.trim())
          .filter(Boolean);
        await onSave({ ...form, tags });
      } finally {
        setSaving(false);
      }
    },
    [form, tagInput, onSave],
  );

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <form
        onSubmit={handleSubmit}
        dir={isAr ? "rtl" : "ltr"}
        className="w-full max-w-lg rounded-xl bg-white p-6 shadow-xl dark:bg-gray-800"
      >
        <h3 className="mb-4 text-lg font-semibold text-gray-900 dark:text-white">
          {expense?.id ? labels.editExpense : labels.addExpense}
        </h3>

        <div className="space-y-4">
          {/* Category */}
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
              {labels.category}
            </label>
            <select
              required
              value={form.categoryId}
              onChange={(e) => setForm({ ...form, categoryId: e.target.value })}
              className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
            >
              <option value="">{labels.selectCategory}</option>
              {categories.map((cat) => (
                <option key={cat.id} value={cat.id}>
                  {isAr && cat.nameAr ? cat.nameAr : cat.name}
                </option>
              ))}
            </select>
          </div>

          {/* Amount + Currency row */}
          <div className="flex gap-3">
            <div className="flex-1">
              <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
                {labels.amount}
              </label>
              <input
                type="number"
                required
                min="0.01"
                step="0.01"
                value={form.amount || ""}
                onChange={(e) =>
                  setForm({ ...form, amount: parseFloat(e.target.value) || 0 })
                }
                className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
              />
            </div>
            <div className="w-24">
              <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
                {labels.currency}
              </label>
              <select
                value={form.currency}
                onChange={(e) => setForm({ ...form, currency: e.target.value })}
                className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
              >
                <option value="QAR">QAR</option>
                <option value="SAR">SAR</option>
                <option value="AED">AED</option>
                <option value="KWD">KWD</option>
                <option value="BHD">BHD</option>
                <option value="OMR">OMR</option>
                <option value="USD">USD</option>
              </select>
            </div>
          </div>

          {/* Date */}
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
              {labels.date}
            </label>
            <input
              type="date"
              required
              value={form.date}
              onChange={(e) => setForm({ ...form, date: e.target.value })}
              className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
            />
          </div>

          {/* Vendor */}
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
              {labels.vendor}
            </label>
            <input
              type="text"
              value={form.vendor}
              onChange={(e) => setForm({ ...form, vendor: e.target.value })}
              className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
            />
          </div>

          {/* Description */}
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
              {labels.description}
            </label>
            <input
              type="text"
              value={form.description}
              onChange={(e) =>
                setForm({ ...form, description: e.target.value })
              }
              className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
            />
          </div>

          {/* Recurring toggle */}
          <div className="flex items-center gap-3">
            <label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
              <input
                type="checkbox"
                checked={form.isRecurring}
                onChange={(e) =>
                  setForm({ ...form, isRecurring: e.target.checked })
                }
                className="rounded"
              />
              {labels.recurring}
            </label>
            {form.isRecurring && (
              <select
                value={form.recurringFrequency}
                onChange={(e) =>
                  setForm({ ...form, recurringFrequency: e.target.value })
                }
                className="rounded-lg border border-gray-300 bg-white px-2 py-1 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
              >
                <option value="weekly">{labels.weekly}</option>
                <option value="monthly">{labels.monthly}</option>
                <option value="quarterly">{labels.quarterly}</option>
                <option value="yearly">{labels.yearly}</option>
              </select>
            )}
          </div>

          {/* Tags */}
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
              {labels.tags}
            </label>
            <input
              type="text"
              value={tagInput}
              onChange={(e) => setTagInput(e.target.value)}
              placeholder={labels.tagsPlaceholder}
              className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
            />
          </div>

          {/* Notes */}
          <div>
            <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
              {labels.notes}
            </label>
            <textarea
              value={form.notes}
              onChange={(e) => setForm({ ...form, notes: e.target.value })}
              rows={2}
              className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
            />
          </div>
        </div>

        {/* Actions */}
        <div className="mt-6 flex justify-end gap-3">
          <button
            type="button"
            onClick={onCancel}
            className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700"
          >
            {labels.cancel}
          </button>
          <button
            type="submit"
            disabled={saving}
            className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
          >
            {saving ? labels.saving : labels.save}
          </button>
        </div>
      </form>
    </div>
  );
}
