import { createFileRoute } 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, FolderTree, ChevronDown, ChevronRight, X } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/categories")({
  head: () => ({
    meta: [
      { title: "Categories — Niyamah Electric & Hardware" },
      { name: "description", content: "Category & Sub-Category management" },
    ],
  }),
  component: CategoriesPage,
});

type CategoryRow = {
  id: string;
  name: string;
  name_bn: string;
  code: string;
  status: string;
  deleted_at: string | null;
  created_at: string;
  product_count: number;
  subcategories: SubCategoryRow[];
};

type SubCategoryRow = {
  id: string;
  category_id: string;
  name: string;
  name_bn: string;
  status: string;
  deleted_at: string | null;
  created_at: string;
  product_count: number;
};

type ModalMode = "add-cat" | "edit-cat" | "add-sub" | "edit-sub" | null;

function CategoriesPage() {
  const { tr, lang } = useLanguage();
  const [categories, setCategories] = useState<CategoryRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [expanded, setExpanded] = useState<string[]>([]);
  const [modalMode, setModalMode] = useState<ModalMode>(null);
  const [editItem, setEditItem] = useState<any>(null);
  const [form, setForm] = useState({ name: "", name_bn: "", code: "", status: "active", category_id: "" });
  const [saving, setSaving] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    const [{ data: cats }, { data: subs }, { data: products }] = await Promise.all([
      supabase.from("categories").select("*").is("deleted_at", null).order("created_at", { ascending: false }),
      supabase.from("subcategories").select("*").is("deleted_at", null).order("name"),
      supabase.from("products").select("category_id, subcategory_id").eq("is_deleted", false),
    ]);

    const catCount: Record<string, number> = {};
    const subCount: Record<string, number> = {};
    (products || []).forEach((p: any) => {
      if (p.category_id) catCount[p.category_id] = (catCount[p.category_id] || 0) + 1;
      if (p.subcategory_id) subCount[p.subcategory_id] = (subCount[p.subcategory_id] || 0) + 1;
    });

    const subMap: Record<string, SubCategoryRow[]> = {};
    (subs || []).forEach((s: any) => {
      const sub: SubCategoryRow = { ...s, product_count: subCount[s.id] || 0 };
      if (!subMap[s.category_id]) subMap[s.category_id] = [];
      subMap[s.category_id].push(sub);
    });

    setCategories(
      (cats || []).map((c: any) => ({
        ...c,
        code: c.code || "",
        status: c.status || "active",
        product_count: catCount[c.id] || 0,
        subcategories: subMap[c.id] || [],
      }))
    );
    setLoading(false);
  };

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

  const filtered = useMemo(() => {
    return categories.filter((c) => {
      const s = search.toLowerCase();
      const matchSearch = !search || c.name.toLowerCase().includes(s) || c.name_bn.includes(search) || (c.code || "").toLowerCase().includes(s);
      const matchStatus = statusFilter === "all" || c.status === statusFilter;
      return matchSearch && matchStatus;
    });
  }, [categories, search, statusFilter]);

  const toggleExpand = (id: string) => setExpanded((p) => p.includes(id) ? p.filter((x) => x !== id) : [...p, id]);

  // Category CRUD
  const openAddCat = () => {
    setEditItem(null);
    setForm({ name: "", name_bn: "", code: "", status: "active", category_id: "" });
    setModalMode("add-cat");
  };
  const openEditCat = (c: CategoryRow) => {
    setEditItem(c);
    setForm({ name: c.name, name_bn: c.name_bn, code: c.code, status: c.status, category_id: "" });
    setModalMode("edit-cat");
  };
  const handleDeleteCat = async (c: CategoryRow) => {
    if (c.product_count > 0 || c.subcategories.length > 0) {
      toast.error(lang === "bn" ? "এই ক্যাটাগরিতে পণ্য/সাব-ক্যাটাগরি আছে, আগে সরান" : "Category has products/subcategories, remove them first");
      return;
    }
    if (!confirm(`"${c.name}" মুছে ফেলতে চান?`)) return;
    const { error } = await supabase.from("categories").update({ deleted_at: new Date().toISOString() }).eq("id", c.id);
    if (error) { toast.error("ডিলিট করা যায়নি"); return; }
    toast.success("ক্যাটাগরি মুছে ফেলা হয়েছে");
    setCategories((p) => p.filter((x) => x.id !== c.id));
  };

  // Sub-Category CRUD
  const openAddSub = (catId: string) => {
    setEditItem(null);
    setForm({ name: "", name_bn: "", code: "", status: "active", category_id: catId });
    setModalMode("add-sub");
  };
  const openEditSub = (s: SubCategoryRow) => {
    setEditItem(s);
    setForm({ name: s.name, name_bn: s.name_bn, code: "", status: s.status, category_id: s.category_id });
    setModalMode("edit-sub");
  };
  const handleDeleteSub = async (s: SubCategoryRow) => {
    if (s.product_count > 0) {
      toast.error(lang === "bn" ? "এই সাব-ক্যাটাগরিতে পণ্য আছে, আগে Product update করুন" : "Sub-category has products, update them first");
      return;
    }
    if (!confirm(`"${s.name}" মুছে ফেলতে চান?`)) return;
    const { error } = await supabase.from("subcategories").update({ deleted_at: new Date().toISOString() }).eq("id", s.id);
    if (error) { toast.error("ডিলিট করা যায়নি"); return; }
    toast.success("সাব-ক্যাটাগরি মুছে ফেলা হয়েছে");
    fetchData();
  };

  const handleSave = async () => {
    if (!form.name.trim()) { toast.error("Name is required"); return; }
    setSaving(true);

    if (modalMode === "add-cat" || modalMode === "edit-cat") {
      const dup = categories.find((c) => c.name.toLowerCase() === form.name.trim().toLowerCase() && c.id !== editItem?.id);
      if (dup) { toast.error("এই নামে ক্যাটাগরি আছে"); setSaving(false); return; }

      if (modalMode === "edit-cat") {
        const { error } = await supabase.from("categories").update({
          name: form.name.trim(), name_bn: form.name_bn.trim(), code: form.code.trim(), status: form.status,
        }).eq("id", editItem.id);
        if (error) { toast.error("আপডেট করা যায়নি"); setSaving(false); return; }
        toast.success("ক্যাটাগরি আপডেট হয়েছে");
      } else {
        const { error } = await supabase.from("categories").insert({
          name: form.name.trim(), name_bn: form.name_bn.trim(), code: form.code.trim(), status: form.status,
        });
        if (error) { toast.error("যোগ করা যায়নি"); setSaving(false); return; }
        toast.success("ক্যাটাগরি যোগ হয়েছে");
      }
    } else {
      // Sub-category
      const parentSubs = categories.find((c) => c.id === form.category_id)?.subcategories || [];
      const dup = parentSubs.find((s) => s.name.toLowerCase() === form.name.trim().toLowerCase() && s.id !== editItem?.id);
      if (dup) { toast.error("এই নামে সাব-ক্যাটাগরি আছে"); setSaving(false); return; }

      if (modalMode === "edit-sub") {
        const { error } = await supabase.from("subcategories").update({
          name: form.name.trim(), name_bn: form.name_bn.trim(), status: form.status, category_id: form.category_id,
        }).eq("id", editItem.id);
        if (error) { toast.error("আপডেট করা যায়নি"); setSaving(false); return; }
        toast.success("সাব-ক্যাটাগরি আপডেট হয়েছে");
      } else {
        const { error } = await supabase.from("subcategories").insert({
          name: form.name.trim(), name_bn: form.name_bn.trim(), status: form.status, category_id: form.category_id,
        });
        if (error) { toast.error("যোগ করা যায়নি"); setSaving(false); return; }
        toast.success("সাব-ক্যাটাগরি যোগ হয়েছে");
      }
    }

    setSaving(false);
    setModalMode(null);
    fetchData();
  };

  const isCatModal = modalMode === "add-cat" || modalMode === "edit-cat";
  const isSubModal = modalMode === "add-sub" || modalMode === "edit-sub";

  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("categories")}</h1>
          <p className="text-sm text-muted-foreground">{tr("categorySubtitle")} — {categories.length} {lang === "bn" ? "টি ক্যাটাগরি" : "categories"}</p>
        </div>
        <button onClick={openAddCat} 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("addCategory")}
        </button>
      </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={lang === "bn" ? "ক্যাটাগরি খুঁজুন..." : "Search categories..."} 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={statusFilter} onChange={(e) => setStatusFilter(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">{lang === "bn" ? "সব স্ট্যাটাস" : "All Status"}</option>
          <option value="active">{lang === "bn" ? "সক্রিয়" : "Active"}</option>
          <option value="inactive">{lang === "bn" ? "নিষ্ক্রিয়" : "Inactive"}</option>
        </select>
      </div>

      {loading ? (
        <div className="flex h-40 items-center justify-center text-muted-foreground">{lang === "bn" ? "লোড হচ্ছে..." : "Loading..."}</div>
      ) : (
        <div className="space-y-2">
          {filtered.map((c) => {
            const isExp = expanded.includes(c.id);
            return (
              <div key={c.id} className="rounded-xl border border-border bg-card overflow-hidden">
                {/* Category Row */}
                <div className="flex items-center gap-3 px-4 py-3 hover:bg-muted/30">
                  <button onClick={() => toggleExpand(c.id)} className="rounded p-1 hover:bg-muted">
                    {isExp ? <ChevronDown className="h-4 w-4 text-muted-foreground" /> : <ChevronRight className="h-4 w-4 text-muted-foreground" />}
                  </button>
                  <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
                    <FolderTree className="h-4 w-4 text-primary" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="font-medium text-foreground">{lang === "bn" ? c.name_bn || c.name : c.name}</p>
                      {c.code && <span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">{c.code}</span>}
                    </div>
                    <p className="text-xs text-muted-foreground">{lang === "bn" ? c.name : c.name_bn} · {c.subcategories.length} {lang === "bn" ? "সাব-ক্যাটাগরি" : "subcategories"}</p>
                  </div>
                  <span className="inline-flex items-center rounded-full bg-secondary px-2.5 py-0.5 text-xs font-medium text-secondary-foreground">
                    {c.product_count} {lang === "bn" ? "পণ্য" : "products"}
                  </span>
                  <span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${c.status === "active" ? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400" : "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400"}`}>
                    {c.status === "active" ? (lang === "bn" ? "সক্রিয়" : "Active") : (lang === "bn" ? "নিষ্ক্রিয়" : "Inactive")}
                  </span>
                  <span className="text-xs text-muted-foreground hidden sm:block">{new Date(c.created_at).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-US")}</span>
                  <div className="flex gap-1">
                    <button onClick={() => openEditCat(c)} className="rounded p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground"><Edit className="h-3.5 w-3.5" /></button>
                    <button onClick={() => handleDeleteCat(c)} 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>
                </div>

                {/* Sub-Categories */}
                {isExp && (
                  <div className="border-t border-border bg-muted/20">
                    <div className="px-4 py-2 flex items-center justify-between">
                      <p className="text-xs font-medium text-muted-foreground">{lang === "bn" ? "সাব-ক্যাটাগরি" : "Sub-Categories"}</p>
                      <button onClick={() => openAddSub(c.id)} className="flex items-center gap-1 rounded-md bg-primary/10 px-2.5 py-1 text-xs font-medium text-primary hover:bg-primary/20">
                        <Plus className="h-3 w-3" /> {lang === "bn" ? "যোগ করুন" : "Add"}
                      </button>
                    </div>
                    {c.subcategories.length === 0 ? (
                      <p className="px-4 pb-3 text-xs text-muted-foreground">{lang === "bn" ? "কোনো সাব-ক্যাটাগরি নেই" : "No sub-categories"}</p>
                    ) : (
                      <table className="w-full text-sm">
                        <tbody>
                          {c.subcategories.map((s) => (
                            <tr key={s.id} className="border-t border-border/50 hover:bg-muted/30">
                              <td className="px-8 py-2">
                                <p className="font-medium text-foreground text-xs">{lang === "bn" ? s.name_bn || s.name : s.name}</p>
                                <p className="text-[10px] text-muted-foreground">{lang === "bn" ? s.name : s.name_bn}</p>
                              </td>
                              <td className="px-4 py-2">
                                <span className="inline-flex items-center rounded-full bg-secondary px-2 py-0.5 text-[10px] font-medium text-secondary-foreground">{s.product_count} {lang === "bn" ? "পণ্য" : "products"}</span>
                              </td>
                              <td className="px-4 py-2">
                                <span className={`inline-flex rounded-full px-2 py-0.5 text-[10px] font-medium ${s.status === "active" ? "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400" : "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400"}`}>
                                  {s.status === "active" ? (lang === "bn" ? "সক্রিয়" : "Active") : (lang === "bn" ? "নিষ্ক্রিয়" : "Inactive")}
                                </span>
                              </td>
                              <td className="px-4 py-2">
                                <div className="flex gap-1 justify-end">
                                  <button onClick={() => openEditSub(s)} className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground"><Edit className="h-3 w-3" /></button>
                                  <button onClick={() => handleDeleteSub(s)} className="rounded p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"><Trash2 className="h-3 w-3" /></button>
                                </div>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    )}
                  </div>
                )}
              </div>
            );
          })}
          {filtered.length === 0 && (
            <div className="flex h-32 items-center justify-center rounded-xl border border-border bg-card text-muted-foreground">
              <FolderTree className="mr-2 h-4 w-4" />
              {lang === "bn" ? "কোনো ক্যাটাগরি পাওয়া যায়নি" : "No categories found"}
            </div>
          )}
        </div>
      )}

      {/* Modal */}
      {modalMode && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={() => setModalMode(null)}>
          <div className="w-full max-w-md rounded-xl bg-card p-6 shadow-lg" onClick={(e) => e.stopPropagation()}>
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-lg font-bold text-foreground">
                {isCatModal
                  ? (modalMode === "edit-cat" ? tr("editCategory") : tr("addCategory"))
                  : (modalMode === "edit-sub" ? tr("editSubCategory") : tr("addSubCategory"))}
              </h2>
              <button onClick={() => setModalMode(null)} className="rounded p-1 hover:bg-muted"><X className="h-4 w-4" /></button>
            </div>
            <div className="space-y-4">
              {isSubModal && (
                <div>
                  <label className="mb-1 block text-sm font-medium text-foreground">{lang === "bn" ? "ক্যাটাগরি" : "Category"} *</label>
                  <select value={form.category_id} onChange={(e) => setForm({ ...form, category_id: e.target.value })} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring">
                    {categories.map((c) => (
                      <option key={c.id} value={c.id}>{lang === "bn" ? c.name_bn || c.name : c.name}</option>
                    ))}
                  </select>
                </div>
              )}
              <div>
                <label className="mb-1 block text-sm font-medium text-foreground">{isCatModal ? "Category" : "Sub-Category"} Name (EN) *</label>
                <input type="text" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring" placeholder={isCatModal ? "e.g. Wiring, Tools" : "e.g. LED Bulbs"} />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-foreground">{isCatModal ? "ক্যাটাগরি" : "সাব-ক্যাটাগরি"} নাম (BN)</label>
                <input type="text" value={form.name_bn} onChange={(e) => setForm({ ...form, name_bn: e.target.value })} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring" placeholder={isCatModal ? "যেমন: ওয়্যারিং, টুলস" : "যেমন: LED বাল্ব"} />
              </div>
              {isCatModal && (
                <div>
                  <label className="mb-1 block text-sm font-medium text-foreground">{lang === "bn" ? "ক্যাটাগরি কোড" : "Category Code"}</label>
                  <input type="text" value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value })} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring" placeholder="e.g. WR, TL" />
                </div>
              )}
              <div>
                <label className="mb-1 block text-sm font-medium text-foreground">{lang === "bn" ? "স্ট্যাটাস" : "Status"}</label>
                <select value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })} className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring">
                  <option value="active">{lang === "bn" ? "সক্রিয়" : "Active"}</option>
                  <option value="inactive">{lang === "bn" ? "নিষ্ক্রিয়" : "Inactive"}</option>
                </select>
              </div>
            </div>
            <div className="mt-6 flex justify-end gap-3">
              <button onClick={() => setModalMode(null)} className="rounded-lg border border-input px-4 py-2 text-sm hover:bg-muted">{lang === "bn" ? "বাতিল" : "Cancel"}</button>
              <button onClick={handleSave} disabled={saving} className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50">
                {saving ? (lang === "bn" ? "সেভ হচ্ছে..." : "Saving...") : (lang === "bn" ? "সেভ করুন" : "Save")}
              </button>
            </div>
          </div>
        </div>
      )}
    </PageLayout>
  );
}
