import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import saleIcon from "@/assets/sale-icon.png";
import clientsIcon from "@/assets/clients-icon.png";
import { useLanguage } from "@/hooks/use-language";
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import {
  TrendingUp,
  TrendingDown,
  Wallet,
  ShoppingCart,
  Package,
  DollarSign,
  ArrowUpRight,
  ArrowDownRight,
  Users,
  Truck,
  AlertTriangle,
  RotateCcw,
  Plus,
  CreditCard,
  Bell,
  Loader2,
} from "lucide-react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  LineChart,
  Line,
} from "recharts";

export const Route = createFileRoute("/_authenticated/")({
  head: () => ({
    meta: [
      { title: "ড্যাশবোর্ড — Niyamah Electric & Hardware" },
      { name: "description", content: "Niyamah Electric & Hardware ERP Dashboard" },
    ],
  }),
  component: DashboardPage,
});

const today = new Date().toISOString().split("T")[0];

function useDashboardData() {
  // Today's sales
  const { data: todaySalesData } = useQuery({
    queryKey: ["dashboard-today-sales"],
    queryFn: async () => {
      const { data } = await supabase
        .from("customer_transactions")
        .select("amount")
        .eq("type", "sale")
        .gte("created_at", today + "T00:00:00")
        .lte("created_at", today + "T23:59:59");
      return data || [];
    },
  });

  // Today's purchases
  const { data: todayPurchases } = useQuery({
    queryKey: ["dashboard-today-purchases"],
    queryFn: async () => {
      const { data } = await supabase
        .from("purchases")
        .select("total_amount")
        .eq("purchase_date", today);
      return data || [];
    },
  });

  // Today's expenses
  const { data: todayExpenses } = useQuery({
    queryKey: ["dashboard-today-expenses"],
    queryFn: async () => {
      const { data } = await supabase
        .from("expenses")
        .select("amount")
        .eq("expense_date", today);
      return data || [];
    },
  });

  // Products summary
  const { data: productsSummary } = useQuery({
    queryKey: ["dashboard-products"],
    queryFn: async () => {
      const { data } = await supabase
        .from("products")
        .select("id, stock_quantity, retail_price, purchase_price, name, name_bn")
        .eq("is_deleted", false);
      return data || [];
    },
  });

  // Customer count
  const { data: customers } = useQuery({
    queryKey: ["dashboard-customers"],
    queryFn: async () => {
      const { data } = await supabase
        .from("customers")
        .select("id, total_due, name")
        .eq("status", "active");
      return data || [];
    },
  });

  // Supplier count
  const { data: suppliers } = useQuery({
    queryKey: ["dashboard-suppliers"],
    queryFn: async () => {
      const { data } = await supabase
        .from("suppliers")
        .select("id, current_due, name")
        .eq("is_deleted", false);
      return data || [];
    },
  });

  // Recent sales returns
  const { data: recentReturns } = useQuery({
    queryKey: ["dashboard-returns"],
    queryFn: async () => {
      const { data } = await supabase
        .from("sales_returns")
        .select("id, return_type, refund_amount, status, created_at")
        .order("created_at", { ascending: false })
        .limit(5);
      return data || [];
    },
  });

  // Recent purchases
  const { data: recentPurchases } = useQuery({
    queryKey: ["dashboard-recent-purchases"],
    queryFn: async () => {
      const { data } = await supabase
        .from("purchases")
        .select("id, invoice_no, total_amount, due_amount, purchase_date, supplier_id")
        .order("created_at", { ascending: false })
        .limit(5);
      return data || [];
    },
  });

  // Monthly sales data (last 6 months)
  const { data: monthlySales } = useQuery({
    queryKey: ["dashboard-monthly-sales"],
    queryFn: async () => {
      const sixMonthsAgo = new Date();
      sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
      const { data } = await supabase
        .from("customer_transactions")
        .select("amount, created_at")
        .eq("type", "sale")
        .gte("created_at", sixMonthsAgo.toISOString());
      return data || [];
    },
  });

  // Low stock products
  const lowStock = (productsSummary || []).filter(
    (p) => Number(p.stock_quantity) < 10 && Number(p.stock_quantity) >= 0
  );

  // Stock value
  const totalStockValue = (productsSummary || []).reduce(
    (sum, p) => sum + Number(p.stock_quantity) * Number(p.retail_price),
    0
  );

  // Today sales total
  const todaySalesTotal = (todaySalesData || []).reduce(
    (sum, t) => sum + Number(t.amount),
    0
  );

  // Today purchases total
  const todayPurchaseTotal = (todayPurchases || []).reduce(
    (sum, p) => sum + Number(p.total_amount),
    0
  );

  // Today expense total
  const todayExpenseTotal = (todayExpenses || []).reduce(
    (sum, e) => sum + Number(e.amount),
    0
  );

  // Rough today profit = sales - purchase - expense
  const todayProfit = todaySalesTotal - todayPurchaseTotal - todayExpenseTotal;

  // Customer total due
  const totalCustomerDue = (customers || []).reduce(
    (sum, c) => sum + Number(c.total_due),
    0
  );

  // Supplier total due
  const totalSupplierDue = (suppliers || []).reduce(
    (sum, s) => sum + Number(s.current_due),
    0
  );

  // Monthly chart data
  const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const monthNamesBn = ["জানু", "ফেব্রু", "মার্চ", "এপ্রি", "মে", "জুন", "জুলাই", "আগ", "সেপ্ট", "অক্টো", "নভে", "ডিসে"];
  const monthlyChartData: { month: string; monthBn: string; sales: number }[] = [];
  for (let i = 5; i >= 0; i--) {
    const d = new Date();
    d.setMonth(d.getMonth() - i);
    const mIdx = d.getMonth();
    const yr = d.getFullYear();
    const monthSales = (monthlySales || [])
      .filter((s) => {
        const sd = new Date(s.created_at);
        return sd.getMonth() === mIdx && sd.getFullYear() === yr;
      })
      .reduce((sum, s) => sum + Number(s.amount), 0);
    monthlyChartData.push({ month: monthNames[mIdx], monthBn: monthNamesBn[mIdx], sales: monthSales });
  }

  // Due customers (top 5)
  const dueCustomers = (customers || [])
    .filter((c) => Number(c.total_due) > 0)
    .sort((a, b) => Number(b.total_due) - Number(a.total_due))
    .slice(0, 5);

  // Due suppliers (top 5)
  const dueSuppliers = (suppliers || [])
    .filter((s) => Number(s.current_due) > 0)
    .sort((a, b) => Number(b.current_due) - Number(a.current_due))
    .slice(0, 5);

  return {
    todaySalesTotal,
    todaySalesCount: (todaySalesData || []).length,
    todayPurchaseTotal,
    todayExpenseTotal,
    todayProfit,
    totalProducts: (productsSummary || []).length,
    totalStockValue,
    lowStock,
    totalCustomers: (customers || []).length,
    totalSuppliers: (suppliers || []).length,
    totalCustomerDue,
    totalSupplierDue,
    monthlyChartData,
    recentReturns: recentReturns || [],
    recentPurchases: recentPurchases || [],
    dueCustomers,
    dueSuppliers,
  };
}

