import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { FileSpreadsheet, Share2, TrendingUp, TrendingDown, Minus } from "lucide-react";
import { useT, fmtMoney } from "@/lib/i18n";
import { downloadCSV } from "@/lib/export-csv";

export const Route = createFileRoute("/_authenticated/daily-report")({
  head: () => ({ meta: [{ title: "দৈনিক রিপোর্ট" }] }),
  component: DailyReportPage,
});

function startOfDay(d: Date) { return new Date(d.getFullYear(), d.getMonth(), d.getDate()); }
function endOfDay(d: Date) { const x = startOfDay(d); x.setDate(x.getDate() + 1); return x; }

function DailyReportPage() {
  const { t, lang } = useT();

  const { data } = useQuery({
    queryKey: ["daily-report"],
    queryFn: async () => {
      const today = new Date();
      const yesterday = new Date(Date.now() - 86400000);
      const t0 = startOfDay(today).toISOString();
      const t1 = endOfDay(today).toISOString();
      const y0 = startOfDay(yesterday).toISOString();
      const y1 = endOfDay(yesterday).toISOString();

      const [tS, yS, tP, yP, tE, yE] = await Promise.all([
        supabase.from("sales").select("total, profit, total_cost, paid, due").gte("created_at", t0).lt("created_at", t1),
        supabase.from("sales").select("total, profit, total_cost").gte("created_at", y0).lt("created_at", y1),
        supabase.from("purchases").select("total, paid, due").gte("created_at", t0).lt("created_at", t1),
        supabase.from("purchases").select("total").gte("created_at", y0).lt("created_at", y1),
        supabase.from("expenses").select("amount").gte("created_at", t0).lt("created_at", t1),
        supabase.from("expenses").select("amount").gte("created_at", y0).lt("created_at", y1),
      ]);

      const sum = (arr: any[] | null, k: string) => (arr || []).reduce((a, r) => a + Number(r[k] || 0), 0);
      const today_sales = sum(tS.data, "total");
      const today_profit = sum(tS.data, "profit");
      const today_purchase = sum(tP.data, "total");
      const today_expense = sum(tE.data, "amount");
      const today_net = today_profit - today_expense;
      const today_orders = (tS.data || []).length;
      const today_paid = sum(tS.data, "paid");
      const today_due = sum(tS.data, "due");

      const y_sales = sum(yS.data, "total");
      const y_profit = sum(yS.data, "profit");
      const y_purchase = sum(yP.data, "total");
      const y_expense = sum(yE.data, "amount");
      const y_net = y_profit - y_expense;

      return {
        today_sales, today_profit, today_purchase, today_expense, today_net, today_orders, today_paid, today_due,
        y_sales, y_profit, y_purchase, y_expense, y_net,
      };
    },
  });

  const d = data || { today_sales: 0, today_profit: 0, today_purchase: 0, today_expense: 0, today_net: 0, today_orders: 0, today_paid: 0, today_due: 0, y_sales: 0, y_profit: 0, y_purchase: 0, y_expense: 0, y_net: 0 };

  const pct = (a: number, b: number) => {
    if (!b) return a > 0 ? 100 : 0;
    return ((a - b) / Math.abs(b)) * 100;
  };
  const profitPct = pct(d.today_profit, d.y_profit);
  const salesPct = pct(d.today_sales, d.y_sales);

  const reportText = () => {
    const dt = new Date().toLocaleDateString(lang === "bn" ? "bn-BD" : "en-IN");
    const sign = profitPct >= 0 ? "↑" : "↓";
    return (lang === "bn"
      ? `📊 দৈনিক রিপোর্ট — ${dt}\n\n` +
        `🛒 বিক্রি: ${fmtMoney(d.today_sales, lang)} (${salesPct >= 0 ? "+" : ""}${salesPct.toFixed(1)}%)\n` +
        `💰 লাভ: ${fmtMoney(d.today_profit, lang)} ${sign} গতকালের চেয়ে ${Math.abs(profitPct).toFixed(1)}%\n` +
        `📦 ক্রয়: ${fmtMoney(d.today_purchase, lang)}\n` +
        `💸 খরচ: ${fmtMoney(d.today_expense, lang)}\n` +
        `✨ নিট লাভ: ${fmtMoney(d.today_net, lang)}\n` +
        `🧾 অর্ডার: ${d.today_orders}টি`
      : `📊 Daily Report — ${dt}\n\n` +
        `🛒 Sales: ${fmtMoney(d.today_sales, lang)} (${salesPct >= 0 ? "+" : ""}${salesPct.toFixed(1)}%)\n` +
        `💰 Profit: ${fmtMoney(d.today_profit, lang)} ${sign} ${Math.abs(profitPct).toFixed(1)}% vs yesterday\n` +
        `📦 Purchases: ${fmtMoney(d.today_purchase, lang)}\n` +
        `💸 Expenses: ${fmtMoney(d.today_expense, lang)}\n` +
        `✨ Net Profit: ${fmtMoney(d.today_net, lang)}\n` +
        `🧾 Orders: ${d.today_orders}`);
  };

  const shareWhatsApp = () => {
    const url = `https://wa.me/?text=${encodeURIComponent(reportText())}`;
    window.open(url, "_blank");
  };
  const shareSMS = () => {
    const url = `sms:?body=${encodeURIComponent(reportText())}`;
    window.location.href = url;
  };
  const exportXls = () => {
    const rows: (string | number)[][] = [
      ["Metric", "Today", "Yesterday", "Change %"],
      ["Sales", d.today_sales, d.y_sales, salesPct.toFixed(2)],
      ["Profit", d.today_profit, d.y_profit, profitPct.toFixed(2)],
      ["Purchase", d.today_purchase, d.y_purchase, pct(d.today_purchase, d.y_purchase).toFixed(2)],
      ["Expense", d.today_expense, d.y_expense, pct(d.today_expense, d.y_expense).toFixed(2)],
      ["Net Profit", d.today_net, d.y_net, pct(d.today_net, d.y_net).toFixed(2)],
      ["Orders", d.today_orders, "", ""],
      ["Paid (collected)", d.today_paid, "", ""],
      ["Due (uncollected)", d.today_due, "", ""],
    ];
    downloadCSV(`daily-report-${new Date().toISOString().slice(0, 10)}`, rows);
  };

  return (
    <div className="space-y-6 max-w-6xl mx-auto">
      <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3">
        <h1 className="text-2xl md:text-3xl font-extrabold">{t("daily_report")}</h1>
        <div className="flex gap-2 flex-wrap">
          <Button variant="outline" size="sm" onClick={exportXls}><FileSpreadsheet className="size-4 mr-1" /> Excel</Button>
          <Button variant="outline" size="sm" onClick={shareWhatsApp}><Share2 className="size-4 mr-1" /> WhatsApp</Button>
          <Button variant="outline" size="sm" onClick={shareSMS}>📱 SMS</Button>
        </div>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <Compare label={t("today_sales")} today={d.today_sales} yest={d.y_sales} lang={lang} money />
        <Compare label={t("profit")} today={d.today_profit} yest={d.y_profit} lang={lang} money highlight />
        <Compare label={lang === "bn" ? "ক্রয়" : "Purchase"} today={d.today_purchase} yest={d.y_purchase} lang={lang} money />
        <Compare label={t("expenses")} today={d.today_expense} yest={d.y_expense} lang={lang} money invert />
      </div>

      <Card className="shadow-card">
        <CardHeader><CardTitle>{lang === "bn" ? "আজকের সারাংশ" : "Today's Summary"}</CardTitle></CardHeader>
        <CardContent className="grid sm:grid-cols-3 gap-4">
          <Row label={lang === "bn" ? "নিট লাভ" : "Net Profit"} value={fmtMoney(d.today_net, lang)} />
          <Row label={lang === "bn" ? "অর্ডার সংখ্যা" : "Orders"} value={String(d.today_orders)} />
          <Row label={lang === "bn" ? "সংগ্রহ (ক্যাশ)" : "Collected"} value={fmtMoney(d.today_paid, lang)} />
          <Row label={lang === "bn" ? "আজকের বকেয়া" : "Today's Due"} value={fmtMoney(d.today_due, lang)} />
        </CardContent>
      </Card>

      <Card className="shadow-card">
        <CardHeader><CardTitle className="text-base">{lang === "bn" ? "শেয়ারযোগ্য রিপোর্ট" : "Shareable Report"}</CardTitle></CardHeader>
        <CardContent>
          <pre className="whitespace-pre-wrap font-mono text-sm bg-muted/40 p-4 rounded-lg">{reportText()}</pre>
        </CardContent>
      </Card>
    </div>
  );
}

