import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import {
  ShoppingCart, Receipt, Package, Users, Truck, Wallet, Building2,
  Warehouse, ArrowLeftRight, BarChart3, ShieldCheck, DatabaseBackup,
  Bell, CreditCard, TrendingUp, TrendingDown, AlertTriangle, Banknote, FolderTree,
} from "lucide-react";

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

type Kpi = {
  todaySales: number;
  todayPurchase: number;
  stockValue: number;
  customerDue: number;
  supplierDue: number;
  todayExpense: number;
  todayIncome: number;
  walletBalance: number;
  branchCount: number;
  lowStockCount: number;
};

const fmt = (n: number) => `৳ ${Math.round(n).toLocaleString()}`;

function ManagementHub() {
  const { tr, lang } = useLanguage();
  const [k, setK] = useState<Kpi | null>(null);

  useEffect(() => {
    (async () => {
      const today = new Date(); today.setHours(0, 0, 0, 0);
      const iso = today.toISOString();
      const dateStr = today.toISOString().slice(0, 10);

      const [sales, purchases, products, customers, suppliers, expenses, incomes, wallets, branches] = await Promise.all([
        supabase.from("customer_transactions").select("amount").eq("type", "sale").gte("created_at", iso),
        supabase.from("purchases").select("total_amount").gte("created_at", iso),
        supabase.from("products").select("stock_quantity, purchase_price").eq("is_deleted", false),
        supabase.from("customers").select("total_due").is("deleted_at", null),
        supabase.from("suppliers").select("current_due").eq("is_deleted", false),
        supabase.from("expenses").select("amount").eq("expense_date", dateStr),
        supabase.from("incomes").select("amount").eq("income_date", dateStr),
        supabase.from("referral_wallets").select("balance"),
        supabase.from("branches").select("id", { count: "exact", head: true }).is("deleted_at", null),
      ]);

      const products_data = products.data || [];
      const stockValue = products_data.reduce((s, p: any) => s + (Number(p.stock_quantity) || 0) * (Number(p.purchase_price) || 0), 0);
      const lowStockCount = products_data.filter((p: any) => Number(p.stock_quantity) <= 10).length;

      setK({
        todaySales: (sales.data || []).reduce((s, r: any) => s + Number(r.amount || 0), 0),
        todayPurchase: (purchases.data || []).reduce((s, r: any) => s + Number(r.total_amount || 0), 0),
        stockValue,
        customerDue: (customers.data || []).reduce((s, r: any) => s + Number(r.total_due || 0), 0),
        supplierDue: (suppliers.data || []).reduce((s, r: any) => s + Number(r.current_due || 0), 0),
        todayExpense: (expenses.data || []).reduce((s, r: any) => s + Number(r.amount || 0), 0),
        todayIncome: (incomes.data || []).reduce((s, r: any) => s + Number(r.amount || 0), 0),
        walletBalance: (wallets.data || []).reduce((s, r: any) => s + Number(r.balance || 0), 0),
        branchCount: branches.count || 0,
        lowStockCount,
      });
    })();
  }, []);

  const kpis = [
    { label: lang === "bn" ? "আজকের বিক্রয়" : "Today Sales", value: k ? fmt(k.todaySales) : "...", icon: Receipt, color: "text-green-600 bg-green-100 dark:bg-green-900/30" },
    { label: lang === "bn" ? "আজকের ক্রয়" : "Today Purchase", value: k ? fmt(k.todayPurchase) : "...", icon: ShoppingCart, color: "text-blue-600 bg-blue-100 dark:bg-blue-900/30" },
    { label: lang === "bn" ? "স্টক মূল্য" : "Stock Value", value: k ? fmt(k.stockValue) : "...", icon: Package, color: "text-purple-600 bg-purple-100 dark:bg-purple-900/30" },
    { label: lang === "bn" ? "কাস্টমার বাকি" : "Customer Due", value: k ? fmt(k.customerDue) : "...", icon: Users, color: "text-orange-600 bg-orange-100 dark:bg-orange-900/30" },
    { label: lang === "bn" ? "সাপ্লায়ার বাকি" : "Supplier Due", value: k ? fmt(k.supplierDue) : "...", icon: Truck, color: "text-red-600 bg-red-100 dark:bg-red-900/30" },
    { label: lang === "bn" ? "আজকের আয়" : "Today Income", value: k ? fmt(k.todayIncome) : "...", icon: TrendingUp, color: "text-emerald-600 bg-emerald-100 dark:bg-emerald-900/30" },
    { label: lang === "bn" ? "আজকের খরচ" : "Today Expense", value: k ? fmt(k.todayExpense) : "...", icon: TrendingDown, color: "text-rose-600 bg-rose-100 dark:bg-rose-900/30" },
    { label: lang === "bn" ? "ওয়ালেট ব্যালেন্স" : "Wallet Balance", value: k ? fmt(k.walletBalance) : "...", icon: Wallet, color: "text-indigo-600 bg-indigo-100 dark:bg-indigo-900/30" },
  ];

  const groups: { title: string; items: { to: string; label: string; icon: any }[] }[] = [
    {
      title: lang === "bn" ? "সংস্থা ও শাখা" : "Organization",
      items: [
        { to: "/branches", label: lang === "bn" ? "শাখা" : "Branches", icon: Building2 },
        { to: "/godowns", label: lang === "bn" ? "গুদাম" : "Godowns", icon: Warehouse },
        { to: "/transfers", label: lang === "bn" ? "ট্রান্সফার" : "Transfers", icon: ArrowLeftRight },
        { to: "/admin", label: lang === "bn" ? "ইউজার ও পারমিশন" : "Users & Permissions", icon: ShieldCheck },
      ],
    },
    {
      title: lang === "bn" ? "পণ্য ও স্টক" : "Products & Stock",
      items: [
        { to: "/products", label: lang === "bn" ? "পণ্য" : "Products", icon: Package },
        { to: "/brands", label: lang === "bn" ? "ব্র্যান্ড" : "Brands", icon: Package },
        { to: "/categories", label: lang === "bn" ? "ক্যাটাগরি" : "Categories", icon: Package },
        { to: "/godowns/transfer", label: lang === "bn" ? "স্টক ট্রান্সফার" : "Stock Transfer", icon: ArrowLeftRight },
      ],
    },
    {
      title: lang === "bn" ? "বিক্রয় ও কাস্টমার" : "Sales & Customers",
      items: [
        { to: "/sales", label: lang === "bn" ? "বিক্রয়" : "Sales", icon: Receipt },
        { to: "/customers", label: lang === "bn" ? "কাস্টমার" : "Customers", icon: Users },
        { to: "/returns", label: lang === "bn" ? "রিটার্ন" : "Returns", icon: ArrowLeftRight },
        { to: "/wallet-management", label: lang === "bn" ? "ওয়ালেট" : "Wallet", icon: Wallet },
        { to: "/wallet-report", label: lang === "bn" ? "ওয়ালেট রিপোর্ট" : "Wallet Report", icon: BarChart3 },
      ],
    },
    {
      title: lang === "bn" ? "ক্রয় ও সাপ্লায়ার" : "Purchase & Suppliers",
      items: [
        { to: "/purchases", label: lang === "bn" ? "ক্রয়" : "Purchases", icon: ShoppingCart },
        { to: "/suppliers", label: lang === "bn" ? "সাপ্লায়ার" : "Suppliers", icon: Truck },
      ],
    },
    {
      title: lang === "bn" ? "অ্যাকাউন্টস" : "Accounts",
      items: [
        { to: "/expenses", label: lang === "bn" ? "খরচ" : "Expenses", icon: TrendingDown },
        { to: "/incomes", label: lang === "bn" ? "আয়" : "Incomes", icon: TrendingUp },
        { to: "/transaction-categories", label: lang === "bn" ? "আয়/ব্যয় ক্যাটাগরি" : "Income/Expense Categories", icon: FolderTree },
        { to: "/commission-settings", label: lang === "bn" ? "কমিশন" : "Commission", icon: Banknote },
      ],
    },
    {
      title: lang === "bn" ? "রিপোর্ট ও সিস্টেম" : "Reports & System",
      items: [
        { to: "/reports", label: lang === "bn" ? "রিপোর্ট" : "Reports", icon: BarChart3 },
        { to: "/branch-reports", label: lang === "bn" ? "শাখা রিপোর্ট" : "Branch Reports", icon: BarChart3 },
        { to: "/notifications", label: lang === "bn" ? "নোটিফিকেশন" : "Notifications", icon: Bell },
        { to: "/backups", label: lang === "bn" ? "ব্যাকআপ" : "Backups", icon: DatabaseBackup },
      ],
    },
  ];

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{lang === "bn" ? "ম্যানেজমেন্ট ড্যাশবোর্ড" : "Management Dashboard"}</h1>
        <p className="text-sm text-muted-foreground">{lang === "bn" ? "সকল মডিউলের কেন্দ্রীয় নিয়ন্ত্রণ" : "Central control for all modules"}</p>
      </div>

      <div className="mb-6 grid gap-3 grid-cols-2 md:grid-cols-4">
        {kpis.map((kpi) => (
          <div key={kpi.label} className="rounded-xl border border-border bg-card p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted-foreground">{kpi.label}</p>
                <p className="mt-1 text-lg font-bold text-foreground">{kpi.value}</p>
              </div>
              <div className={`flex h-10 w-10 items-center justify-center rounded-lg ${kpi.color}`}>
                <kpi.icon className="h-5 w-5" />
              </div>
            </div>
          </div>
        ))}
      </div>

      {k && k.lowStockCount > 0 && (
        <Link to="/notifications" className="mb-6 flex items-center gap-3 rounded-xl border border-orange-200 bg-orange-50 p-4 dark:border-orange-900 dark:bg-orange-900/20">
          <AlertTriangle className="h-5 w-5 text-orange-600" />
          <div className="flex-1">
            <p className="text-sm font-medium text-orange-900 dark:text-orange-200">
              {lang === "bn" ? `${k.lowStockCount} টি পণ্যের স্টক কম` : `${k.lowStockCount} products have low stock`}
            </p>
          </div>
          <span className="text-xs text-orange-700 dark:text-orange-300">{lang === "bn" ? "দেখুন →" : "View →"}</span>
        </Link>
      )}

      <div className="space-y-6">
        {groups.map((g) => (
          <div key={g.title}>
            <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground">{g.title}</h2>
            <div className="grid gap-3 grid-cols-2 md:grid-cols-4">
              {g.items.map((it) => (
                <Link key={it.to} to={it.to} className="group flex items-center gap-3 rounded-xl border border-border bg-card p-4 transition hover:border-primary hover:shadow-sm">
                  <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary group-hover:bg-primary group-hover:text-primary-foreground">
                    <it.icon className="h-4 w-4" />
                  </div>
                  <span className="text-sm font-medium text-foreground">{it.label}</span>
                </Link>
              ))}
            </div>
          </div>
        ))}
      </div>
    </PageLayout>
  );
}
