import { useState, type ReactNode } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from "@/components/ui/dialog";
import { toast } from "sonner";
import { Plus, Pencil, Trash2, Search } from "lucide-react";
import { useT } from "@/lib/i18n";

export type ContactField = "name" | "phone" | "address" | "note";

/** Generic page for contact-like tables: customers, suppliers */
export function ContactPage({
  table, title, addLabel, showDue = true,
}: { table: "customers" | "suppliers"; title: string; addLabel: string; showDue?: boolean }) {
  const { t, lang } = useT();
  const qc = useQueryClient();
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [search, setSearch] = useState("");

  const { data: rows = [] } = useQuery({
    queryKey: [table],
    queryFn: async () => (await supabase.from(table).select("*").order("created_at", { ascending: false })).data || [],
  });

  const filtered = rows.filter((r: any) =>
    r.name.toLowerCase().includes(search.toLowerCase()) || (r.phone || "").includes(search)
  );

  const save = async (f: any) => {
    const { data: u } = await supabase.auth.getUser();
    if (!u.user) return;
    const payload = { user_id: u.user.id, name: f.name, phone: f.phone || null, address: f.address || null, note: f.note || null };
    const res = editing
      ? await supabase.from(table).update(payload).eq("id", editing.id)
      : await supabase.from(table).insert(payload);
    if (res.error) return toast.error(res.error.message);
    toast.success(t("saved"));
    qc.invalidateQueries({ queryKey: [table] });
    setOpen(false); setEditing(null);
  };

  const del = async (id: string) => {
    if (!confirm(t("confirm_delete"))) return;
    const { error } = await supabase.from(table).delete().eq("id", id);
    if (error) return toast.error(error.message);
    toast.success(t("deleted"));
    qc.invalidateQueries({ queryKey: [table] });
  };

  return (
    <div className="space-y-6 max-w-6xl mx-auto">
      <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-4">
        <h1 className="text-2xl md:text-3xl font-extrabold truncate">{title}</h1>
        <Dialog open={open} onOpenChange={(v) => { setOpen(v); if (!v) setEditing(null); }}>
          <DialogTrigger asChild><Button className="gradient-primary text-white"><Plus className="size-4 mr-1" /> {addLabel}</Button></DialogTrigger>
          <ContactDialog editing={editing} onSave={save} title={addLabel} />
        </Dialog>
      </div>

      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
        <Input placeholder={t("search")} value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9" />
      </div>

      {filtered.length === 0 ? (
        <Card><CardContent className="p-12 text-center text-muted-foreground">{t("no_data")}</CardContent></Card>
      ) : (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-3">
          {filtered.map((r: any) => (
            <Card key={r.id} className="shadow-card hover:shadow-elegant transition">
              <CardContent className="p-4">
                <div className="flex justify-between items-start gap-2">
                  <div className="min-w-0 flex-1">
                    <h3 className="font-bold truncate">{r.name}</h3>
                    {r.phone && <div className="text-sm text-muted-foreground">{r.phone}</div>}
                    {r.address && <div className="text-xs text-muted-foreground truncate">{r.address}</div>}
                  </div>
                  <div className="flex gap-1">
                    <Button size="icon" variant="ghost" onClick={() => { setEditing(r); setOpen(true); }}><Pencil className="size-4" /></Button>
                    <Button size="icon" variant="ghost" onClick={() => del(r.id)}><Trash2 className="size-4 text-destructive" /></Button>
                  </div>
                </div>
                {showDue && Number(r.due) > 0 && (
                  <div className="mt-2 pt-2 border-t text-sm">
                    <span className="text-muted-foreground">{t("due")}: </span>
                    <span className="font-bold text-destructive">৳{Number(r.due).toLocaleString(lang === "bn" ? "bn-BD" : "en-IN")}</span>
                  </div>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

function ContactDialog({ editing, onSave, title }: any) {
  const { t } = useT();
  const [f, setF] = useState({
    name: editing?.name || "", phone: editing?.phone || "",
    address: editing?.address || "", note: editing?.note || "",
  });
  return (
    <DialogContent>
      <DialogHeader><DialogTitle>{title}</DialogTitle></DialogHeader>
      <div className="space-y-3">
        <Fld label={t("name") + " *"}><Input value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></Fld>
        <Fld label={t("phone")}><Input value={f.phone} onChange={(e) => setF({ ...f, phone: e.target.value })} /></Fld>
        <Fld label={t("address")}><Input value={f.address} onChange={(e) => setF({ ...f, address: e.target.value })} /></Fld>
        <Fld label={t("note")}><Input value={f.note} onChange={(e) => setF({ ...f, note: e.target.value })} /></Fld>
      </div>
      <DialogFooter>
        <Button onClick={() => onSave(f)} disabled={!f.name} className="gradient-primary text-white">{t("save")}</Button>
      </DialogFooter>
    </DialogContent>
  );
}

function Fld({ label, children }: { label: string; children: ReactNode }) {
  return <div className="space-y-1.5"><Label className="text-sm font-semibold">{label}</Label>{children}</div>;
}

/** Generic simple list page for name-only tables: categories, brands */
export function SimpleNamePage({
  table, title, addLabel,
}: { table: "categories" | "brands"; title: string; addLabel: string }) {
  const { t } = useT();
  const qc = useQueryClient();
  const [name, setName] = useState("");
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editingName, setEditingName] = useState("");

  const { data: rows = [] } = useQuery({
    queryKey: [table],
    queryFn: async () => (await supabase.from(table).select("*").order("created_at", { ascending: false })).data || [],
  });

  const add = async () => {
    if (!name.trim()) return;
    const { data: u } = await supabase.auth.getUser();
    if (!u.user) return;
    const { error } = await supabase.from(table).insert({ user_id: u.user.id, name: name.trim() });
    if (error) return toast.error(error.message);
    setName("");
    qc.invalidateQueries({ queryKey: [table] });
  };

  const update = async (id: string) => {
    const { error } = await supabase.from(table).update({ name: editingName }).eq("id", id);
    if (error) return toast.error(error.message);
    setEditingId(null);
    qc.invalidateQueries({ queryKey: [table] });
  };

  const del = async (id: string) => {
    if (!confirm(t("confirm_delete"))) return;
    await supabase.from(table).delete().eq("id", id);
    qc.invalidateQueries({ queryKey: [table] });
  };

  return (
    <div className="space-y-6 max-w-3xl mx-auto">
      <h1 className="text-2xl md:text-3xl font-extrabold">{title}</h1>
      <Card><CardContent className="p-4 flex gap-2">
        <Input value={name} onChange={(e) => setName(e.target.value)} placeholder={addLabel} onKeyDown={(e) => e.key === "Enter" && add()} />
        <Button onClick={add} className="gradient-primary text-white"><Plus className="size-4 mr-1" />{t("save")}</Button>
      </CardContent></Card>

      {rows.length === 0 ? (
        <Card><CardContent className="p-12 text-center text-muted-foreground">{t("no_data")}</CardContent></Card>
      ) : (
        <Card>
          <CardContent className="p-0 divide-y">
            {rows.map((r: any) => (
              <div key={r.id} className="p-3 flex items-center gap-2">
                {editingId === r.id ? (
                  <>
                    <Input value={editingName} onChange={(e) => setEditingName(e.target.value)} className="flex-1" />
                    <Button size="sm" onClick={() => update(r.id)}>{t("save")}</Button>
                    <Button size="sm" variant="ghost" onClick={() => setEditingId(null)}>{t("cancel")}</Button>
                  </>
                ) : (
                  <>
                    <div className="flex-1 font-medium">{r.name}</div>
                    <Button size="icon" variant="ghost" onClick={() => { setEditingId(r.id); setEditingName(r.name); }}><Pencil className="size-4" /></Button>
                    <Button size="icon" variant="ghost" onClick={() => del(r.id)}><Trash2 className="size-4 text-destructive" /></Button>
                  </>
                )}
              </div>
            ))}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
