"use client";

import { useState, useEffect, useCallback } from "react";
import ExpenseForm from "./ExpenseForm";
import { fetchWithCSRF } from "@/lib/csrf-client";

interface Category {
  id: string;
  name: string;
  nameAr: string | null;
  color: string;
  icon?: string;
  expenseCount: number;
}

interface Expense {
  id: string;
  categoryId: string;
  category: { name: string; nameAr: string | null; color: string };
  amount: number;
  currency: string;
  vendor: string | null;
  description: string | null;
  date: string;
  notes: string | null;
  isRecurring: boolean;
  recurringFrequency: string | null;
  tags: string[];
}

const t = {
  en: {
    title: "Expenses",
    addExpense: "Add Expense",
    search: "Search expenses...",
    allCategories: "All Categories",
    dateFrom: "From",
    dateTo: "To",
    noExpenses: "No expenses found. Add your first expense to get started.",
    vendor: "Vendor",
    date: "Date",
    amount: "Amount",
    category: "Category",
    actions: "Actions",
    edit: "Edit",
    delete: "Delete",
    confirmDelete: "Delete this expense?",
    total: "Total",
    showing: "Showing",
    of: "of",
    prev: "Previous",
    next: "Next",
    recurring: "Recurring",
  },
  ar: {
    title: "المصروفات",
    addExpense: "إضافة مصروف",
    search: "بحث في المصروفات...",
    allCategories: "جميع الفئات",
    dateFrom: "من",
    dateTo: "إلى",
    noExpenses: "لا توجد مصروفات. أضف أول مصروف للبدء.",
    vendor: "المورد",
    date: "التاريخ",
    amount: "المبلغ",
    category: "الفئة",
    actions: "إجراءات",
    edit: "تعديل",
    delete: "حذف",
    confirmDelete: "حذف هذا المصروف؟",
    total: "الإجمالي",
    showing: "عرض",
    of: "من",
    prev: "السابق",
    next: "التالي",
    recurring: "متكرر",
  },
};

interface ExpensesListProps {
  lang: string;
}

