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 { TrendingUp, TrendingDown, DollarSign, Wallet, Percent, AlertTriangle, FileSpreadsheet, FileText, Printer } from "lucide-react";
import { exportCSV, exportXLSX, exportPDF } from "@/lib/export-utils";

export const Route = createFileRoute("/_authenticated/profit-loss")({
  head: () => ({ meta: [{ title: "Profit & Loss — Niyamah ERP" }] }),
  component: ProfitLossPage,
});

type Branch = { id: string; name: string };

function startOfMonth() { const d = new Date(); d.setDate(1); return d.toISOString().slice(0, 10); }
function today() { return new Date().toISOString().slice(0, 10); }
const fmt = (n: number) => "৳ " + Math.round(n).toLocaleString();

function ProfitLossPage() {
  const { lang } = useLanguage();
  const [branches, setBranches] = useState<Branch[]>([]);
  const [from, setFrom] = useState(startOfMonth());
  const [to, setTo] = useState(today());
  const [branchId, setBranchId] = useState("");
  const [loading, setLoading] = useState(true);

  const [sales, setSales] = useState<any[]>([]);
  const [purchases, setPurchases] = useState<any[]>([]);
  const [expenses, setExpenses] = useState<any[]>([]);
  const [incomes, setIncomes] = useState<any[]>([]);
  const [damages, setDamages] = useState<any[]>([]);

  useEffect(() => {
    supabase.from("branches").select("id, name").is("deleted_at", null).then(({ data }) => setBranches(data || []));
  }, []);

  const fetchAll = async () => {
    setLoading(true);
    let salesQ = supabase.from("sales_orders").select("id, total_amount, discount, order_date, status, branch_id").gte("order_date", from).lte("order_date", to).neq("status", "cancelled");
    if (branchId) salesQ = salesQ.eq("branch_id", branchId);
    let purQ = supabase.from("purchases").select("id, total_amount, purchase_date").gte("purchase_date", from).lte("purchase_date", to);
    let expQ = supabase.from("expenses").select("id, amount, category, expense_date, branch_id").gte("expense_date", from).lte("expense_date", to);
    if (branchId) expQ = expQ.eq("branch_id", branchId);
    let incQ = supabase.from("incomes").select("id, amount, source, income_date, branch_id").gte("income_date", from).lte("income_date", to);
    if (branchId) incQ = incQ.eq("branch_id", branchId);
    const dmgQ = supabase.from("damage_stock").select("id, quantity, product_id, created_at, products:product_id(purchase_price, name)").gte("created_at", from).lte("created_at", to + "T23:59:59");

    const [s, p, e, i, d] = await Promise.all([salesQ, purQ, expQ, incQ, dmgQ]);
    setSales(s.data || []); setPurchases(p.data || []); setExpenses(e.data || []); setIncomes(i.data || []); setDamages(d.data || []);
    setLoading(false);
  };
  useEffect(() => { fetchAll(); }, [from, to, branchId]);

  const totalSales = useMemo(() => sales.reduce((s, r) => s + Number(r.total_amount || 0), 0), [sales]);
  const totalPurchase = useMemo(() => purchases.reduce((s, r) => s + Number(r.total_amount || 0), 0), [purchases]);
  const totalExpense = useMemo(() => expenses.reduce((s, r) => s + Number(r.amount || 0), 0), [expenses]);
  const totalIncome = useMemo(() => incomes.reduce((s, r) => s + Number(r.amount || 0), 0), [incomes]);
  const totalDamage = useMemo(() => damages.reduce((s, r: any) => s + Number(r.quantity || 0) * Number(r.products?.purchase_price || 0), 0), [damages]);
  const grossProfit = totalSales - totalPurchase;
  const netProfit = grossProfit + totalIncome - totalExpense - totalDamage;
  const margin = totalSales > 0 ? (netProfit / totalSales) * 100 : 0;
  const isLoss = netProfit < 0;

  const expenseByCat = useMemo(() => {
    const m = new Map<string, number>();
    expenses.forEach((e) => m.set(e.category || "other", (m.get(e.category || "other") || 0) + Number(e.amount || 0)));
    return Array.from(m.entries()).map(([k, v]) => ({ category: k, amount: v })).sort((a, b) => b.amount - a.amount);
  }, [expenses]);

  // Monthly trend (group by month within range)
  const monthly = useMemo(() => {
    const map = new Map<string, { sales: number; cost: number; exp: number }>();
    sales.forEach((r) => { const k = r.order_date?.slice(0, 7); if (!k) return; const v = map.get(k) || { sales: 0, cost: 0, exp: 0 }; v.sales += Number(r.total_amount || 0); map.set(k, v); });
    purchases.forEach((r) => { const k = r.purchase_date?.slice(0, 7); if (!k) return; const v = map.get(k) || { sales: 0, cost: 0, exp: 0 }; v.cost += Number(r.total_amount || 0); map.set(k, v); });
    expenses.forEach((r) => { const k = r.expense_date?.slice(0, 7); if (!k) return; const v = map.get(k) || { sales: 0, cost: 0, exp: 0 }; v.exp += Number(r.amount || 0); map.set(k, v); });
    return Array.from(map.entries()).map(([month, v]) => ({ month, ...v, profit: v.sales - v.cost - v.exp })).sort((a, b) => a.month.localeCompare(b.month));
  }, [sales, purchases, expenses]);

  const exportRows = () => [
    { Section: "Revenue", Label: "Total Sales", Amount: totalSales },
    { Section: "Revenue", Label: "Other Income", Amount: totalIncome },
    { Section: "Cost", Label: "Purchase Cost", Amount: totalPurchase },
    { Section: "Cost", Label: "Total Expenses", Amount: totalExpense },
    { Section: "Cost", Label: "Damage/Loss", Amount: totalDamage },
    { Section: "Result", Label: "Gross Profit", Amount: grossProfit },
    { Section: "Result", Label: "Net Profit/Loss", Amount: netProfit },
    { Section: "Result", Label: "Profit Margin %", Amount: Number(margin.toFixed(2)) },
  ];

  const inputCls = "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" ? "লাভ ও ক্ষতি প্রতিবেদন" : "Profit & Loss Report"}</h1>
          <p className="text-sm text-muted-foreground">{lang === "bn" ? "বিক্রয়, খরচ ও লাভের বিস্তারিত বিশ্লেষণ" : "Comprehensive sales, cost & profit analysis"}</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <button onClick={() => exportCSV("profit-loss", exportRows())} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-secondary"><FileText className="h-4 w-4" /> CSV</button>
          <button onClick={() => exportXLSX("profit-loss", exportRows())} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-secondary"><FileSpreadsheet className="h-4 w-4" /> Excel</button>
          <button onClick={() => exportPDF("profit-loss", "Profit & Loss Report", exportRows())} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-secondary"><FileText className="h-4 w-4" /> PDF</button>
          <button onClick={() => window.print()} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-secondary"><Printer className="h-4 w-4" /> Print</button>
        </div>
      </div>

      {/* Filters */}
      <div className="mb-6 flex flex-wrap items-end gap-3 rounded-xl border border-border bg-card p-4">
        <div><label className="mb-1 block text-xs text-muted-foreground">{lang === "bn" ? "তারিখ থেকে" : "From"}</label><input type="date" className={inputCls} value={from} onChange={(e) => setFrom(e.target.value)} /></div>
        <div><label className="mb-1 block text-xs text-muted-foreground">{lang === "bn" ? "তারিখ পর্যন্ত" : "To"}</label><input type="date" className={inputCls} value={to} onChange={(e) => setTo(e.target.value)} /></div>
        <div><label className="mb-1 block text-xs text-muted-foreground">{lang === "bn" ? "শাখা" : "Branch"}</label>
          <select className={inputCls} value={branchId} onChange={(e) => setBranchId(e.target.value)}>
            <option value="">{lang === "bn" ? "সব শাখা" : "All Branches"}</option>
            {branches.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
          </select>
        </div>
        <div className="ml-auto flex gap-2">
          {[
            { k: "today", label: lang === "bn" ? "আজ" : "Today", from: today(), to: today() },
            { k: "month", label: lang === "bn" ? "এই মাস" : "This Month", from: startOfMonth(), to: today() },
            { k: "year", label: lang === "bn" ? "এই বছর" : "This Year", from: new Date(new Date().getFullYear(), 0, 1).toISOString().slice(0, 10), to: today() },
          ].map((p) => (
            <button key={p.k} onClick={() => { setFrom(p.from); setTo(p.to); }} className="rounded-lg border border-border px-3 py-2 text-xs hover:bg-secondary">{p.label}</button>
          ))}
        </div>
      </div>

      {loading ? (
        <div className="flex h-40 items-center justify-center text-muted-foreground">{lang === "bn" ? "লোড হচ্ছে..." : "Loading..."}</div>
      ) : (
        <>
          {/* Summary cards */}
          <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-5">
            <Card icon={<TrendingUp className="h-4 w-4" />} label={lang === "bn" ? "মোট বিক্রয়" : "Total Sales"} value={fmt(totalSales)} tone="emerald" />
            <Card icon={<DollarSign className="h-4 w-4" />} label={lang === "bn" ? "ক্রয় মূল্য" : "Purchase Cost"} value={fmt(totalPurchase)} tone="blue" />
            <Card icon={<Wallet className="h-4 w-4" />} label={lang === "bn" ? "মোট খরচ" : "Total Expense"} value={fmt(totalExpense)} tone="amber" />
            <Card icon={<AlertTriangle className="h-4 w-4" />} label={lang === "bn" ? "ক্ষতি/ড্যামেজ" : "Damage Loss"} value={fmt(totalDamage)} tone="rose" />
            <Card icon={isLoss ? <TrendingDown className="h-4 w-4" /> : <TrendingUp className="h-4 w-4" />} label={lang === "bn" ? "নিট লাভ/ক্ষতি" : "Net Profit/Loss"} value={fmt(Math.abs(netProfit))} tone={isLoss ? "rose" : "emerald"} sub={`${margin.toFixed(1)}% ${lang === "bn" ? "মার্জিন" : "margin"}`} />
          </div>

          {/* P&L Statement */}
          <div className="mb-6 grid gap-6 lg:grid-cols-2">
            <div className="rounded-xl border border-border bg-card p-6">
              <h2 className="mb-4 text-base font-bold">{lang === "bn" ? "লাভ-ক্ষতি বিবরণী" : "P&L Statement"}</h2>
              <table className="w-full text-sm">
                <tbody className="divide-y divide-border">
                  <Row label={lang === "bn" ? "মোট বিক্রয়" : "Total Sales"} value={totalSales} positive />
                  <Row label={lang === "bn" ? "অন্যান্য আয়" : "Other Income"} value={totalIncome} positive />
                  <Row label={lang === "bn" ? "(-) ক্রয় মূল্য" : "(-) Purchase Cost"} value={-totalPurchase} />
                  <tr className="border-t-2 border-foreground/20"><td className="py-2 font-semibold">{lang === "bn" ? "গ্রস প্রফিট" : "Gross Profit"}</td><td className={`py-2 text-right font-semibold ${grossProfit < 0 ? "text-rose-600" : "text-emerald-600"}`}>{fmt(grossProfit)}</td></tr>
                  <Row label={lang === "bn" ? "(-) মোট খরচ" : "(-) Total Expenses"} value={-totalExpense} />
                  <Row label={lang === "bn" ? "(-) ড্যামেজ ক্ষতি" : "(-) Damage Loss"} value={-totalDamage} />
                  <tr className="border-t-2 border-foreground"><td className="py-3 text-base font-bold">{lang === "bn" ? "নিট লাভ/ক্ষতি" : "Net Profit / Loss"}</td><td className={`py-3 text-right text-base font-bold ${isLoss ? "text-rose-600" : "text-emerald-600"}`}>{fmt(netProfit)}</td></tr>
                  <tr><td className="py-1 text-xs text-muted-foreground"><Percent className="inline h-3 w-3" /> {lang === "bn" ? "প্রফিট মার্জিন" : "Profit Margin"}</td><td className="py-1 text-right text-xs text-muted-foreground">{margin.toFixed(2)}%</td></tr>
                </tbody>
              </table>
            </div>

            {/* Expense breakdown */}
            <div className="rounded-xl border border-border bg-card p-6">
              <h2 className="mb-4 text-base font-bold">{lang === "bn" ? "খরচের বিভাজন" : "Expense Breakdown"}</h2>
              {expenseByCat.length === 0 ? (
                <p className="py-8 text-center text-sm text-muted-foreground">{lang === "bn" ? "কোনো খরচ নেই" : "No expenses"}</p>
              ) : (
                <div className="space-y-3">
                  {expenseByCat.map((e) => {
                    const pct = totalExpense > 0 ? (e.amount / totalExpense) * 100 : 0;
                    return (
                      <div key={e.category}>
                        <div className="mb-1 flex justify-between text-sm"><span className="capitalize">{e.category}</span><span className="font-medium">{fmt(e.amount)} ({pct.toFixed(1)}%)</span></div>
                        <div className="h-2 overflow-hidden rounded-full bg-muted"><div className="h-full bg-amber-500" style={{ width: `${pct}%` }} /></div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>

          {/* Monthly trend */}
          <div className="rounded-xl border border-border bg-card p-6">
            <h2 className="mb-4 text-base font-bold">{lang === "bn" ? "মাসিক প্রবণতা" : "Monthly Trend"}</h2>
            {monthly.length === 0 ? (
              <p className="py-8 text-center text-sm text-muted-foreground">{lang === "bn" ? "তথ্য নেই" : "No data"}</p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="text-xs text-muted-foreground"><tr><th className="px-2 py-2 text-left">{lang === "bn" ? "মাস" : "Month"}</th><th className="px-2 py-2 text-right">{lang === "bn" ? "বিক্রয়" : "Sales"}</th><th className="px-2 py-2 text-right">{lang === "bn" ? "ক্রয়" : "Cost"}</th><th className="px-2 py-2 text-right">{lang === "bn" ? "খরচ" : "Expense"}</th><th className="px-2 py-2 text-right">{lang === "bn" ? "লাভ" : "Profit"}</th></tr></thead>
                  <tbody>
                    {monthly.map((m) => (
                      <tr key={m.month} className="border-t border-border">
                        <td className="px-2 py-2 font-medium">{m.month}</td>
                        <td className="px-2 py-2 text-right text-emerald-600">{fmt(m.sales)}</td>
                        <td className="px-2 py-2 text-right">{fmt(m.cost)}</td>
                        <td className="px-2 py-2 text-right">{fmt(m.exp)}</td>
                        <td className={`px-2 py-2 text-right font-semibold ${m.profit < 0 ? "text-rose-600" : "text-emerald-600"}`}>{fmt(m.profit)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </>
      )}
    </PageLayout>
  );
}

function Card({ icon, label, value, tone, sub }: { icon: React.ReactNode; label: string; value: string; tone: "emerald" | "blue" | "amber" | "rose"; sub?: string }) {
  const tones: Record<string, string> = {
    emerald: "text-emerald-600 bg-emerald-500/10",
    blue: "text-blue-600 bg-blue-500/10",
    amber: "text-amber-600 bg-amber-500/10",
    rose: "text-rose-600 bg-rose-500/10",
  };
  return (
    <div className="rounded-xl border border-border bg-card p-4">
      <div className={`mb-2 inline-flex h-8 w-8 items-center justify-center rounded-lg ${tones[tone]}`}>{icon}</div>
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className="mt-1 text-lg font-bold text-foreground">{value}</p>
      {sub && <p className="mt-0.5 text-xs text-muted-foreground">{sub}</p>}
    </div>
  );
}

function Row({ label, value, positive }: { label: string; value: number; positive?: boolean }) {
  return (
    <tr><td className="py-2 text-muted-foreground">{label}</td><td className={`py-2 text-right font-medium ${positive ? "text-emerald-600" : value < 0 ? "text-rose-600" : ""}`}>{fmt(Math.abs(value))}</td></tr>
  );
}
