"use client";

import { useEffect, useState } from "react";
import { Plus, Search, Receipt, Trash2, X } from "lucide-react";
import { format } from "date-fns";

interface Expense {
  id: number;
  category: string;
  description: string | null;
  amount: string;
  date: string;
  notes: string | null;
  createdAt: string;
}

function formatCurrency(val: string | number) {
  const num = typeof val === "string" ? parseFloat(val) : val;
  return "৳" + new Intl.NumberFormat("bn-BD", { maximumFractionDigits: 0 }).format(num);
}

const expenseCategories = [
  "Packaging",
  "Shipping",
  "Marketing",
  "Rent",
  "Utilities",
  "Photography",
  "Travel",
  "Miscellaneous",
];

const categoryColors: Record<string, string> = {
  Packaging: "bg-blue-100 text-blue-700",
  Shipping: "bg-purple-100 text-purple-700",
  Marketing: "bg-brand-100 text-brand-700",
  Rent: "bg-orange-100 text-orange-700",
  Utilities: "bg-yellow-100 text-yellow-700",
  Photography: "bg-green-100 text-green-700",
  Travel: "bg-teal-100 text-teal-700",
  Miscellaneous: "bg-gray-100 text-gray-700",
};

export default function ExpensesPage() {
  const [expenses, setExpenses] = useState<Expense[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ category: "", description: "", amount: "", date: "", notes: "" });

  const fetchData = async () => {
    const res = await fetch("/api/expenses");
    setExpenses(await res.json());
    setLoading(false);
  };

  useEffect(() => { fetchData(); }, []);

  const filtered = expenses.filter(
    (e) =>
      e.category.toLowerCase().includes(search.toLowerCase()) ||
      (e.description || "").toLowerCase().includes(search.toLowerCase())
  );

  const totalExpenses = expenses.reduce((sum, e) => sum + parseFloat(e.amount), 0);
  const categoryTotals = expenses.reduce((acc, e) => {
    acc[e.category] = (acc[e.category] || 0) + parseFloat(e.amount);
    return acc;
  }, {} as Record<string, number>);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await fetch("/api/expenses", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });
    setShowForm(false);
    setForm({ category: "", description: "", amount: "", date: "", notes: "" });
    fetchData();
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Delete this expense?")) return;
    await fetch(`/api/expenses?id=${id}`, { method: "DELETE" });
    fetchData();
  };

  if (loading) {
    return <div className="flex items-center justify-center h-96"><div className="animate-spin w-10 h-10 border-4 border-brand-500 border-t-transparent rounded-full" /></div>;
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 flex items-center gap-3">
            <Receipt className="text-brand-500" size={28} />
            Expenses
          </h1>
          <p className="text-gray-500 mt-1">Track business expenses</p>
        </div>
        <button onClick={() => setShowForm(true)} className="bg-brand-600 hover:bg-brand-700 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 font-medium shadow-lg shadow-brand-200">
          <Plus size={18} /> Add Expense
        </button>
      </div>

      {/* Summary */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5 mb-6">
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 md:col-span-2 lg:col-span-1">
          <p className="text-sm text-gray-500">Total Expenses</p>
          <p className="text-2xl font-bold text-red-600">{formatCurrency(totalExpenses)}</p>
          <p className="text-xs text-gray-400">{expenses.length} entries</p>
        </div>
        {Object.entries(categoryTotals)
          .sort((a, b) => b[1] - a[1])
          .slice(0, 3)
          .map(([cat, total]) => (
            <div key={cat} className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
              <p className="text-sm text-gray-500">{cat}</p>
              <p className="text-xl font-bold text-gray-900">{formatCurrency(total)}</p>
              <p className="text-xs text-gray-400">{((total / totalExpenses) * 100).toFixed(0)}% of total</p>
            </div>
          ))}
      </div>

      {/* Search */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 mb-6">
        <div className="relative">
          <Search size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
          <input type="text" placeholder="Search expenses..." value={search} onChange={(e) => setSearch(e.target.value)} className="w-full pl-10 pr-4 py-2.5 bg-gray-50 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-300 text-sm" />
        </div>
      </div>

      {/* Expenses Table */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b border-gray-100">
              <tr>
                <th className="text-left py-4 px-4 font-semibold text-gray-600">Date</th>
                <th className="text-left py-4 px-4 font-semibold text-gray-600">Category</th>
                <th className="text-left py-4 px-4 font-semibold text-gray-600">Description</th>
                <th className="text-right py-4 px-4 font-semibold text-gray-600">Amount</th>
                <th className="text-left py-4 px-4 font-semibold text-gray-600">Notes</th>
                <th className="text-center py-4 px-4 font-semibold text-gray-600">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((e) => (
                <tr key={e.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                  <td className="py-3 px-4 text-gray-600">{format(new Date(e.date), "dd MMM yyyy")}</td>
                  <td className="py-3 px-4">
                    <span className={`px-3 py-1 rounded-full text-xs font-medium ${categoryColors[e.category] || "bg-gray-100 text-gray-700"}`}>
                      {e.category}
                    </span>
                  </td>
                  <td className="py-3 px-4 text-gray-700">{e.description || "—"}</td>
                  <td className="py-3 px-4 text-right font-semibold text-red-600">{formatCurrency(e.amount)}</td>
                  <td className="py-3 px-4 text-gray-400 text-xs max-w-[200px] truncate">{e.notes || "—"}</td>
                  <td className="py-3 px-4 text-center">
                    <button onClick={() => handleDelete(e.id)} className="p-1.5 hover:bg-red-50 rounded-lg">
                      <Trash2 size={14} className="text-red-400" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {showForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl p-6 w-full max-w-md">
            <div className="flex items-center justify-between mb-5">
              <h2 className="text-xl font-bold">Add Expense</h2>
              <button onClick={() => setShowForm(false)} className="p-2 hover:bg-gray-100 rounded-lg"><X size={18} /></button>
            </div>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">Category *</label>
                <select required value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-300 text-sm">
                  <option value="">Select category</option>
                  {expenseCategories.map((c) => <option key={c} value={c}>{c}</option>)}
                </select>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">Description</label>
                <input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-300 text-sm" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">Amount (৳) *</label>
                  <input required type="number" step="0.01" value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-300 text-sm" />
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">Date</label>
                  <input type="date" value={form.date} onChange={(e) => setForm({ ...form, date: e.target.value })} className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-300 text-sm" />
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1 block">Notes</label>
                <textarea value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} rows={2} className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-300 text-sm" />
              </div>
              <div className="flex gap-3 pt-2">
                <button type="submit" className="flex-1 bg-brand-600 hover:bg-brand-700 text-white py-2.5 rounded-xl font-medium">Add Expense</button>
                <button type="button" onClick={() => setShowForm(false)} className="px-6 py-2.5 border border-gray-200 rounded-xl text-gray-600 hover:bg-gray-50 font-medium">Cancel</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
