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, Tag, X, Upload } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { usePermissions } from "@/hooks/use-permissions";

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

type BrandRow = {
  id: string;
  name: string;
  logo: string;
  description: string;
  status: string;
  created_at: string;
  product_count?: number;
};

const empty = { name: "", logo: "", description: "", status: "active" };

function BrandsPage() {
  const { tr, lang } = useLanguage();
  const { isAdmin } = usePermissions();
  const [rows, setRows] = useState<BrandRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [modalOpen, setModalOpen] = useState(false);
  const [editItem, setEditItem] = useState<BrandRow | null>(null);
  const [form, setForm] = useState({ ...empty });
  const [logoFile, setLogoFile] = useState<File | null>(null);
  const [logoPreview, setLogoPreview] = useState<string>("");
  const [saving, setSaving] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    const [{ data: brands }, { data: products }] = await Promise.all([
      supabase.from("brands").select("*").is("deleted_at", null).order("created_at", { ascending: false }),
      supabase.from("products").select("brand_id").eq("is_deleted", false),
    ]);
    const counts: Record<string, number> = {};
    (products || []).forEach((p: any) => { if (p.brand_id) counts[p.brand_id] = (counts[p.brand_id] || 0) + 1; });
    setRows(((brands as BrandRow[]) || []).map((b) => ({ ...b, product_count: counts[b.id] || 0 })));
    setLoading(false);
  };

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

  const filtered = useMemo(() => rows.filter((r) => {
    const s = search.toLowerCase();
    const matchS = !search || r.name.toLowerCase().includes(s);
    const matchST = statusFilter === "all" || r.status === statusFilter;
    return matchS && matchST;
  }), [rows, search, statusFilter]);

  const openAdd = () => { setEditItem(null); setForm({ ...empty }); setLogoFile(null); setLogoPreview(""); setModalOpen(true); };
  const openEdit = (r: BrandRow) => {
    setEditItem(r);
    setForm({ name: r.name, logo: r.logo || "", description: r.description || "", status: r.status });
    setLogoFile(null); setLogoPreview(r.logo || "");
    setModalOpen(true);
  };
  const handleDelete = async (r: BrandRow) => {
    if ((r.product_count || 0) > 0) { toast.error(lang === "bn" ? "এই ব্র্যান্ডে পণ্য আছে" : "Brand has products"); return; }
    if (!confirm(`"${r.name}" ${lang === "bn" ? "মুছে ফেলতে চান?" : "delete?"}`)) return;
    const { error } = await supabase.from("brands").update({ deleted_at: new Date().toISOString() }).eq("id", r.id);
    if (error) { toast.error(lang === "bn" ? "ডিলিট করা যায়নি" : "Delete failed"); return; }
    toast.success(lang === "bn" ? "ব্র্যান্ড মুছে ফেলা হয়েছে" : "Brand deleted");
    setRows((p) => p.filter((x) => x.id !== r.id));
  };

  const handleLogo = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!["image/jpeg", "image/png", "image/webp", "image/svg+xml"].includes(file.type)) {
      toast.error("JPG/PNG/WebP/SVG only"); return;
    }
    if (file.size > 2 * 1024 * 1024) { toast.error("Max 2 MB"); return; }
    setLogoFile(file);
    setLogoPreview(URL.createObjectURL(file));
  };

  const handleSave = async () => {
    if (!form.name.trim()) { toast.error(lang === "bn" ? "নাম লিখুন" : "Name required"); return; }
    setSaving(true);
    let logoUrl = form.logo;
    if (logoFile) {
      const ext = logoFile.name.split(".").pop();
      const path = `${Date.now()}-${form.name.replace(/[^a-z0-9]/gi, "_")}.${ext}`;
      const { error: upErr } = await supabase.storage.from("brand-logos").upload(path, logoFile);
      if (upErr) { toast.error("Upload failed"); setSaving(false); return; }
      logoUrl = supabase.storage.from("brand-logos").getPublicUrl(path).data.publicUrl;
    }
    const payload = { name: form.name.trim(), logo: logoUrl, description: form.description.trim(), status: form.status };
    if (editItem) {
      const { error } = await supabase.from("brands").update(payload).eq("id", editItem.id);
      if (error) { toast.error(lang === "bn" ? "আপডেট করা যায়নি" : "Update failed"); setSaving(false); return; }
      toast.success(lang === "bn" ? "ব্র্যান্ড আপডেট হয়েছে" : "Brand updated");
    } else {
      const { error } = await supabase.from("brands").insert(payload);
      if (error) { toast.error(lang === "bn" ? "যোগ করা যায়নি" : "Add failed"); setSaving(false); return; }
      toast.success(lang === "bn" ? "ব্র্যান্ড যোগ হয়েছে" : "Brand added");
    }
    setSaving(false); setModalOpen(false); fetchData();
  };

  const inputCls = "w-full rounded-lg border border-input bg-card px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring";

  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("brands")}</h1>
          <p className="text-sm text-muted-foreground">{tr("brandManagement")} — {rows.length}</p>
        </div>
        {isAdmin && (
          <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 hover:bg-primary/90">
            <Plus className="h-4 w-4" /> {tr("addBrand")}
          </button>
        )}
      </div>

      <div className="mb-4 flex flex-wrap 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 value={search} onChange={(e) => setSearch(e.target.value)} placeholder={lang === "bn" ? "ব্র্যান্ড খুঁজুন..." : "Search brands..."} 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">
          <option value="all">{lang === "bn" ? "সব" : "All"}</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="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {filtered.map((r) => (
            <div key={r.id} className="rounded-xl border border-border bg-card p-4">
              <div className="flex items-start gap-3">
                <div className="flex h-14 w-14 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted">
                  {r.logo ? <img src={r.logo} alt={r.name} className="h-full w-full object-contain" /> : <Tag className="h-6 w-6 text-muted-foreground" />}
                </div>
                <div className="min-w-0 flex-1">
                  <p className="truncate font-medium text-foreground">{r.name}</p>
                  <p className="text-xs text-muted-foreground">{r.product_count} {tr("totalProducts")}</p>
                  <span className={`mt-1 inline-flex rounded-full px-2 py-0.5 text-[10px] font-medium ${r.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"}`}>
                    {r.status === "active" ? (lang === "bn" ? "সক্রিয়" : "Active") : (lang === "bn" ? "নিষ্ক্রিয়" : "Inactive")}
                  </span>
                </div>
                {isAdmin && (
                  <div className="flex flex-col gap-1">
                    <button onClick={() => openEdit(r)} 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(r)} 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>
              {r.description && <p className="mt-2 line-clamp-2 text-xs text-muted-foreground">{r.description}</p>}
            </div>
          ))}
          {filtered.length === 0 && (
            <div className="col-span-full flex h-32 items-center justify-center rounded-xl border border-border bg-card text-muted-foreground">
              {lang === "bn" ? "কোনো ব্র্যান্ড পাওয়া যায়নি" : "No brands found"}
            </div>
          )}
        </div>
      )}

      {modalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setModalOpen(false)}>
          <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">{editItem ? tr("editBrand") : tr("addBrand")}</h2>
              <button onClick={() => setModalOpen(false)} className="rounded p-1 hover:bg-muted"><X className="h-4 w-4" /></button>
            </div>
            <div className="space-y-3">
              <div>
                <label className="mb-1 block text-sm font-medium">{tr("brandLogo")}</label>
                <div className="flex items-center gap-3">
                  <div className="flex h-16 w-16 items-center justify-center overflow-hidden rounded-lg border border-border bg-muted">
                    {logoPreview ? <img src={logoPreview} alt="" className="h-full w-full object-contain" /> : <Tag className="h-6 w-6 text-muted-foreground" />}
                  </div>
                  <label className="flex cursor-pointer items-center gap-2 rounded-lg border border-border bg-secondary px-3 py-2 text-xs hover:bg-secondary/80">
                    <Upload className="h-3.5 w-3.5" /> {lang === "bn" ? "লোগো আপলোড" : "Upload logo"}
                    <input type="file" accept="image/*" className="hidden" onChange={handleLogo} />
                  </label>
                </div>
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium">{tr("brandName")} *</label>
                <input className={inputCls} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium">{tr("description")}</label>
                <textarea rows={3} className={inputCls} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium">{lang === "bn" ? "স্ট্যাটাস" : "Status"}</label>
                <select className={inputCls} value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
                  <option value="active">{lang === "bn" ? "সক্রিয়" : "Active"}</option>
                  <option value="inactive">{lang === "bn" ? "নিষ্ক্রিয়" : "Inactive"}</option>
                </select>
              </div>
            </div>
            <div className="mt-5 flex justify-end gap-2">
              <button onClick={() => setModalOpen(false)} className="rounded-lg border border-border px-4 py-2 text-sm">{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>
  );
}
