import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useState, useEffect, useMemo } from "react";
import { Search, Plus, Edit, Trash2, Package, AlertTriangle, ImageIcon } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/products/")({
  head: () => ({
    meta: [
      { title: "Products — Niyamah Electric & Hardware" },
      { name: "description", content: "Product management" },
    ],
  }),
  component: ProductsPage,
});

type ProductRow = {
  id: string;
  name: string;
  name_bn: string;
  sku: string;
  barcode: string | null;
  category_id: string | null;
  subcategory_id: string | null;
  purchase_price: number;
  retail_price: number;
  wholesale_price: number;
  stock_quantity: number;
  unit: string;
  image_url: string | null;
  is_deleted: boolean;
  product_type: string;
  categories?: { name: string; name_bn: string } | null;
  subcategories?: { name: string; name_bn: string } | null;
};

type CategoryRow = { id: string; name: string; name_bn: string };

function ProductsPage() {
  const { tr, lang } = useLanguage();
  const [search, setSearch] = useState("");
  const [catFilter, setCatFilter] = useState("all");
  const [typeFilter, setTypeFilter] = useState("all");
  const [products, setProducts] = useState<ProductRow[]>([]);
  const [categories, setCategories] = useState<CategoryRow[]>([]);
  const [loading, setLoading] = useState(true);
  const LOW_STOCK_THRESHOLD = 10;

  const fetchData = async () => {
    setLoading(true);
    const [{ data: prods }, { data: cats }] = await Promise.all([
      supabase
        .from("products")
        .select("*, categories(name, name_bn), subcategories(name, name_bn)")
        .eq("is_deleted", false)
        .order("created_at", { ascending: false }),
      supabase.from("categories").select("*").order("name_bn"),
    ]);
    setProducts((prods as ProductRow[]) || []);
    setCategories((cats as CategoryRow[]) || []);
    setLoading(false);
  };

  useEffect(() => { fetchData(); }, []);

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`"${name}" মুছে ফেলতে চান?`)) return;
    const { error } = await supabase.from("products").update({ is_deleted: true }).eq("id", id);
    if (error) { toast.error("ডিলিট করা যায়নি"); return; }
    toast.success("প্রোডাক্ট মুছে ফেলা হয়েছে");
    setProducts((prev) => prev.filter((p) => p.id !== id));
  };

  const filtered = useMemo(() => {
    return products.filter((p) => {
      const s = search.toLowerCase();
      const matchSearch =
        !search ||
        p.name.toLowerCase().includes(s) ||
        p.name_bn.includes(search) ||
        p.sku.toLowerCase().includes(s) ||
        (p.barcode || "").includes(search);
      const matchCat = catFilter === "all" || p.category_id === catFilter;
      const matchType = typeFilter === "all" || p.product_type === typeFilter;
      return matchSearch && matchCat && matchType;
    });
  }, [products, search, catFilter, typeFilter]);

  const lowStockCount = products.filter((p) => p.stock_quantity < LOW_STOCK_THRESHOLD).length;

  return (
    <PageLayout>
      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-xl font-bold text-foreground">{tr("productsTitle")}</h1>
          <p className="text-sm text-muted-foreground">
            {tr("productsSubtitle")} — {products.length} টি পণ্য
            {lowStockCount > 0 && (
              <span className="ml-2 inline-flex items-center gap-1 text-destructive">
                <AlertTriangle className="h-3.5 w-3.5" />
                {lowStockCount} টি কম স্টক
              </span>
            )}
          </p>
        </div>
        <Link
          to="/products/add"
          className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground transition hover:bg-primary/90"
        >
          <Plus className="h-4 w-4" />
          {tr("addProduct")}
        </Link>
      </div>

      <div className="mb-4 flex flex-wrap items-center gap-3">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <input
            type="text"
            placeholder="পণ্য খুঁজুন — নাম, SKU, বারকোড..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-input bg-card py-2 pl-10 pr-4 text-sm outline-none focus:ring-2 focus:ring-ring"
          />
        </div>
        <select
          value={catFilter}
          onChange={(e) => setCatFilter(e.target.value)}
          className="rounded-lg border border-input bg-card px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
        >
          <option value="all">সব ক্যাটাগরি</option>
          {categories.map((c) => (
            <option key={c.id} value={c.id}>
              {lang === "bn" ? c.name_bn : c.name}
            </option>
          ))}
        </select>
        <select
          value={typeFilter}
          onChange={(e) => setTypeFilter(e.target.value)}
          className="rounded-lg border border-input bg-card px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
        >
          <option value="all">সব ধরন</option>
          <option value="electric">⚡ Electric</option>
          <option value="hardware">🔩 Hardware</option>
        </select>
      </div>

      {loading ? (
        <div className="flex h-40 items-center justify-center text-muted-foreground">লোড হচ্ছে...</div>
      ) : (
        <div className="rounded-xl border border-border bg-card 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-4 py-3 font-medium">ছবি</th>
                <th className="px-4 py-3 font-medium">ধরন</th>
                <th className="px-4 py-3 font-medium">{tr("productName")}</th>
                <th className="px-4 py-3 font-medium">{tr("category")}</th>
                <th className="px-4 py-3 font-medium">SKU</th>
                <th className="px-4 py-3 font-medium">{tr("barcode")}</th>
                <th className="px-4 py-3 font-medium">ক্রয় মূল্য</th>
                <th className="px-4 py-3 font-medium">খুচরা মূল্য</th>
                <th className="px-4 py-3 font-medium">পাইকারি মূল্য</th>
                <th className="px-4 py-3 font-medium">{tr("stock")}</th>
                <th className="px-4 py-3 font-medium">{tr("unit")}</th>
                <th className="px-4 py-3 font-medium">{tr("action")}</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((p) => (
                <tr key={p.id} className="border-b border-border last:border-0 hover:bg-muted/30">
                  <td className="px-4 py-2">
                    {p.image_url ? (
                      <img src={p.image_url} alt={p.name} className="h-10 w-10 rounded-md object-cover" />
                    ) : (
                      <div className="flex h-10 w-10 items-center justify-center rounded-md bg-muted">
                        <ImageIcon className="h-4 w-4 text-muted-foreground" />
                      </div>
                    )}
                  </td>
                  <td className="px-4 py-2">
                    <span className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${p.product_type === "electric" ? "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400" : "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"}`}>
                      {p.product_type === "electric" ? "⚡ Electric" : "🔩 Hardware"}
                    </span>
                  </td>
                  <td className="px-4 py-2">
                    <p className="font-medium text-foreground">{lang === "bn" ? p.name_bn || p.name : p.name}</p>
                    <p className="text-xs text-muted-foreground">{lang === "bn" ? p.name : p.name_bn}</p>
                  </td>
                  <td className="px-4 py-2">
                    <span className="rounded-full bg-secondary px-2 py-0.5 text-xs text-secondary-foreground">
                      {lang === "bn" ? p.categories?.name_bn : p.categories?.name}
                    </span>
                    {p.subcategories && (
                      <p className="mt-0.5 text-xs text-muted-foreground">
                        {lang === "bn" ? p.subcategories.name_bn : p.subcategories.name}
                      </p>
                    )}
                  </td>
                  <td className="px-4 py-2 font-mono text-xs text-muted-foreground">{p.sku}</td>
                  <td className="px-4 py-2 font-mono text-xs text-muted-foreground">{p.barcode || "—"}</td>
                  <td className="px-4 py-2 text-foreground">৳{Number(p.purchase_price).toLocaleString()}</td>
                  <td className="px-4 py-2 font-semibold text-foreground">৳{Number(p.retail_price).toLocaleString()}</td>
                  <td className="px-4 py-2 text-foreground">৳{Number(p.wholesale_price).toLocaleString()}</td>
                  <td className="px-4 py-2">
                    <span className={`text-sm font-medium ${p.stock_quantity < LOW_STOCK_THRESHOLD ? "text-destructive" : "text-green-600"}`}>
                      {Number(p.stock_quantity)}
                    </span>
                    {p.stock_quantity < LOW_STOCK_THRESHOLD && (
                      <AlertTriangle className="ml-1 inline h-3.5 w-3.5 text-destructive" />
                    )}
                  </td>
                  <td className="px-4 py-2 text-muted-foreground">{p.unit}</td>
                  <td className="px-4 py-2">
                    <div className="flex gap-1">
                      <Link
                        to="/products/$productId/edit"
                        params={{ productId: p.id }}
                        className="rounded p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground"
                      >
                        <Edit className="h-3.5 w-3.5" />
                      </Link>
                      <button
                        onClick={() => handleDelete(p.id, p.name)}
                        className="rounded p-1.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length === 0 && (
            <div className="flex h-32 items-center justify-center text-muted-foreground">
              <Package className="mr-2 h-4 w-4" />
              {tr("noProductFound")}
            </div>
          )}
        </div>
      )}
    </PageLayout>
  );
}
