import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useEffect, useMemo, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useLanguage } from "@/hooks/use-language";
import { usePermissions } from "@/hooks/use-permissions";
import { useAuth } from "@/hooks/use-auth";
import { Plus, Edit, Trash2, X, TrendingUp } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/incomes")({
  head: () => ({ meta: [{ title: "Incomes — Niyamah ERP" }] }),
  component: IncomesPage,
});

type Row = { id: string; source: string; category_id: string | null; amount: number; payment_method: string; income_date: string; note: string; branch_id: string | null };
type CatOpt = { id: string; name: string; name_bn: string; color: string };
const empty = { source: "other", category_id: "", amount: 0, payment_method: "cash", income_date: new Date().toISOString().slice(0, 10), note: "", branch_id: "" };

function IncomesPage() {
  const { lang } = useLanguage();
  const { isAdmin } = usePermissions();
  const { user } = useAuth();
  const [rows, setRows] = useState<Row[]>([]);
  const [branches, setBranches] = useState<{ id: string; name: string }[]>([]);
  const [cats, setCats] = useState<CatOpt[]>([]);
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const [edit, setEdit] = useState<Row | null>(null);
  const [form, setForm] = useState({ ...empty });
  const [saving, setSaving] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    const [{ data }, { data: br }, { data: cs }] = await Promise.all([
      supabase.from("incomes").select("*").order("income_date", { ascending: false }).limit(500),
      supabase.from("branches").select("id, name").is("deleted_at", null),
      supabase.from("transaction_categories").select("id, name, name_bn, color").eq("type", "income").eq("status", "active").is("deleted_at", null).order("name"),
    ]);
    setRows((data as Row[]) || []);
    setBranches(br || []);
    setCats((cs as CatOpt[]) || []);
    setLoading(false);
  };
  useEffect(() => { fetchData(); }, []);

  const total = useMemo(() => rows.reduce((s, r) => s + Number(r.amount || 0), 0), [rows]);

  const openAdd = () => { setEdit(null); setForm({ ...empty }); setOpen(true); };
  const openEdit = (r: Row) => { setEdit(r); setForm({ source: r.source, category_id: r.category_id || "", amount: Number(r.amount), payment_method: r.payment_method, income_date: r.income_date, note: r.note || "", branch_id: r.branch_id || "" }); setOpen(true); };
  const del = async (r: Row) => {
    if (!confirm(lang === "bn" ? "মুছবেন?" : "Delete?")) return;
    const { error } = await supabase.from("incomes").delete().eq("id", r.id);
    if (error) { toast.error("Delete failed"); return; }
    toast.success(lang === "bn" ? "মুছে ফেলা হয়েছে" : "Deleted"); fetchData();
  };
  const save = async () => {
    if (!form.amount || form.amount <= 0) { toast.error(lang === "bn" ? "পরিমাণ লিখুন" : "Amount required"); return; }
    setSaving(true);
    const selectedCat = cats.find((c) => c.id === form.category_id);
    const sourceName = selectedCat ? selectedCat.name : (form.source || "other");
    const payload = { ...form, source: sourceName, category_id: form.category_id || null, branch_id: form.branch_id || null, created_by: user?.id };
    const { error } = edit
      ? await supabase.from("incomes").update(payload).eq("id", edit.id)
      : await supabase.from("incomes").insert(payload);
    setSaving(false);
    if (error) { toast.error(error.message); return; }
    toast.success(edit ? (lang === "bn" ? "আপডেট হয়েছে" : "Updated") : (lang === "bn" ? "যোগ হয়েছে" : "Added"));
    setOpen(false); fetchData();
  };

  const inputCls = "w-full rounded-lg border border-input bg-card px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring";

  return (
    <PageLayout>
      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-xl font-bold text-foreground">{lang === "bn" ? "আয় ব্যবস্থাপনা" : "Income Management"}</h1>
          <p className="text-sm text-muted-foreground">{rows.length} {lang === "bn" ? "এন্ট্রি" : "entries"} · {lang === "bn" ? "মোট" : "Total"}: ৳ {total.toLocaleString()}</p>
        </div>
        {isAdmin && (
          <button onClick={openAdd} className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground hover:bg-primary/90">
            <Plus className="h-4 w-4" /> {lang === "bn" ? "নতুন আয়" : "Add Income"}
          </button>
        )}
      </div>

      {loading ? (
        <div className="flex h-40 items-center justify-center text-muted-foreground">{lang === "bn" ? "লোড হচ্ছে..." : "Loading..."}</div>
      ) : (
        <div className="overflow-hidden rounded-xl border border-border bg-card">
          <table className="w-full text-sm">
            <thead className="bg-muted/50 text-xs text-muted-foreground">
              <tr>
                <th className="px-4 py-3 text-left">{lang === "bn" ? "তারিখ" : "Date"}</th>
                <th className="px-4 py-3 text-left">{lang === "bn" ? "উৎস" : "Source"}</th>
                <th className="px-4 py-3 text-left">{lang === "bn" ? "পদ্ধতি" : "Method"}</th>
                <th className="px-4 py-3 text-left">{lang === "bn" ? "নোট" : "Note"}</th>
                <th className="px-4 py-3 text-right">{lang === "bn" ? "পরিমাণ" : "Amount"}</th>
                <th className="px-4 py-3 text-right">{lang === "bn" ? "অ্যাকশন" : "Action"}</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.id} className="border-t border-border hover:bg-muted/30">
                  <td className="px-4 py-3 text-muted-foreground">{r.income_date}</td>
                  <td className="px-4 py-3"><span className="inline-flex items-center gap-2"><TrendingUp className="h-3.5 w-3.5 text-emerald-600" />{r.source}</span></td>
                  <td className="px-4 py-3 text-muted-foreground">{r.payment_method}</td>
                  <td className="px-4 py-3 text-muted-foreground">{r.note || "—"}</td>
                  <td className="px-4 py-3 text-right font-medium">৳ {Number(r.amount).toLocaleString()}</td>
                  <td className="px-4 py-3">
                    {isAdmin && (
                      <div className="flex justify-end gap-1">
                        <button onClick={() => openEdit(r)} className="rounded p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground"><Edit className="h-3.5 w-3.5" /></button>
                        <button onClick={() => del(r)} className="rounded p-1.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"><Trash2 className="h-3.5 w-3.5" /></button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
              {rows.length === 0 && <tr><td colSpan={6} className="py-8 text-center text-muted-foreground">{lang === "bn" ? "কোনো আয় নেই" : "No incomes"}</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {open && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setOpen(false)}>
          <div className="w-full max-w-lg rounded-xl bg-card p-6 shadow-lg" onClick={(e) => e.stopPropagation()}>
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-lg font-bold">{edit ? (lang === "bn" ? "আয় এডিট" : "Edit Income") : (lang === "bn" ? "নতুন আয়" : "Add Income")}</h2>
              <button onClick={() => setOpen(false)} className="rounded p-1 hover:bg-muted"><X className="h-4 w-4" /></button>
            </div>
            <div className="grid gap-3 md:grid-cols-2">
              <div><label className="mb-1 block text-sm font-medium">{lang === "bn" ? "উৎস" : "Source"} *</label>
                <select className={inputCls} value={form.category_id} onChange={(e) => setForm({ ...form, category_id: e.target.value })}>
                  <option value="">{lang === "bn" ? "— নির্বাচন করুন —" : "— Select —"}</option>
                  {cats.map((c) => <option key={c.id} value={c.id}>{lang === "bn" ? (c.name_bn || c.name) : c.name}</option>)}
                </select></div>
              <div><label className="mb-1 block text-sm font-medium">{lang === "bn" ? "পরিমাণ" : "Amount"} *</label>
                <input type="number" className={inputCls} value={form.amount} onChange={(e) => setForm({ ...form, amount: Number(e.target.value) })} /></div>
              <div><label className="mb-1 block text-sm font-medium">{lang === "bn" ? "পদ্ধতি" : "Payment Method"}</label>
                <select className={inputCls} value={form.payment_method} onChange={(e) => setForm({ ...form, payment_method: e.target.value })}>
                  <option value="cash">Cash</option><option value="bank">Bank</option><option value="mobile">Mobile</option><option value="card">Card</option>
                </select></div>
              <div><label className="mb-1 block text-sm font-medium">{lang === "bn" ? "তারিখ" : "Date"}</label>
                <input type="date" className={inputCls} value={form.income_date} onChange={(e) => setForm({ ...form, income_date: e.target.value })} /></div>
              <div className="md:col-span-2"><label className="mb-1 block text-sm font-medium">{lang === "bn" ? "শাখা" : "Branch"}</label>
                <select className={inputCls} value={form.branch_id} onChange={(e) => setForm({ ...form, branch_id: e.target.value })}>
                  <option value="">{lang === "bn" ? "— কোনোটিই না —" : "— None —"}</option>
                  {branches.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
                </select></div>
              <div className="md:col-span-2"><label className="mb-1 block text-sm font-medium">{lang === "bn" ? "নোট" : "Note"}</label>
                <textarea rows={2} className={inputCls} value={form.note} onChange={(e) => setForm({ ...form, note: e.target.value })} /></div>
            </div>
            <div className="mt-5 flex justify-end gap-2">
              <button onClick={() => setOpen(false)} className="rounded-lg border border-border px-4 py-2 text-sm">{lang === "bn" ? "বাতিল" : "Cancel"}</button>
              <button onClick={save} disabled={saving} className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50">
                {saving ? "..." : (lang === "bn" ? "সংরক্ষণ" : "Save")}
              </button>
            </div>
          </div>
        </div>
      )}
    </PageLayout>
  );
}
