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

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

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

type ModalMode = "add" | "edit" | null;

function SubCategoriesPage() {
  const { tr, lang } = useLanguage();
  const [categories, setCategories] = useState<CategoryRow[]>([]);
  const [subcategories, setSubcategories] = useState<SubCategoryRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const [modalMode, setModalMode] = useState<ModalMode>(null);
  const [editItem, setEditItem] = useState<SubCategoryRow | null>(null);
  const [form, setForm] = useState({ name: "", name_bn: "", 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("id, name, name_bn").is("deleted_at", null).order("name"),
      supabase.from("subcategories").select("*").is("deleted_at", null).order("created_at", { ascending: false }),
      supabase.from("products").select("subcategory_id").eq("is_deleted", false),
    ]);

    const catMap: Record<string, CategoryRow> = {};
    (cats || []).forEach((c: any) => { catMap[c.id] = c; });

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

    setCategories(cats || []);
    setSubcategories(
      (subs || []).map((s: any) => ({
        ...s,
        category_name: catMap[s.category_id]?.name || "",
        category_name_bn: catMap[s.category_id]?.name_bn || "",
        product_count: prodCount[s.id] || 0,
      }))
    );
    setLoading(false);
  };

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

  const filtered = useMemo(() => {
    return subcategories.filter((s) => {
      const q = search.toLowerCase();
      const matchSearch = !search || s.name.toLowerCase().includes(q) || s.name_bn.includes(search) || s.category_name.toLowerCase().includes(q);
      const matchCat = categoryFilter === "all" || s.category_id === categoryFilter;
      const matchStatus = statusFilter === "all" || s.status === statusFilter;
      return matchSearch && matchCat && matchStatus;
    });
  }, [subcategories, search, categoryFilter, statusFilter]);

  const openAdd = () => {
    setEditItem(null);
    setForm({ name: "", name_bn: "", status: "active", category_id: categories[0]?.id || "" });
    setModalMode("add");
  };

  const openEdit = (s: SubCategoryRow) => {
    setEditItem(s);
    setForm({ name: s.name, name_bn: s.name_bn, status: s.status, category_id: s.category_id });
    setModalMode("edit");
  };

  const handleDelete = async (s: SubCategoryRow) => {
    if (s.product_count > 0) {
      toast.error(lang === "bn" ? "এই সাব-ক্যাটাগরিতে পণ্য আছে, আগে Product update করুন" : "This sub-category has products, update them first");
      return;
    }
    if (!confirm(lang === "bn" ? `"${s.name_bn || s.name}" মুছে ফেলতে চান?` : `Delete "${s.name}"?`)) return;
    const { error } = await supabase.from("subcategories").update({ deleted_at: new Date().toISOString() }).eq("id", s.id);
    if (error) { toast.error(lang === "bn" ? "ডিলিট করা যায়নি" : "Delete failed"); return; }
    toast.success(lang === "bn" ? "সাব-ক্যাটাগরি মুছে ফেলা হয়েছে" : "Sub-category deleted");
    fetchData();
  };

  const handleSave = async () => {
    if (!form.name.trim()) { toast.error(lang === "bn" ? "নাম আবশ্যক" : "Name is required"); return; }
    if (!form.category_id) { toast.error(lang === "bn" ? "ক্যাটাগরি নির্বাচন করুন" : "Select a category"); return; }
    setSaving(true);

    // Duplicate check within same category
    const dup = subcategories.find(
      (s) => s.category_id === form.category_id && s.name.toLowerCase() === form.name.trim().toLowerCase() && s.id !== editItem?.id
    );
    if (dup) { toast.error(lang === "bn" ? "এই নামে সাব-ক্যাটাগরি আছে" : "Duplicate name in this category"); setSaving(false); return; }

    const payload = { name: form.name.trim(), name_bn: form.name_bn.trim(), status: form.status, category_id: form.category_id };

    if (modalMode === "edit" && editItem) {
      const { error } = await supabase.from("subcategories").update(payload).eq("id", editItem.id);
      if (error) { toast.error(lang === "bn" ? "আপডেট করা যায়নি" : "Update failed"); setSaving(false); return; }
      toast.success(lang === "bn" ? "সাব-ক্যাটাগরি আপডেট হয়েছে" : "Sub-category updated");
    } else {
      const { error } = await supabase.from("subcategories").insert(payload);
      if (error) { toast.error(lang === "bn" ? "যোগ করা যায়নি" : "Add failed"); setSaving(false); return; }
      toast.success(lang === "bn" ? "সাব-ক্যাটাগরি যোগ হয়েছে" : "Sub-category added");
    }

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

  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("subCategories")}</h1>
          <p className="text-sm text-muted-foreground">{tr("subCategorySubtitle")} — {subcategories.length} {lang === "bn" ? "টি সাব-ক্যাটাগরি" : "sub-categories"}</p>
        </div>
        <button onClick={openAdd} 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("addSubCategory")}
        </button>
      </div>

      {/* Filters */}
      <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 sub-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={categoryFilter} onChange={(e) => setCategoryFilter(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 Categories"}</option>
          {categories.map((c) => (
            <option key={c.id} value={c.id}>{lang === "bn" ? c.name_bn || c.name : c.name}</option>
          ))}
        </select>
        <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>

      {/* Table */}
      {loading ? (
        <div className="flex h-40 items-center justify-center text-muted-foreground">{lang === "bn" ? "লোড হচ্ছে..." : "Loading..."}</div>
      ) : filtered.length === 0 ? (
        <div className="flex h-32 items-center justify-center rounded-xl border border-border bg-card text-muted-foreground">
          <FolderOpen className="mr-2 h-4 w-4" />
          {lang === "bn" ? "কোনো সাব-ক্যাটাগরি পাওয়া যায়নি" : "No sub-categories found"}
        </div>
      ) : (
        <div className="overflow-hidden rounded-xl border border-border bg-card">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-muted/30">
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{lang === "bn" ? "সাব-ক্যাটাগরি" : "Sub-Category"}</th>
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{lang === "bn" ? "ক্যাটাগরি" : "Category"}</th>
                <th className="px-4 py-3 text-center font-medium text-muted-foreground">{lang === "bn" ? "পণ্য" : "Products"}</th>
                <th className="px-4 py-3 text-center font-medium text-muted-foreground">{lang === "bn" ? "স্ট্যাটাস" : "Status"}</th>
                <th className="px-4 py-3 text-center font-medium text-muted-foreground hidden sm:table-cell">{lang === "bn" ? "তারিখ" : "Date"}</th>
                <th className="px-4 py-3 text-right font-medium text-muted-foreground">{lang === "bn" ? "অ্যাকশন" : "Action"}</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((s) => (
                <tr key={s.id} className="border-b border-border/50 hover:bg-muted/20 transition-colors">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-accent/50">
                        <FolderOpen className="h-4 w-4 text-primary" />
                      </div>
                      <div>
                        <p className="font-medium text-foreground">{lang === "bn" ? s.name_bn || s.name : s.name}</p>
                        <p className="text-xs text-muted-foreground">{lang === "bn" ? s.name : s.name_bn}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className="inline-flex rounded-full bg-secondary px-2.5 py-0.5 text-xs font-medium text-secondary-foreground">
                      {lang === "bn" ? s.category_name_bn || s.category_name : s.category_name}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <span className="inline-flex rounded-full bg-secondary px-2 py-0.5 text-xs font-medium text-secondary-foreground">
                      {s.product_count}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs 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-3 text-center text-xs text-muted-foreground hidden sm:table-cell">
                    {new Date(s.created_at).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-US")}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-1 justify-end">
                      <button onClick={() => openEdit(s)} 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={() => handleDelete(s)} 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>
        </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">
                {modalMode === "edit" ? 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">
              <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">
                  <option value="">{lang === "bn" ? "— নির্বাচন করুন —" : "— Select —"}</option>
                  {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">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="e.g. LED Bulbs" />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-foreground">সাব-ক্যাটাগরি নাম (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="যেমন: LED বাল্ব" />
              </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>
  );
}