function Compare({ label, today, yest, lang, money, highlight, invert }: any) {
  const diff = today - yest;
  const pct = yest ? (diff / Math.abs(yest)) * 100 : (today > 0 ? 100 : 0);
  const up = invert ? diff < 0 : diff > 0;
  const flat = diff === 0;
  return (
    <Card className={highlight ? "gradient-forest text-white border-0 shadow-elegant" : ""}>
      <CardContent className="p-4">
        <div className={`text-xs ${highlight ? "text-white/80" : "text-muted-foreground"}`}>{label}</div>
        <div className="text-xl font-extrabold mt-1">{money ? fmtMoney(today, lang) : today}</div>
        <div className={`text-xs mt-2 flex items-center gap-1 ${flat ? "opacity-60" : up ? "text-success" : "text-destructive"} ${highlight ? "!text-white/90" : ""}`}>
          {flat ? <Minus className="size-3" /> : up ? <TrendingUp className="size-3" /> : <TrendingDown className="size-3" />}
          {pct >= 0 ? "+" : ""}{pct.toFixed(1)}%
        </div>
      </CardContent>
    </Card>
  );
}
function Row({ label, value }: any) {
  return <div><div className="text-xs text-muted-foreground">{label}</div><div className="font-bold text-lg mt-0.5">{value}</div></div>;
}