function fmt(n: number) {
  return "৳" + n.toLocaleString("en-IN");
}

function DashboardPage() {
  const { tr, lang } = useLanguage();
  const d = useDashboardData();

  const COLORS = ["hsl(var(--primary))", "hsl(var(--chart-2))", "hsl(var(--chart-3))", "hsl(var(--chart-4))", "hsl(var(--chart-5))"];

  const stats = [
    { label: lang === "bn" ? "আজকের বিক্রি" : "Today Sales", value: fmt(d.todaySalesTotal), icon: DollarSign, image: saleIcon, color: "bg-primary/10 text-primary" },
    { label: lang === "bn" ? "আজকের ক্রয়" : "Today Purchase", value: fmt(d.todayPurchaseTotal), icon: ShoppingCart, color: "bg-chart-2/10 text-chart-2" },
    { label: lang === "bn" ? "আজকের খরচ" : "Today Expense", value: fmt(d.todayExpenseTotal), icon: Wallet, color: "bg-orange-500/10 text-orange-500" },
    { label: lang === "bn" ? "আজকের লাভ/ক্ষতি" : "Today Profit/Loss", value: fmt(d.todayProfit), icon: d.todayProfit >= 0 ? TrendingUp : TrendingDown, color: d.todayProfit >= 0 ? "bg-emerald-500/10 text-emerald-600" : "bg-destructive/10 text-destructive" },
    { label: lang === "bn" ? "মোট স্টক মূল্য" : "Stock Value", value: fmt(d.totalStockValue), icon: Package, color: "bg-chart-3/10 text-chart-3" },
    { label: lang === "bn" ? "কম স্টক সতর্কতা" : "Low Stock Alert", value: String(d.lowStock.length), icon: AlertTriangle, color: "bg-destructive/10 text-destructive" },
    { label: lang === "bn" ? "মোট কাস্টমার" : "Total Customers", value: String(d.totalCustomers), icon: Users, image: clientsIcon, color: "bg-chart-4/10 text-chart-4" },
    { label: lang === "bn" ? "মোট সরবরাহকারী" : "Total Suppliers", value: String(d.totalSuppliers), icon: Truck, color: "bg-chart-5/10 text-chart-5" },
    { label: lang === "bn" ? "কাস্টমার বকেয়া" : "Customer Due", value: fmt(d.totalCustomerDue), icon: CreditCard, color: "bg-orange-500/10 text-orange-500" },
    { label: lang === "bn" ? "সরবরাহকারী বকেয়া" : "Supplier Due", value: fmt(d.totalSupplierDue), icon: CreditCard, color: "bg-red-500/10 text-red-500" },
  ];

  const quickActions = [
    { label: lang === "bn" ? "নতুন বিক্রয়" : "New Sale", to: "/sales/create", icon: Plus, color: "bg-primary text-primary-foreground" },
    { label: lang === "bn" ? "নতুন ক্রয়" : "Add Purchase", to: "/purchases/add", icon: Plus, color: "bg-chart-2 text-white" },
    { label: lang === "bn" ? "নতুন কাস্টমার" : "Add Customer", to: "/customers", icon: Users, color: "bg-chart-3 text-white" },
    { label: lang === "bn" ? "নতুন সরবরাহকারী" : "Add Supplier", to: "/suppliers/add", icon: Truck, color: "bg-chart-5 text-white" },
  ];

  // Pie data for due distribution
  const pieData = [
    { name: lang === "bn" ? "কাস্টমার বকেয়া" : "Customer Due", value: d.totalCustomerDue },
    { name: lang === "bn" ? "সরবরাহকারী বকেয়া" : "Supplier Due", value: d.totalSupplierDue },
  ].filter((p) => p.value > 0);

  return (
    <PageLayout>
      {/* Header */}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold text-foreground">
            {lang === "bn" ? "ম্যানেজমেন্ট ড্যাশবোর্ড" : "Management Dashboard"}
          </h1>
          <p className="text-sm text-muted-foreground">
            {lang === "bn" ? "ব্যবসার সম্পূর্ণ সারাংশ ও কন্ট্রোল" : "Complete business overview & control"}
          </p>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="mb-6 flex flex-wrap gap-2">
        {quickActions.map((a) => (
          <Link
            key={a.to}
            to={a.to}
            className={`flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-semibold transition-opacity hover:opacity-90 ${a.color}`}
          >
            <a.icon className="h-4 w-4" />
            {a.label}
          </Link>
        ))}
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-4 xl:grid-cols-4">
        {stats.map((s) => (
          <div key={s.label} className="rounded-xl border border-border bg-card p-4">
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">{s.label}</span>
              <div className={`flex h-8 w-8 items-center justify-center rounded-lg ${s.color}`}>
                {"image" in s && (s as any).image ? (
                  <img src={(s as any).image} alt="" className="h-5 w-5 object-contain" />
                ) : (
                  <s.icon className="h-4 w-4" />
                )}
              </div>
            </div>
            <p className="mt-1.5 text-xl font-bold text-foreground">{s.value}</p>
          </div>
        ))}
      </div>

      {/* Charts Row */}
      <div className="mt-6 grid grid-cols-1 gap-4 lg:grid-cols-3">
        {/* Monthly Sales Chart */}
        <div className="col-span-2 rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-bold text-foreground">
            {lang === "bn" ? "মাসিক বিক্রয় (৬ মাস)" : "Monthly Sales (6 Months)"}
          </h2>
          <ResponsiveContainer width="100%" height={250}>
            <BarChart data={d.monthlyChartData}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
              <XAxis dataKey={lang === "bn" ? "monthBn" : "month"} className="text-xs" />
              <YAxis className="text-xs" />
              <Tooltip
                formatter={(value: number) => [fmt(value), lang === "bn" ? "বিক্রয়" : "Sales"]}
                contentStyle={{ borderRadius: 8, border: "1px solid hsl(var(--border))", background: "hsl(var(--card))" }}
              />
              <Bar dataKey="sales" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>

        {/* Due Distribution Pie */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-bold text-foreground">
            {lang === "bn" ? "বকেয়া বিতরণ" : "Due Distribution"}
          </h2>
          {pieData.length > 0 ? (
            <ResponsiveContainer width="100%" height={250}>
              <PieChart>
                <Pie data={pieData} cx="50%" cy="50%" outerRadius={80} dataKey="value" label={({ name, value }) => `${name}: ${fmt(value)}`}>
                  {pieData.map((_, i) => (
                    <Cell key={i} fill={COLORS[i]} />
                  ))}
                </Pie>
                <Tooltip formatter={(value: number) => fmt(value)} />
              </PieChart>
            </ResponsiveContainer>
          ) : (
            <div className="flex h-[250px] items-center justify-center text-sm text-muted-foreground">
              {lang === "bn" ? "কোনো বকেয়া নেই" : "No dues"}
            </div>
          )}
        </div>
      </div>

      {/* Notifications / Alerts */}
      {d.lowStock.length > 0 && (
        <div className="mt-6 rounded-xl border border-destructive/30 bg-destructive/5 p-4">
          <div className="flex items-center gap-2 mb-3">
            <Bell className="h-4 w-4 text-destructive" />
            <h2 className="text-sm font-bold text-destructive">
              {lang === "bn" ? "⚠️ কম স্টক সতর্কতা" : "⚠️ Low Stock Alert"}
            </h2>
          </div>
          <div className="flex flex-wrap gap-2">
            {d.lowStock.slice(0, 10).map((p) => (
              <span
                key={p.id}
                className="rounded-full bg-destructive/10 px-3 py-1 text-xs font-medium text-destructive"
              >
                {lang === "bn" && p.name_bn ? p.name_bn : p.name} ({p.stock_quantity})
              </span>
            ))}
            {d.lowStock.length > 10 && (
              <span className="text-xs text-muted-foreground">
                +{d.lowStock.length - 10} {lang === "bn" ? "আরো" : "more"}
              </span>
            )}
          </div>
        </div>
      )}

      {/* Bottom Section: Due Lists + Recent Returns + Recent Purchases */}
      <div className="mt-6 grid grid-cols-1 gap-4 lg:grid-cols-3">
        {/* Due Customers */}
        <div className="rounded-xl border border-border bg-card">
          <div className="border-b border-border px-5 py-3 flex items-center justify-between">
            <h2 className="text-sm font-bold text-foreground">
              {lang === "bn" ? "বকেয়া কাস্টমার" : "Due Customers"}
            </h2>
            <Link to="/customers" className="text-xs text-primary hover:underline">
              {lang === "bn" ? "সব দেখুন" : "View All"}
            </Link>
          </div>
          <div className="divide-y divide-border">
            {d.dueCustomers.length === 0 && (
              <p className="px-5 py-4 text-xs text-muted-foreground">
                {lang === "bn" ? "কোনো বকেয়া নেই" : "No dues"}
              </p>
            )}
            {d.dueCustomers.map((c) => (
              <div key={c.id} className="flex items-center justify-between px-5 py-2.5">
                <span className="text-sm text-foreground">{c.name}</span>
                <span className="text-sm font-semibold text-destructive">{fmt(Number(c.total_due))}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Due Suppliers */}
        <div className="rounded-xl border border-border bg-card">
          <div className="border-b border-border px-5 py-3 flex items-center justify-between">
            <h2 className="text-sm font-bold text-foreground">
              {lang === "bn" ? "বকেয়া সরবরাহকারী" : "Due Suppliers"}
            </h2>
            <Link to="/suppliers" className="text-xs text-primary hover:underline">
              {lang === "bn" ? "সব দেখুন" : "View All"}
            </Link>
          </div>
          <div className="divide-y divide-border">
            {d.dueSuppliers.length === 0 && (
              <p className="px-5 py-4 text-xs text-muted-foreground">
                {lang === "bn" ? "কোনো বকেয়া নেই" : "No dues"}
              </p>
            )}
            {d.dueSuppliers.map((s) => (
              <div key={s.id} className="flex items-center justify-between px-5 py-2.5">
                <span className="text-sm text-foreground">{s.name}</span>
                <span className="text-sm font-semibold text-destructive">{fmt(Number(s.current_due))}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Recent Returns */}
        <div className="rounded-xl border border-border bg-card">
          <div className="border-b border-border px-5 py-3 flex items-center justify-between">
            <h2 className="text-sm font-bold text-foreground">
              {lang === "bn" ? "সাম্প্রতিক রিটার্ন" : "Recent Returns"}
            </h2>
            <Link to="/returns" className="text-xs text-primary hover:underline">
              {lang === "bn" ? "সব দেখুন" : "View All"}
            </Link>
          </div>
          <div className="divide-y divide-border">
            {d.recentReturns.length === 0 && (
              <p className="px-5 py-4 text-xs text-muted-foreground">
                {lang === "bn" ? "কোনো রিটার্ন নেই" : "No returns"}
              </p>
            )}
            {d.recentReturns.map((r) => (
              <div key={r.id} className="flex items-center justify-between px-5 py-2.5">
                <div>
                  <span className="text-xs font-medium text-foreground capitalize">{r.return_type}</span>
                  <span className="ml-2 text-xs text-muted-foreground">
                    {new Date(r.created_at).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-US")}
                  </span>
                </div>
                <span className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${
                  r.status === "completed" ? "bg-green-500/10 text-green-600" : "bg-yellow-500/10 text-yellow-600"
                }`}>
                  {r.status}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Recent Purchases */}
      <div className="mt-6 rounded-xl border border-border bg-card">
        <div className="border-b border-border px-5 py-3 flex items-center justify-between">
          <h2 className="text-sm font-bold text-foreground">
            {lang === "bn" ? "সাম্প্রতিক ক্রয়" : "Recent Purchases"}
          </h2>
          <Link to="/purchases" className="text-xs text-primary hover:underline">
            {lang === "bn" ? "সব দেখুন" : "View All"}
          </Link>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border text-left text-xs text-muted-foreground">
                <th className="px-5 py-3 font-medium">{lang === "bn" ? "ইনভয়েস" : "Invoice"}</th>
                <th className="px-5 py-3 font-medium">{lang === "bn" ? "তারিখ" : "Date"}</th>
                <th className="px-5 py-3 font-medium">{lang === "bn" ? "মোট" : "Total"}</th>
                <th className="px-5 py-3 font-medium">{lang === "bn" ? "বকেয়া" : "Due"}</th>
              </tr>
            </thead>
            <tbody>
              {d.recentPurchases.length === 0 && (
                <tr>
                  <td colSpan={4} className="px-5 py-4 text-xs text-muted-foreground text-center">
                    {lang === "bn" ? "কোনো তথ্য নেই" : "No data"}
                  </td>
                </tr>
              )}
              {d.recentPurchases.map((p) => (
                <tr key={p.id} className="border-b border-border last:border-0">
                  <td className="px-5 py-2.5 font-mono text-xs">{p.invoice_no || "-"}</td>
                  <td className="px-5 py-2.5 text-xs text-muted-foreground">
                    {new Date(p.purchase_date).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-US")}
                  </td>
                  <td className="px-5 py-2.5 font-semibold">{fmt(Number(p.total_amount))}</td>
                  <td className="px-5 py-2.5">
                    <span className={Number(p.due_amount) > 0 ? "text-destructive font-semibold" : "text-muted-foreground"}>
                      {fmt(Number(p.due_amount))}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </PageLayout>
  );
}