export default function ExpensesList({ lang }: ExpensesListProps) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;

  const [expenses, setExpenses] = useState<Expense[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [loading, setLoading] = useState(true);

  // Filters
  const [search, setSearch] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("");
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");

  // Form
  const [showForm, setShowForm] = useState(false);
  const [editingExpense, setEditingExpense] = useState<Expense | null>(null);

  const fetchCategories = useCallback(async () => {
    try {
      const res = await fetch("/api/dashboard/expenses/categories");
      const data = await res.json();
      if (data.success) setCategories(data.categories);
    } catch {
      /* ignore */
    }
  }, []);

  const fetchExpenses = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ page: String(page), limit: "20" });
      if (search) params.set("search", search);
      if (categoryFilter) params.set("categoryId", categoryFilter);
      if (dateFrom) params.set("dateFrom", dateFrom);
      if (dateTo) params.set("dateTo", dateTo);

      const res = await fetch(`/api/dashboard/expenses?${params}`);
      const data = await res.json();
      if (data.success) {
        setExpenses(data.expenses);
        setTotal(data.total);
        setTotalPages(data.totalPages);
      }
    } catch {
      /* ignore */
    }
    setLoading(false);
  }, [page, search, categoryFilter, dateFrom, dateTo]);

  useEffect(() => {
    fetchCategories();
  }, [fetchCategories]);
  useEffect(() => {
    fetchExpenses();
  }, [fetchExpenses]);

  const handleSave = async (formData: {
    id?: string;
    categoryId: string;
    amount: number;
    currency: string;
    vendor: string;
    description: string;
    date: string;
    notes: string;
    isRecurring: boolean;
    recurringFrequency: string;
    tags: string[];
  }) => {
    const method = editingExpense ? "PUT" : "POST";
    const url = editingExpense
      ? `/api/dashboard/expenses/${editingExpense.id}`
      : "/api/dashboard/expenses";

    await fetchWithCSRF(url, {
      method,
      body: JSON.stringify(formData),
    });

    setShowForm(false);
    setEditingExpense(null);
    fetchExpenses();
  };

  const handleDelete = async (id: string) => {
    if (!confirm(labels.confirmDelete)) return;
    await fetch(`/api/dashboard/expenses/${id}`, { method: "DELETE" });
    fetchExpenses();
  };

  const pageTotal = expenses.reduce((sum, e) => sum + e.amount, 0);

  return (
    <div dir={isAr ? "rtl" : "ltr"}>
      {/* Header */}
      <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
          {labels.title}
        </h3>
        <button
          onClick={() => {
            setEditingExpense(null);
            setShowForm(true);
          }}
          className="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-2 text-sm font-medium text-white hover:bg-indigo-700"
        >
          <span className="text-lg leading-none">+</span> {labels.addExpense}
        </button>
      </div>

      {/* Filters */}
      <div className="mb-4 flex flex-wrap gap-3">
        <input
          type="text"
          placeholder={labels.search}
          value={search}
          onChange={(e) => {
            setSearch(e.target.value);
            setPage(1);
          }}
          className="rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
        />
        <select
          value={categoryFilter}
          onChange={(e) => {
            setCategoryFilter(e.target.value);
            setPage(1);
          }}
          className="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.allCategories}</option>
          {categories.map((cat) => (
            <option key={cat.id} value={cat.id}>
              {isAr && cat.nameAr ? cat.nameAr : cat.name}
            </option>
          ))}
        </select>
        <div className="flex items-center gap-2">
          <span className="text-xs text-gray-500">{labels.dateFrom}</span>
          <input
            type="date"
            value={dateFrom}
            onChange={(e) => {
              setDateFrom(e.target.value);
              setPage(1);
            }}
            className="rounded-lg border border-gray-300 px-2 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
          />
          <span className="text-xs text-gray-500">{labels.dateTo}</span>
          <input
            type="date"
            value={dateTo}
            onChange={(e) => {
              setDateTo(e.target.value);
              setPage(1);
            }}
            className="rounded-lg border border-gray-300 px-2 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
          />
        </div>
      </div>

      {/* Table */}
      {loading ? (
        <div className="flex h-40 items-center justify-center">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-indigo-300 border-t-indigo-600" />
        </div>
      ) : expenses.length === 0 ? (
        <div className="rounded-lg border border-dashed border-gray-300 p-8 text-center text-gray-500 dark:border-gray-600">
          {labels.noExpenses}
        </div>
      ) : (
        <>
          <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 text-gray-600 dark:bg-gray-800 dark:text-gray-400">
                <tr>
                  <th className="px-4 py-3 text-start font-medium">
                    {labels.date}
                  </th>
                  <th className="px-4 py-3 text-start font-medium">
                    {labels.category}
                  </th>
                  <th className="px-4 py-3 text-start font-medium">
                    {labels.vendor}
                  </th>
                  <th className="px-4 py-3 text-end font-medium">
                    {labels.amount}
                  </th>
                  <th className="px-4 py-3 text-end font-medium">
                    {labels.actions}
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
                {expenses.map((exp) => (
                  <tr
                    key={exp.id}
                    className="hover:bg-gray-50 dark:hover:bg-gray-800/50"
                  >
                    <td className="px-4 py-3 text-gray-900 dark:text-white">
                      {new Date(exp.date).toLocaleDateString(
                        isAr ? "ar-QA" : "en-QA",
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium text-white"
                        style={{ backgroundColor: exp.category.color }}
                      >
                        {isAr && exp.category.nameAr
                          ? exp.category.nameAr
                          : exp.category.name}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-700 dark:text-gray-300">
                      {exp.vendor || "—"}
                      {exp.isRecurring && (
                        <span className="ms-1 text-xs text-indigo-500">
                          ({labels.recurring})
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-end font-medium text-gray-900 dark:text-white">
                      {exp.amount.toLocaleString(isAr ? "ar-QA" : "en-QA", {
                        style: "currency",
                        currency: exp.currency,
                      })}
                    </td>
                    <td className="px-4 py-3 text-end">
                      <button
                        onClick={() => {
                          setEditingExpense(exp);
                          setShowForm(true);
                        }}
                        className="me-2 text-indigo-600 hover:underline dark:text-indigo-400"
                      >
                        {labels.edit}
                      </button>
                      <button
                        onClick={() => handleDelete(exp.id)}
                        className="text-red-600 hover:underline dark:text-red-400"
                      >
                        {labels.delete}
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr className="bg-gray-50 font-medium dark:bg-gray-800">
                  <td
                    colSpan={3}
                    className="px-4 py-3 text-gray-900 dark:text-white"
                  >
                    {labels.total}
                  </td>
                  <td className="px-4 py-3 text-end text-gray-900 dark:text-white">
                    {pageTotal.toLocaleString(isAr ? "ar-QA" : "en-QA", {
                      style: "currency",
                      currency: "QAR",
                    })}
                  </td>
                  <td />
                </tr>
              </tfoot>
            </table>
          </div>

          {/* Pagination */}
          <div className="mt-4 flex items-center justify-between text-sm text-gray-600 dark:text-gray-400">
            <span>
              {labels.showing} {expenses.length} {labels.of} {total}
            </span>
            <div className="flex gap-2">
              <button
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page <= 1}
                className="rounded-lg border px-3 py-1 disabled:opacity-40 dark:border-gray-600"
              >
                {labels.prev}
              </button>
              <button
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page >= totalPages}
                className="rounded-lg border px-3 py-1 disabled:opacity-40 dark:border-gray-600"
              >
                {labels.next}
              </button>
            </div>
          </div>
        </>
      )}

      {/* Form modal */}
      {showForm && (
        <ExpenseForm
          lang={lang}
          categories={categories}
          expense={
            editingExpense
              ? {
                  id: editingExpense.id,
                  categoryId: editingExpense.categoryId,
                  amount: editingExpense.amount,
                  currency: editingExpense.currency,
                  vendor: editingExpense.vendor ?? "",
                  description: editingExpense.description ?? "",
                  date: editingExpense.date,
                  notes: editingExpense.notes ?? "",
                  isRecurring: editingExpense.isRecurring,
                  recurringFrequency:
                    editingExpense.recurringFrequency ?? "monthly",
                  tags: editingExpense.tags,
                }
              : null
          }
          onSave={handleSave}
          onCancel={() => {
            setShowForm(false);
            setEditingExpense(null);
          }}
        />
      )}
    </div>
  );
}
