import { createFileRoute, Link } 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 { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { TrendingUp, Package, ShoppingCart, AlertTriangle, Plus, Users, Truck, Wallet, ListOrdered } from "lucide-react";
import { useT, fmtMoney } from "@/lib/i18n";
import { LineChart, Line, ResponsiveContainer, Tooltip, XAxis, YAxis, BarChart, Bar, CartesianGrid } from "recharts";

export const Route = createFileRoute("/_authenticated/")({
  head: () => ({ meta: [{ title: "ড্যাশবোর্ড — Helpgate Inventory" }] }),
  component: Dashboard,
});

function Dashboard() {
  const { t, lang } = useT();
  const fmt = (n: number) => fmtMoney(n, lang);

  const { data: profile } = useQuery({
    queryKey: ["profile"],
    queryFn: async () => (await supabase.from("profiles").select("*").maybeSingle()).data,
  });

  const { data: stats } = useQuery({
    queryKey: ["dashboard-stats"],
    queryFn: async () => {
      const today = new Date(); today.setHours(0, 0, 0, 0);
      const startMonth = new Date(today.getFullYear(), today.getMonth(), 1);
      const last30 = new Date(); last30.setDate(last30.getDate() - 29); last30.setHours(0, 0, 0, 0);

      const [todayS, monthS, products, lowStock, last30Sales, custDue, supDue, recent] = await Promise.all([
        supabase.from("sales").select("total, profit").gte("created_at", today.toISOString()),
        supabase.from("sales").select("total, profit").gte("created_at", startMonth.toISOString()),
        supabase.from("products").select("id", { count: "exact", head: true }),
        supabase.from("products").select("*").order("stock", { ascending: true }).limit(50),
        supabase.from("sales").select("total, profit, created_at").gte("created_at", last30.toISOString()),
        supabase.from("customers").select("due"),
        supabase.from("suppliers").select("due"),
        supabase.from("sales").select("id, customer_name, total, created_at").order("created_at", { ascending: false }).limit(6),
      ]);

      const sum = (rows: any[] | null, key: string) => (rows || []).reduce((a, r) => a + Number(r[key] || 0), 0);
      const low = (lowStock.data || []).filter((p: any) => Number(p.stock) <= Number(p.low_stock_threshold));

      // chart data — last 14 days
      const days = 14;
      const byDay = new Map<string, { date: string; revenue: number; profit: number }>();
      for (let i = days - 1; i >= 0; i--) {
        const d = new Date(); d.setDate(d.getDate() - i); d.setHours(0, 0, 0, 0);
        const k = d.toISOString().slice(0, 10);
        byDay.set(k, { date: d.toLocaleDateString(lang === "bn" ? "bn-BD" : "en-IN", { day: "numeric", month: "short" }), revenue: 0, profit: 0 });
      }
      for (const r of last30Sales.data || []) {
        const k = new Date(r.created_at).toISOString().slice(0, 10);
        const ex = byDay.get(k); if (ex) { ex.revenue += Number(r.total); ex.profit += Number(r.profit); }
      }

      return {
        todayRev: sum(todayS.data, "total"), todayProf: sum(todayS.data, "profit"), todayCnt: (todayS.data || []).length,
        monthRev: sum(monthS.data, "total"), monthProf: sum(monthS.data, "profit"),
        productCount: products.count || 0, lowStock: low,
        custDue: sum(custDue.data, "due"), supDue: sum(supDue.data, "due"),
        chart: Array.from(byDay.values()),
        recent: recent.data || [],
      };
    },
  });

  return (
    <div className="space-y-6 max-w-[1400px] mx-auto">
      <header className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-4">
        <div className="min-w-0">
          <h1 className="text-2xl md:text-4xl font-extrabold truncate">
            {t("welcome")}, <span className="text-primary">{profile?.shop_name || "..."}</span>
          </h1>
          <p className="text-muted-foreground text-sm mt-1">
            {new Date().toLocaleDateString(lang === "bn" ? "bn-BD" : "en-US", { dateStyle: "full" })}
          </p>
        </div>
        <Link to="/pos">
          <Button size="lg" className="gradient-primary text-white shadow-elegant"><Plus className="size-4 mr-1" /> {t("new_sale")}</Button>
        </Link>
      </header>

      {/* KPI cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KpiCard gradient="gradient-primary" icon={ShoppingCart} label={t("today_sales")} value={fmt(stats?.todayRev ?? 0)} sub={`${stats?.todayCnt ?? 0} ${t("orders")}`} />
        <KpiCard gradient="gradient-forest" icon={TrendingUp} label={t("today_profit")} value={fmt(stats?.todayProf ?? 0)} />
        <KpiCard gradient="gradient-ocean" icon={ShoppingCart} label={t("month_sales")} value={fmt(stats?.monthRev ?? 0)} sub={`${t("profit")}: ${fmt(stats?.monthProf ?? 0)}`} />
        <KpiCard gradient="gradient-violet" icon={Package} label={t("total_products")} value={String(stats?.productCount ?? 0)} />
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <SmallStat icon={Users} label={t("customer_due")} value={fmt(stats?.custDue ?? 0)} color="text-info" />
        <SmallStat icon={Truck} label={t("supplier_due")} value={fmt(stats?.supDue ?? 0)} color="text-warning" />
        <SmallStat icon={AlertTriangle} label={t("low_stock")} value={String(stats?.lowStock?.length ?? 0)} color="text-destructive" />
        <SmallStat icon={ListOrdered} label={t("orders")} value={String(stats?.todayCnt ?? 0)} color="text-primary" />
      </div>

      {/* Charts */}
      <div className="grid lg:grid-cols-3 gap-4">
        <Card className="lg:col-span-2 shadow-card">
          <CardHeader><CardTitle className="text-lg">{lang === "bn" ? "১৪ দিনের বিক্রি ও লাভ" : "Last 14 Days Sales & Profit"}</CardTitle></CardHeader>
          <CardContent className="h-72">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={stats?.chart || []}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
                <XAxis dataKey="date" fontSize={11} stroke="var(--muted-foreground)" />
                <YAxis fontSize={11} stroke="var(--muted-foreground)" />
                <Tooltip contentStyle={{ backgroundColor: "var(--popover)", border: "1px solid var(--border)", borderRadius: 8 }} />
                <Line type="monotone" dataKey="revenue" stroke="var(--chart-1)" strokeWidth={2.5} dot={false} name={t("revenue")} />
                <Line type="monotone" dataKey="profit" stroke="var(--chart-2)" strokeWidth={2.5} dot={false} name={t("profit")} />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card className="shadow-card">
          <CardHeader><CardTitle className="text-lg flex items-center gap-2"><AlertTriangle className="size-5 text-destructive" />{t("low_stock_items")}</CardTitle></CardHeader>
          <CardContent>
            {stats?.lowStock?.length ? (
              <div className="space-y-2 max-h-60 overflow-y-auto">
                {stats.lowStock.slice(0, 6).map((p: any) => (
                  <div key={p.id} className="flex items-center justify-between p-2 rounded-lg bg-destructive/5 border border-destructive/20">
                    <div className="min-w-0 flex-1"><div className="font-medium truncate text-sm">{p.name}</div></div>
                    <Badge variant="destructive" className="text-xs">{p.stock}</Badge>
                  </div>
                ))}
              </div>
            ) : <p className="text-muted-foreground text-sm">✓ সব ঠিক আছে</p>}
          </CardContent>
        </Card>
      </div>

      {/* Recent */}
      <Card className="shadow-card">
        <CardHeader><CardTitle className="text-lg">{t("recent_sales")}</CardTitle></CardHeader>
        <CardContent>
          {stats?.recent?.length ? (
            <div className="space-y-2">
              {stats.recent.map((s: any) => (
                <div key={s.id} className="flex justify-between items-center p-2 rounded-lg hover:bg-accent/40">
                  <div className="min-w-0">
                    <div className="font-medium truncate">{s.customer_name || t("walk_in")}</div>
                    <div className="text-xs text-muted-foreground">{new Date(s.created_at).toLocaleString(lang === "bn" ? "bn-BD" : "en-IN")}</div>
                  </div>
                  <div className="font-bold text-primary">{fmt(s.total)}</div>
                </div>
              ))}
            </div>
          ) : <p className="text-sm text-muted-foreground">{t("no_data")}</p>}
        </CardContent>
      </Card>
    </div>
  );
}

function KpiCard({ gradient, icon: Icon, label, value, sub }: any) {
  return (
    <Card className={`${gradient} text-white border-0 shadow-elegant overflow-hidden relative`}>
      <CardContent className="p-5 relative">
        <div className="absolute -right-4 -top-4 size-24 rounded-full bg-white/10" />
        <div className="absolute -right-8 -bottom-8 size-32 rounded-full bg-white/5" />
        <div className="relative">
          <div className="size-10 rounded-lg bg-white/20 grid place-items-center mb-3">
            <Icon className="size-5" />
          </div>
          <p className="text-xs text-white/80 font-medium">{label}</p>
          <p className="text-2xl md:text-3xl font-extrabold mt-1">{value}</p>
          {sub && <p className="text-xs text-white/70 mt-1">{sub}</p>}
        </div>
      </CardContent>
    </Card>
  );
}

function SmallStat({ icon: Icon, label, value, color }: any) {
  return (
    <Card className="shadow-card">
      <CardContent className="p-4 flex items-center gap-3">
        <div className={`size-10 rounded-lg bg-current/10 grid place-items-center ${color}`}>
          <Icon className="size-5" />
        </div>
        <div className="min-w-0">
          <p className="text-xs text-muted-foreground truncate">{label}</p>
          <p className="text-lg font-bold truncate">{value}</p>
        </div>
      </CardContent>
    </Card>
  );
}
