import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useLanguage } from "@/hooks/use-language";
import { AlertTriangle, Wallet, DatabaseBackup, Users, Bell, ShoppingBag, Undo2 } from "lucide-react";

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

type Notif = { id: string; type: "low_stock" | "due" | "wallet" | "backup" | "new_order" | "returned_order"; title: string; subtitle: string; href: string; time?: string };

function NotificationsPage() {
  const { lang } = useLanguage();
  const [items, setItems] = useState<Notif[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      const list: Notif[] = [];
      const sinceIso = new Date(Date.now() - 24 * 3600 * 1000).toISOString();

      const [
        { data: lowStock },
        { data: dueCustomers },
        { data: walletPending },
        { data: lastBackup },
        { data: newOrders },
        { data: returnedOrders },
      ] = await Promise.all([
        supabase.from("products").select("id, name, name_bn, stock_quantity").eq("is_deleted", false).lte("stock_quantity", 10).order("stock_quantity").limit(20),
        supabase.from("customers").select("id, name, total_due").is("deleted_at", null).gt("total_due", 0).order("total_due", { ascending: false }).limit(20),
        supabase.from("referral_wallets").select("id, customer_id, balance").gt("balance", 0).order("balance", { ascending: false }).limit(20),
        supabase.from("backups").select("created_at, status, file_name").order("created_at", { ascending: false }).limit(1),
        supabase.from("sales_orders" as any).select("id, order_no, total_amount, customers(name)")
          .in("status", ["pending", "confirmed", "processing", "ready_for_delivery"])
          .gte("created_at", sinceIso)
          .order("created_at", { ascending: false }).limit(20),
        supabase.from("sales_orders" as any).select("id, order_no, total_amount, customers(name)")
          .eq("status", "returned")
          .gte("created_at", sinceIso)
          .order("created_at", { ascending: false }).limit(20),
      ]);

      (lowStock || []).forEach((p: any) => list.push({
        id: `ls-${p.id}`, type: "low_stock",
        title: lang === "bn" ? `কম স্টক: ${p.name_bn || p.name}` : `Low stock: ${p.name}`,
        subtitle: lang === "bn" ? `অবশিষ্ট: ${p.stock_quantity}` : `Remaining: ${p.stock_quantity}`,
        href: "/products",
      }));
      (newOrders || []).forEach((o: any) => list.push({
        id: `no-${o.id}`, type: "new_order",
        title: lang === "bn" ? `নতুন অর্ডার: ${o.order_no}` : `New order: ${o.order_no}`,
        subtitle: `${o.customers?.name || "Walk-in"} · ৳${Number(o.total_amount).toLocaleString()}`,
        href: `/sales-orders/${o.id}`,
      }));
      (returnedOrders || []).forEach((o: any) => list.push({
        id: `rt-${o.id}`, type: "returned_order",
        title: lang === "bn" ? `রিটার্ন: ${o.order_no}` : `Return: ${o.order_no}`,
        subtitle: `${o.customers?.name || "—"} · ৳${Number(o.total_amount).toLocaleString()}`,
        href: `/sales-orders/${o.id}`,
      }));
      (dueCustomers || []).forEach((c: any) => list.push({
        id: `du-${c.id}`, type: "due",
        title: lang === "bn" ? `বাকি: ${c.name}` : `Due: ${c.name}`,
        subtitle: `৳ ${Number(c.total_due).toLocaleString()}`,
        href: "/customers",
      }));
      (walletPending || []).forEach((w: any) => list.push({
        id: `wp-${w.id}`, type: "wallet",
        title: lang === "bn" ? "ওয়ালেট ব্যালেন্স" : "Wallet balance",
        subtitle: `৳ ${Number(w.balance).toLocaleString()}`,
        href: "/wallet-management",
      }));
      const lb = lastBackup?.[0];
      if (!lb) {
        list.push({ id: "bk-none", type: "backup", title: lang === "bn" ? "কোনো ব্যাকআপ নেই" : "No backup yet", subtitle: lang === "bn" ? "ব্যাকআপ নিন" : "Create one now", href: "/backups" });
      } else {
        const ageDays = Math.floor((Date.now() - new Date(lb.created_at).getTime()) / 86400000);
        if (ageDays >= 7) list.push({ id: "bk-old", type: "backup", title: lang === "bn" ? `পুরাতন ব্যাকআপ (${ageDays} দিন)` : `Old backup (${ageDays} days)`, subtitle: lb.file_name, href: "/backups" });
      }

      setItems(list);
      setLoading(false);
    })();
  }, [lang]);

  const iconFor = (t: Notif["type"]) => {
    if (t === "low_stock") return <AlertTriangle className="h-4 w-4 text-orange-600" />;
    if (t === "due") return <Users className="h-4 w-4 text-red-600" />;
    if (t === "wallet") return <Wallet className="h-4 w-4 text-indigo-600" />;
    if (t === "new_order") return <ShoppingBag className="h-4 w-4 text-green-600" />;
    if (t === "returned_order") return <Undo2 className="h-4 w-4 text-orange-600" />;
    return <DatabaseBackup className="h-4 w-4 text-blue-600" />;
  };

  return (
    <PageLayout>
      <div className="mb-6 flex items-center gap-3">
        <Bell className="h-5 w-5 text-primary" />
        <div>
          <h1 className="text-xl font-bold text-foreground">{lang === "bn" ? "নোটিফিকেশন" : "Notifications"}</h1>
          <p className="text-sm text-muted-foreground">{items.length} {lang === "bn" ? "টি অ্যালার্ট" : "alerts"}</p>
        </div>
      </div>

      {loading ? (
        <div className="flex h-40 items-center justify-center text-muted-foreground">{lang === "bn" ? "লোড হচ্ছে..." : "Loading..."}</div>
      ) : items.length === 0 ? (
        <div className="rounded-xl border border-border bg-card p-10 text-center text-muted-foreground">
          ✨ {lang === "bn" ? "সবকিছু ঠিক আছে!" : "All clear!"}
        </div>
      ) : (
        <div className="space-y-2">
          {items.map((n) => (
            <Link key={n.id} to={n.href} className="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-muted">{iconFor(n.type)}</div>
              <div className="flex-1">
                <p className="text-sm font-medium text-foreground">{n.title}</p>
                <p className="text-xs text-muted-foreground">{n.subtitle}</p>
              </div>
              <span className="text-xs text-muted-foreground">→</span>
            </Link>
          ))}
        </div>
      )}
    </PageLayout>
  );
}
