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

export const Route = createFileRoute("/_authenticated/units")({
  head: () => ({
    meta: [
      { title: "Units — Niyamah Electric & Hardware" },
      { name: "description", content: "Unit management" },
    ],
  }),
  component: UnitsPage,
});

type UnitRow = {
  id: string;
  name: string;
  name_bn: string;
  short_code: string;
  status: string;
  deleted_at: string | null;
  created_at: string;
  product_count?: number;
};

function UnitsPage() {
  const { tr, lang } = useLanguage();
  const [units, setUnits] = useState<UnitRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [modalOpen, setModalOpen] = useState(false);
  const [editUnit, setEditUnit] = useState<UnitRow | null>(null);
  const [form, setForm] = useState({ name: "", name_bn: "", short_code: "", status: "active" });
  const [saving, setSaving] = useState(false);

  const fetchUnits = async () => {
    setLoading(true);
    const { data: unitsData } = await supabase
      .from("units")
      .select("*")
      .is("deleted_at", null)
      .order("created_at", { ascending: false });

    const { data: products } = await supabase
      .from("products")
      .select("unit")
      .eq("is_deleted", false);

    const countMap: Record<string, number> = {};
    (products || []).forEach((p: any) => {
      const u = (p.unit || "").toLowerCase();
      countMap[u] = (countMap[u] || 0) + 1;
    });

    setUnits(
      (unitsData || []).map((u: any) => ({
        ...u,
        product_count: countMap[u.name.toLowerCase()] || 0,
      }))
    );
    setLoading(false);
  };

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

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

  const openAdd = () => {
    setEditUnit(null);
    setForm({ name: "", name_bn: "", short_code: "", status: "active" });
    setModalOpen(true);
  };

  const openEdit = (u: UnitRow) => {
    setEditUnit(u);
    setForm({ name: u.name, name_bn: u.name_bn, short_code: u.short_code || "", status: u.status });
    setModalOpen(true);
  };

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

    // Check unique name
    const existing = units.find(
      (u) => u.name.toLowerCase() === form.name.trim().toLowerCase() && u.id !== editUnit?.id
    );
    if (existing) { toast.error("এই নামে Unit আগে থেকে আছে"); setSaving(false); return; }

    if (editUnit) {
      const { error } = await supabase.from("units").update({
        name: form.name.trim(),
        name_bn: form.name_bn.trim(),
        short_code: form.short_code.trim(),
        status: form.status,
      }).eq("id", editUnit.id);
      if (error) { toast.error("আপডেট করা যায়নি"); setSaving(false); return; }
      toast.success("Unit আপডেট হয়েছে");
    } else {
      const { error } = await supabase.from("units").insert({
        name: form.name.trim(),
        name_bn: form.name_bn.trim(),
        short_code: form.short_code.trim(),
        status: form.status,
      });
      if (error) { toast.error("যোগ করা যায়নি"); setSaving(false); return; }
      toast.success("Unit যোগ হয়েছে");
    }

    setSaving(false);
    setModalOpen(false);
    fetchUnits();
  };

  const handleDelete = async (u: UnitRow) => {
    if (u.product_count && u.product_count > 0) {
      toast.error("এই Unit এর সাথে Product যুক্ত আছে, আগে Product update করুন");
      return;
    }
    if (!confirm(`"${u.name}" মুছে ফেলতে চান?`)) return;
    const { error } = await supabase.from("units").update({ deleted_at: new Date().toISOString() }).eq("id", u.id);
    if (error) { toast.error("ডিলিট করা যায়নি"); return; }
    toast.success("Unit মুছে ফেলা হয়েছে");
    setUnits((prev) => prev.filter((x) => x.id !== u.id));
  };

  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("units")}</h1>
          <p className="text-sm text-muted-foreground">{tr("unitSubtitle")} — {units.length} {lang === "bn" ? "টি ইউনিট" : "units"}</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("addUnit")}
        </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 units..."} 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="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">{lang === "bn" ? "ইউনিট নাম" : "Unit Name"}</th>
                <th className="px-4 py-3 font-medium">{lang === "bn" ? "সংক্ষিপ্ত কোড" : "Short Code"}</th>
                <th className="px-4 py-3 font-medium">{lang === "bn" ? "পণ্য সংখ্যা" : "Products"}</th>
                <th className="px-4 py-3 font-medium">{lang === "bn" ? "স্ট্যাটাস" : "Status"}</th>
                <th className="px-4 py-3 font-medium">{lang === "bn" ? "তারিখ" : "Created"}</th>
                <th className="px-4 py-3 font-medium">{tr("action")}</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((u) => (
                <tr key={u.id} className="border-b border-border last:border-0 hover:bg-muted/30">
                  <td className="px-4 py-2.5">
                    <div className="flex items-center gap-2">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10">
                        <Ruler className="h-4 w-4 text-primary" />
                      </div>
                      <div>
                        <p className="font-medium text-foreground">{lang === "bn" ? u.name_bn || u.name : u.name}</p>
                        <p className="text-xs text-muted-foreground">{lang === "bn" ? u.name : u.name_bn}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-2.5">
                    <span className="rounded bg-muted px-2 py-0.5 font-mono text-xs">{u.short_code || "—"}</span>
                  </td>
                  <td className="px-4 py-2.5">
                    <span className="inline-flex items-center gap-1 rounded-full bg-secondary px-2.5 py-0.5 text-xs font-medium text-secondary-foreground">
                      {u.product_count || 0}
                    </span>
                  </td>
                  <td className="px-4 py-2.5">
                    <span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${u.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"}`}>
                      {u.status === "active" ? (lang === "bn" ? "সক্রিয়" : "Active") : (lang === "bn" ? "নিষ্ক্রিয়" : "Inactive")}
                    </span>
                  </td>
                  <td className="px-4 py-2.5 text-xs text-muted-foreground">
                    {new Date(u.created_at).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-US")}
                  </td>
                  <td className="px-4 py-2.5">
                    <div className="flex gap-1">
                      <button onClick={() => openEdit(u)} 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(u)} 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">
              <Ruler className="mr-2 h-4 w-4" />
              {lang === "bn" ? "কোনো ইউনিট পাওয়া যায়নি" : "No units found"}
            </div>
          )}
        </div>
      )}

      {/* Modal */}
      {modalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" 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">{editUnit ? tr("editUnit") : tr("addUnit")}</h2>
              <button onClick={() => setModalOpen(false)} 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">Unit 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. pcs, box, meter" />
              </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="যেমন: পিস, বক্স, মিটার" />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-foreground">{lang === "bn" ? "সংক্ষিপ্ত কোড" : "Short Code"}</label>
                <input type="text" value={form.short_code} onChange={(e) => setForm({ ...form, short_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. pc, bx, m" />
              </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={() => setModalOpen(false)} 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>
  );
}
