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

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

type BranchRow = {
  id: string;
  name: string;
  code: string;
  mobile: string;
  email: string;
  address: string;
  manager_name: string;
  status: string;
  created_at: string;
};

const empty = { name: "", code: "", mobile: "", email: "", address: "", manager_name: "", status: "active" };

function BranchesPage() {
  const { tr, lang } = useLanguage();
  const { isAdmin } = usePermissions();
  const [rows, setRows] = useState<BranchRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [salesByBranch, setSalesByBranch] = useState<Record<string, number>>({});
  const [modalOpen, setModalOpen] = useState(false);
  const [editItem, setEditItem] = useState<BranchRow | null>(null);
  const [form, setForm] = useState({ ...empty });
  const [saving, setSaving] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    const { data } = await supabase.from("branches").select("*").is("deleted_at", null).order("created_at", { ascending: false });
    setRows((data as BranchRow[]) || []);
    // total sales per branch via products.branch_id → invoice items? Skip for phase 1, show 0
    setSalesByBranch({});
    setLoading(false);
  };

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

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

  const openAdd = () => { setEditItem(null); setForm({ ...empty }); setModalOpen(true); };
  const openEdit = (r: BranchRow) => {
    setEditItem(r);
    setForm({ name: r.name, code: r.code || "", mobile: r.mobile || "", email: r.email || "", address: r.address || "", manager_name: r.manager_name || "", status: r.status });
    setModalOpen(true);
  };
  const handleDelete = async (r: BranchRow) => {
    if (!confirm(`"${r.name}" ${lang === "bn" ? "মুছে ফেলতে চান?" : "delete?"}`)) return;
    const { error } = await supabase.from("branches").update({ deleted_at: new Date().toISOString() }).eq("id", r.id);
    if (error) { toast.error(lang === "bn" ? "ডিলিট করা যায়নি" : "Delete failed"); return; }
    toast.success(lang === "bn" ? "শাখা মুছে ফেলা হয়েছে" : "Branch deleted");
    setRows((p) => p.filter((x) => x.id !== r.id));
  };

  const handleSave = async () => {
    if (!form.name.trim()) { toast.error(lang === "bn" ? "নাম লিখুন" : "Name required"); return; }
    setSaving(true);
    const payload = {
      name: form.name.trim(), code: form.code.trim(), mobile: form.mobile.trim(), email: form.email.trim(),
      address: form.address.trim(), manager_name: form.manager_name.trim(), status: form.status,
    };
    if (editItem) {
      const { error } = await supabase.from("branches").update(payload).eq("id", editItem.id);
      if (error) { toast.error(lang === "bn" ? "আপডেট করা যায়নি" : "Update failed"); setSaving(false); return; }
      toast.success(lang === "bn" ? "শাখা আপডেট হয়েছে" : "Branch updated");
    } else {
      const { error } = await supabase.from("branches").insert(payload);
      if (error) { toast.error(lang === "bn" ? "যোগ করা যায়নি" : "Add failed"); setSaving(false); return; }
      toast.success(lang === "bn" ? "শাখা যোগ হয়েছে" : "Branch 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("branches")}</h1>
          <p className="text-sm text-muted-foreground">{tr("branchManagement")} — {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("addBranch")}
          </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 branches..."} 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 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="overflow-hidden rounded-xl border border-border bg-card">
          <table className="w-full text-sm">
            <thead className="bg-muted/50 text-xs text-muted-foreground">
              <tr>
                <th className="px-4 py-3 text-left">{tr("branchName")}</th>
                <th className="px-4 py-3 text-left">{tr("branchCode")}</th>
                <th className="px-4 py-3 text-left">{lang === "bn" ? "মোবাইল" : "Mobile"}</th>
                <th className="px-4 py-3 text-left">{tr("managerName")}</th>
                <th className="px-4 py-3 text-left">{lang === "bn" ? "স্ট্যাটাস" : "Status"}</th>
                <th className="px-4 py-3 text-right">{lang === "bn" ? "অ্যাকশন" : "Action"}</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((r) => (
                <tr key={r.id} className="border-t border-border hover:bg-muted/30">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10"><Building2 className="h-4 w-4 text-primary" /></div>
                      <span className="font-medium text-foreground">{r.name}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 font-mono text-xs text-muted-foreground">{r.code || "—"}</td>
                  <td className="px-4 py-3 text-muted-foreground">{r.mobile || "—"}</td>
                  <td className="px-4 py-3 text-muted-foreground">{r.manager_name || "—"}</td>
                  <td className="px-4 py-3">
                    <span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs 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>
                  </td>
                  <td className="px-4 py-3">
                    {isAdmin && (
                      <div className="flex justify-end 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>
                    )}
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan={6} className="py-8 text-center text-muted-foreground">{lang === "bn" ? "কোনো শাখা পাওয়া যায়নি" : "No branches found"}</td></tr>
              )}
            </tbody>
          </table>
        </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-lg 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("editBranch") : tr("addBranch")}</h2>
              <button onClick={() => setModalOpen(false)} className="rounded p-1 hover:bg-muted"><X className="h-4 w-4" /></button>
            </div>
            <div className="grid gap-3 md:grid-cols-2">
              <div className="md:col-span-2">
                <label className="mb-1 block text-sm font-medium">{tr("branchName")} *</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("branchCode")}</label>
                <input className={inputCls} value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value })} />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium">{lang === "bn" ? "মোবাইল" : "Mobile"}</label>
                <input className={inputCls} value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value })} />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium">Email</label>
                <input className={inputCls} value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium">{tr("managerName")}</label>
                <input className={inputCls} value={form.manager_name} onChange={(e) => setForm({ ...form, manager_name: e.target.value })} />
              </div>
              <div className="md:col-span-2">
                <label className="mb-1 block text-sm font-medium">{lang === "bn" ? "ঠিকানা" : "Address"}</label>
                <textarea rows={2} className={inputCls} value={form.address} onChange={(e) => setForm({ ...form, address: 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>
  );
}
