import { useEffect, useMemo, useState, type FormEvent } from "react";
import {
  BadgeDollarSignIcon,
  CheckCircle2Icon,
  ChevronDownIcon,
  PencilIcon,
  PlusIcon,
  SearchIcon,
  Trash2Icon,
  XIcon,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { getSupabaseClient, type GlmUser } from "@/lib/supabase";
import {
  loadTariffItems,
  mutateTariffItem,
  trackAppEvent,
  type TariffDraft,
  type TariffItem,
} from "@/lib/wmc-backend";

const COUNTRIES = [
  { code: "GT", name: "Guatemala" },
  { code: "CR", name: "Costa Rica" },
  { code: "SV", name: "El Salvador" },
  { code: "HN", name: "Honduras" },
  { code: "NI", name: "Nicaragua" },
];

const EMPTY_DRAFT: TariffDraft = {
  countryCode: "GT",
  country: "Guatemala",
  itemCode: "",
  category: "Personal",
  name: "",
  detail: "",
  mandatoryRequirement: "",
  formatScope: "WM, SP, BF",
  period: "",
  unitType: "",
  baseCostUsd: 0,
  sourceName: "Edición manual desde módulo Tarifario",
};

function itemToDraft(item: TariffItem): TariffDraft {
  return {
    countryCode: item.country_code,
    country: item.country_name,
    itemCode: item.item_code,
    category: item.category,
    name: item.name,
    detail: item.detail ?? "",
    mandatoryRequirement: item.mandatory_requirement ?? "",
    formatScope: item.format_scope,
    period: item.period ?? "",
    unitType: item.unit_type ?? "",
    baseCostUsd: Number(item.base_cost_usd),
    sourceName: item.source_name,
    effectiveFrom: item.effective_from,
  };
}

export function TariffDialog({ user }: { user: GlmUser }) {
  const [open, setOpen] = useState(false);
  const [items, setItems] = useState<TariffItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [query, setQuery] = useState("");
  const [country, setCountry] = useState("TODOS");
  const [editing, setEditing] = useState<TariffItem | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [draft, setDraft] = useState<TariffDraft>(EMPTY_DRAFT);

  const refresh = async () => {
    setLoading(true);
    setError("");
    try {
      const data = await loadTariffItems(getSupabaseClient());
      setItems(data);
    } catch (cause) {
      console.error(cause);
      setError("No se pudo cargar el Tarifario desde Supabase.");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!open) return;
    void refresh();
    void trackAppEvent(getSupabaseClient(), user, "tariff_opened");
  }, [open, user]);

  const filtered = useMemo(() => {
    const term = query.trim().toLowerCase();
    return items.filter((item) => {
      if (country !== "TODOS" && item.country_code !== country) return false;
      if (!term) return true;
      return [item.name, item.category, item.item_code, item.detail ?? "", item.country_name]
        .join(" ")
        .toLowerCase()
        .includes(term);
    });
  }, [country, items, query]);

  const beginCreate = () => {
    setEditing(null);
    setDraft(EMPTY_DRAFT);
    setError("");
    setNotice("");
    setShowForm(true);
  };

  const beginEdit = (item: TariffItem) => {
    setEditing(item);
    setDraft(itemToDraft(item));
    setError("");
    setNotice("");
    setShowForm(true);
  };

  const setCountryCode = (code: string) => {
    const selected = COUNTRIES.find((entry) => entry.code === code) ?? { code: "GT", name: "Guatemala" };
    setDraft((current) => ({ ...current, countryCode: selected.code, country: selected.name }));
  };

  const submit = async (event: FormEvent) => {
    event.preventDefault();
    if (!draft.name.trim() || !draft.category.trim() || !draft.itemCode.trim()) {
      setError("Nombre, código y categoría son obligatorios.");
      return;
    }
    if (!Number.isFinite(Number(draft.baseCostUsd)) || Number(draft.baseCostUsd) < 0) {
      setError("El costo USD debe ser un número válido mayor o igual a cero.");
      return;
    }

    const actionText = editing ? "actualizar" : "crear";
    if (!window.confirm(`¿Confirmas ${actionText} esta tarifa? El cambio quedará auditado en Supabase.`)) {
      return;
    }

    setSaving(true);
    setError("");
    setNotice("");
    try {
      await mutateTariffItem(
        getSupabaseClient(),
        user,
        editing ? "update" : "insert",
        editing ? { ...draft, id: editing.id } : draft,
      );
      setNotice(editing ? "Tarifa actualizada correctamente." : "Tarifa creada correctamente.");
      setShowForm(false);
      setEditing(null);
      await refresh();
    } catch (cause) {
      console.error(cause);
      setError(cause instanceof Error ? cause.message : "No se pudo guardar la tarifa.");
    } finally {
      setSaving(false);
    }
  };

  const deactivate = async (item: TariffItem) => {
    if (!window.confirm(`¿Confirmas eliminar/desactivar “${item.name}” del tarifario vigente?`)) return;
    setSaving(true);
    setError("");
    setNotice("");
    try {
      await mutateTariffItem(getSupabaseClient(), user, "deactivate", {
        id: item.id,
        countryCode: item.country_code,
        country: item.country_name,
        itemCode: item.item_code,
        category: item.category,
        name: item.name,
        baseCostUsd: Number(item.base_cost_usd),
      });
      setNotice("Tarifa desactivada correctamente.");
      await refresh();
    } catch (cause) {
      console.error(cause);
      setError(cause instanceof Error ? cause.message : "No se pudo desactivar la tarifa.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <button
          type="button"
          aria-label="Tarifario"
          className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border bg-card px-2.5 text-xs font-bold text-foreground transition-colors hover:bg-secondary sm:px-3"
        >
          <BadgeDollarSignIcon className="size-4" />
          <span className="hidden sm:inline">Tarifario</span>
        </button>
      </DialogTrigger>

      <DialogContent className="flex max-h-[88dvh] w-[min(96vw,70rem)] max-w-none flex-col overflow-hidden border-border bg-card p-0">
        <div className="h-1 shrink-0 bg-brand" />
        <div className="flex min-h-0 flex-1 flex-col p-5 sm:p-6">
          <DialogHeader className="shrink-0">
            <DialogTitle className="flex items-center gap-2 text-xl font-bold text-primary">
              <BadgeDollarSignIcon className="size-5" />
              Tarifario Walmart Connect
            </DialogTitle>
            <DialogDescription>
              Consulta, agrega, edita o elimina tarifas vigentes. Cada modificación requiere confirmación y queda auditada.
            </DialogDescription>
          </DialogHeader>

          <div className="mt-5 flex shrink-0 flex-col gap-2 sm:flex-row">
            <label className="relative min-w-0 flex-1">
              <SearchIcon className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
              <input
                value={query}
                onChange={(event) => setQuery(event.target.value)}
                placeholder="Buscar por nombre, código, categoría..."
                className="h-10 w-full rounded-lg border border-border bg-background pl-9 pr-3 text-sm outline-none focus:border-primary"
              />
            </label>
            <div className="relative shrink-0 sm:w-48">
              <select
                value={country}
                onChange={(event) => setCountry(event.target.value)}
                className="h-10 w-full appearance-none rounded-lg border border-border bg-background pl-3 pr-10 text-sm outline-none transition-colors focus:border-primary focus:ring-2 focus:ring-primary/10"
              >
                <option value="TODOS">Todos los países</option>
                {COUNTRIES.map((entry) => (
                  <option key={entry.code} value={entry.code}>{entry.name}</option>
                ))}
              </select>
              <ChevronDownIcon className="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            </div>
            <button
              type="button"
              onClick={beginCreate}
              className="inline-flex h-10 items-center justify-center gap-2 rounded-lg bg-primary px-4 text-sm font-bold text-primary-foreground hover:bg-primary/90"
            >
              <PlusIcon className="size-4" />
              Agregar tarifa
            </button>
          </div>

          {error ? <p className="mt-3 shrink-0 text-sm text-destructive">{error}</p> : null}
          {notice ? (
            <p className="mt-3 flex shrink-0 items-center gap-2 text-sm font-medium text-brand">
              <CheckCircle2Icon className="size-4" /> {notice}
            </p>
          ) : null}

          {showForm ? (
            <form onSubmit={submit} className="mt-4 shrink-0 rounded-xl border border-border bg-secondary/35 p-4">
              <div className="mb-3 flex items-center justify-between gap-3">
                <h3 className="text-sm font-bold text-primary">{editing ? "Editar tarifa" : "Nueva tarifa"}</h3>
                <button type="button" onClick={() => setShowForm(false)} className="text-muted-foreground hover:text-foreground">
                  <XIcon className="size-4" />
                </button>
              </div>
              <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                <label className="text-xs font-bold text-foreground">País
                  <span className="relative mt-1 block">
                    <select value={draft.countryCode} onChange={(event) => setCountryCode(event.target.value)} className="h-9 w-full appearance-none rounded-md border border-border bg-background pl-2 pr-9 text-sm font-normal outline-none focus:border-primary">
                      {COUNTRIES.map((entry) => <option key={entry.code} value={entry.code}>{entry.name}</option>)}
                    </select>
                    <ChevronDownIcon className="pointer-events-none absolute right-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
                  </span>
                </label>
                <label className="text-xs font-bold text-foreground">Código *
                  <input value={draft.itemCode} onChange={(event) => setDraft((v) => ({...v,itemCode:event.target.value}))} className="mt-1 h-9 w-full rounded-md border border-border bg-background px-2 text-sm font-normal" />
                </label>
                <label className="text-xs font-bold text-foreground">Categoría *
                  <input value={draft.category} onChange={(event) => setDraft((v) => ({...v,category:event.target.value}))} className="mt-1 h-9 w-full rounded-md border border-border bg-background px-2 text-sm font-normal" />
                </label>
                <label className="text-xs font-bold text-foreground">Costo unitario USD *
                  <input type="number" min="0" step="0.01" value={draft.baseCostUsd} onChange={(event) => setDraft((v) => ({...v,baseCostUsd:Number(event.target.value)}))} className="mt-1 h-9 w-full rounded-md border border-border bg-background px-2 text-sm font-normal" />
                </label>
                <label className="text-xs font-bold text-foreground sm:col-span-2">Nombre *
                  <input value={draft.name} onChange={(event) => setDraft((v) => ({...v,name:event.target.value}))} className="mt-1 h-9 w-full rounded-md border border-border bg-background px-2 text-sm font-normal" />
                </label>
                <label className="text-xs font-bold text-foreground">Período
                  <input value={draft.period ?? ""} onChange={(event) => setDraft((v) => ({...v,period:event.target.value}))} placeholder="1 día / Por unidad" className="mt-1 h-9 w-full rounded-md border border-border bg-background px-2 text-sm font-normal" />
                </label>
                <label className="text-xs font-bold text-foreground">Tipo de unidad
                  <input value={draft.unitType ?? ""} onChange={(event) => setDraft((v) => ({...v,unitType:event.target.value}))} placeholder="persona/día / unidad" className="mt-1 h-9 w-full rounded-md border border-border bg-background px-2 text-sm font-normal" />
                </label>
                <label className="text-xs font-bold text-foreground sm:col-span-2">Detalle
                  <textarea value={draft.detail ?? ""} onChange={(event) => setDraft((v) => ({...v,detail:event.target.value}))} rows={2} className="mt-1 w-full rounded-md border border-border bg-background px-2 py-2 text-sm font-normal" />
                </label>
                <label className="text-xs font-bold text-foreground">Requisito
                  <input value={draft.mandatoryRequirement ?? ""} onChange={(event) => setDraft((v) => ({...v,mandatoryRequirement:event.target.value}))} className="mt-1 h-9 w-full rounded-md border border-border bg-background px-2 text-sm font-normal" />
                </label>
                <label className="text-xs font-bold text-foreground">Alcance formato
                  <input value={draft.formatScope ?? ""} onChange={(event) => setDraft((v) => ({...v,formatScope:event.target.value}))} className="mt-1 h-9 w-full rounded-md border border-border bg-background px-2 text-sm font-normal" />
                </label>
              </div>
              <div className="mt-4 flex justify-end gap-2">
                <button type="button" onClick={() => setShowForm(false)} disabled={saving} className="h-9 rounded-lg border border-border bg-card px-4 text-sm font-bold hover:bg-secondary">Cancelar</button>
                <button type="submit" disabled={saving} className="h-9 rounded-lg bg-primary px-4 text-sm font-bold text-primary-foreground disabled:opacity-50">{saving ? "Guardando..." : editing ? "Guardar cambios" : "Crear tarifa"}</button>
              </div>
            </form>
          ) : null}

          <div className="scrollbar-slim mt-4 min-h-0 flex-1 overflow-auto rounded-xl border border-border">
            <table className="w-full min-w-[900px] border-collapse text-left text-sm">
              <thead className="sticky top-0 z-10 bg-secondary text-xs uppercase tracking-wide text-muted-foreground">
                <tr>
                  <th className="px-3 py-3">País</th>
                  <th className="px-3 py-3">Código</th>
                  <th className="px-3 py-3">Categoría</th>
                  <th className="px-3 py-3">Concepto</th>
                  <th className="px-3 py-3">Unidad / período</th>
                  <th className="px-3 py-3 text-right">USD</th>
                  <th className="px-3 py-3 text-right">Acciones</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr><td colSpan={7} className="px-4 py-10 text-center text-muted-foreground">Cargando tarifario...</td></tr>
                ) : filtered.length === 0 ? (
                  <tr><td colSpan={7} className="px-4 py-10 text-center text-muted-foreground">No se encontraron tarifas.</td></tr>
                ) : filtered.map((item) => (
                  <tr key={item.id} className="border-t border-border align-top hover:bg-secondary/30">
                    <td className="px-3 py-3 font-bold text-primary">{item.country_code}</td>
                    <td className="px-3 py-3 font-mono text-xs">{item.item_code}</td>
                    <td className="px-3 py-3">{item.category}</td>
                    <td className="max-w-[24rem] px-3 py-3"><div className="font-semibold text-foreground">{item.name}</div>{item.detail ? <div className="mt-1 line-clamp-2 text-xs text-muted-foreground">{item.detail}</div> : null}</td>
                    <td className="px-3 py-3 text-xs text-muted-foreground">{[item.unit_type,item.period].filter(Boolean).join(" · ") || "—"}</td>
                    <td className="px-3 py-3 text-right font-bold tabular-nums">${Number(item.base_cost_usd).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}</td>
                    <td className="px-3 py-3"><div className="flex justify-end gap-1"><button type="button" onClick={() => beginEdit(item)} title="Editar" className="grid size-8 place-items-center rounded-md text-primary hover:bg-primary/10"><PencilIcon className="size-4" /></button><button type="button" onClick={() => void deactivate(item)} disabled={saving} title="Eliminar / desactivar" className="grid size-8 place-items-center rounded-md text-destructive hover:bg-destructive/10 disabled:opacity-50"><Trash2Icon className="size-4" /></button></div></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <p className="mt-3 shrink-0 text-xs text-muted-foreground">{filtered.length} tarifa(s) visible(s).</p>
        </div>
      </DialogContent>
    </Dialog>
  );
}
