import React, { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Building2, CreditCard, Edit, Mail, MapPin, Phone, Plus, Store, Trash2 } from "lucide-react";

import { OcSupplierAPI } from "@/apis/OcSupplierAPI";
import { PaymentMethodAPI } from "@/apis/PaymentMethodAPI";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useCompanyStore } from "@/hooks/store/useCompanyStore";

const PAYMENT_METHOD_NONE = "__payment_method_none__";

const emptyForm = () => ({
  rut: "",
  business_name: "",
  trade_name: "",
  phone: "",
  email: "",
  address: "",
  giro: "",
  id_payment_method: "",
  notes: "",
});

/** @param {import("@/types/modules/ocSupplier").OcSupplier} s */
const supplierToForm = (s) => ({
  rut: String(s.rut ?? ""),
  business_name: String(s.business_name ?? ""),
  trade_name: String(s.trade_name ?? ""),
  phone: String(s.phone ?? ""),
  email: String(s.email ?? ""),
  address: String(s.address ?? ""),
  giro: String(s.giro ?? ""),
  id_payment_method: s.id_payment_method != null && String(s.id_payment_method) !== "" ? String(s.id_payment_method) : "",
  notes: String(s.notes ?? ""),
});

export default function OcSuppliers() {
  const queryClient = useQueryClient();
  const { selectedCompany } = useCompanyStore();
  const companyId = String(selectedCompany?.id ?? "");

  const [search, setSearch] = useState("");
  const [appliedSearch, setAppliedSearch] = useState("");

  const listParams = useMemo(() => {
    const p = {};
    if (appliedSearch.trim()) p.search = appliedSearch.trim();
    return p;
  }, [appliedSearch]);

  const listQuery = useQuery({
    queryKey: ["suppliers", companyId, listParams],
    queryFn: () => OcSupplierAPI.list(companyId, listParams),
    enabled: Boolean(companyId),
  });

  const paymentMethodsQuery = useQuery({
    queryKey: ["payment-methods", companyId],
    queryFn: () => PaymentMethodAPI.getByCompanyId(companyId),
    enabled: Boolean(companyId),
  });

  /** @type {null | 'create' | 'edit'} */
  const [activeForm, setActiveForm] = useState(null);
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState(emptyForm);

  const resetForm = () => {
    setForm(emptyForm());
    setEditingId(null);
    setActiveForm(null);
  };

  const openCreate = () => {
    setForm(emptyForm());
    setEditingId(null);
    setActiveForm("create");
  };

  /** @param {import("@/types/modules/ocSupplier").OcSupplier} row */
  const openEdit = (row) => {
    setForm(supplierToForm(row));
    setEditingId(String(row.id ?? ""));
    setActiveForm("edit");
  };

  const saveMutation = useMutation({
    mutationFn: async () => {
      const payload = {
        rut: form.rut.trim(),
        business_name: form.business_name.trim(),
        trade_name: form.trade_name.trim() || undefined,
        phone: form.phone.trim() || undefined,
        email: form.email.trim() || undefined,
        address: form.address.trim() || undefined,
        giro: form.giro.trim() || undefined,
        id_payment_method: form.id_payment_method ? Number(form.id_payment_method) : null,
        notes: form.notes.trim() || undefined,
        is_active: true,
      };
      if (activeForm === "create") {
        return OcSupplierAPI.create(companyId, payload);
      }
      if (activeForm === "edit" && editingId) {
        return OcSupplierAPI.update(companyId, editingId, payload);
      }
      return null;
    },
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["suppliers", companyId] });
      toast.success(activeForm === "create" ? "Proveedor creado." : "Proveedor actualizado.");
      resetForm();
    },
    onError: () => {
      toast.error("No se pudo guardar. Verifique el RUT (único por empresa) y los datos.");
    },
  });

  const deleteMutation = useMutation({
    mutationFn: ({ id }) => OcSupplierAPI.delete(companyId, id),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["suppliers", companyId] });
      toast.success("Proveedor eliminado.");
    },
    onError: () => toast.error("No se pudo eliminar el proveedor."),
  });

  const handleApplyFilters = () => setAppliedSearch(search);

  const rows = listQuery.data ?? [];

  return (
    <div className="p-4 lg:p-8 space-y-8">
      <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4">
        <div>
          <h1 className="text-3xl font-bold text-gradient">Proveedores</h1>
          <p className="text-gray-600 mt-1">
            {String(selectedCompany?.name ?? "Empresa")} • {rows.length}{" "}
            {rows.length === 1 ? "proveedor" : "proveedores"}
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button
            onClick={openCreate}
            disabled={!companyId}
            className="bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700"
          >
            <Plus className="w-4 h-4 mr-2" />
            Nuevo proveedor
          </Button>
        </div>
      </div>

      {!companyId ? (
        <p className="text-sm text-amber-800 bg-amber-50 border border-amber-200 rounded-lg p-3 max-w-3xl">
          Seleccione una empresa para administrar proveedores.
        </p>
      ) : null}

      <Card className="glass-card border-white/20">
        <CardContent className="p-4 space-y-4">
          <h2 className="text-base font-semibold text-slate-800">Filtros del listado</h2>
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:gap-4">
            <div className="flex-1">
              <Label>Buscar</Label>
              <Input
                placeholder="RUT, razón social, correo…"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleApplyFilters()}
              />
            </div>
            <Button type="button" className="bg-gradient-to-r from-blue-500 to-blue-600 shrink-0" onClick={handleApplyFilters}>
              Aplicar filtros
            </Button>
          </div>
        </CardContent>
      </Card>

      {activeForm ? (
        <Card className="glass-card border-white/20">
          <CardHeader>
            <CardTitle>{activeForm === "create" ? "Nuevo" : "Editar"} proveedor</CardTitle>
          </CardHeader>
          <CardContent>
            <form
              className="space-y-4"
              onSubmit={(e) => {
                e.preventDefault();
                if (!form.rut.trim() || !form.business_name.trim()) {
                  toast.error("RUT y razón social son obligatorios.");
                  return;
                }
                saveMutation.mutate();
              }}
            >
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>
                    RUT <span className="text-red-600">*</span>
                  </Label>
                  <Input
                    value={form.rut}
                    onChange={(e) => setForm((p) => ({ ...p, rut: e.target.value }))}
                    placeholder="Ej: 12.345.678-9"
                    required
                  />
                </div>
                <div>
                  <Label>Giro</Label>
                  <Input value={form.giro} onChange={(e) => setForm((p) => ({ ...p, giro: e.target.value }))} placeholder="Giro comercial" />
                </div>
                <div className="col-span-2">
                  <Label>
                    Razón social <span className="text-red-600">*</span>
                  </Label>
                  <Input
                    value={form.business_name}
                    onChange={(e) => setForm((p) => ({ ...p, business_name: e.target.value }))}
                    placeholder="Razón social del proveedor"
                    required
                  />
                </div>
                <div className="col-span-2">
                  <Label>Nombre fantasía</Label>
                  <Input
                    value={form.trade_name}
                    onChange={(e) => setForm((p) => ({ ...p, trade_name: e.target.value }))}
                    placeholder="Nombre de fantasía (opcional)"
                  />
                </div>
                <div>
                  <Label>Teléfono</Label>
                  <Input value={form.phone} onChange={(e) => setForm((p) => ({ ...p, phone: e.target.value }))} placeholder="Teléfono" />
                </div>
                <div>
                  <Label>Email</Label>
                  <Input type="email" value={form.email} onChange={(e) => setForm((p) => ({ ...p, email: e.target.value }))} placeholder="correo@empresa.cl" />
                </div>
                <div className="col-span-2">
                  <Label>Dirección</Label>
                  <Input value={form.address} onChange={(e) => setForm((p) => ({ ...p, address: e.target.value }))} placeholder="Dirección completa" />
                </div>
                <div className="col-span-2">
                  <Label>Forma de pago frecuente</Label>
                  <Select
                    value={form.id_payment_method ? String(form.id_payment_method) : PAYMENT_METHOD_NONE}
                    onValueChange={(v) =>
                      setForm((p) => ({ ...p, id_payment_method: v === PAYMENT_METHOD_NONE ? "" : v }))
                    }
                    disabled={!companyId || paymentMethodsQuery.isLoading}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Seleccione del maestro de formas de pago" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={PAYMENT_METHOD_NONE}>Sin seleccionar</SelectItem>
                      {(paymentMethodsQuery.data ?? [])
                        .filter((m) => m.id !== undefined && m.id !== null && String(m.id) !== "")
                        .map((m) => (
                          <SelectItem key={String(m.id)} value={String(m.id)}>
                            {String(m.name ?? "—")}
                            {m.code ? ` · ${m.code}` : ""}
                          </SelectItem>
                        ))}
                    </SelectContent>
                  </Select>
                  {companyId && !paymentMethodsQuery.isLoading && (paymentMethodsQuery.data ?? []).length === 0 ? (
                    <p className="text-xs text-amber-700 mt-1.5">No hay formas de pago activas en el maestro para esta empresa.</p>
                  ) : null}
                </div>
                <div className="col-span-2">
                  <Label>Notas internas</Label>
                  <Textarea value={form.notes} onChange={(e) => setForm((p) => ({ ...p, notes: e.target.value }))} placeholder="Observaciones internas" rows={3} />
                </div>
              </div>

              <div className="flex justify-end gap-3 pt-2">
                <Button type="button" variant="outline" onClick={resetForm} disabled={saveMutation.isPending}>
                  Cancelar
                </Button>
                <Button type="submit" className="bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700" disabled={saveMutation.isPending}>
                  {saveMutation.isPending ? "Guardando..." : activeForm === "create" ? "Crear proveedor" : "Guardar cambios"}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      ) : null}

      {listQuery.isLoading ? (
        <div className="animate-pulse space-y-6">
          <div className="h-8 bg-gray-200 rounded w-1/4 max-w-xs" />
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {[...Array(6)].map((_, i) => (
              <div key={i} className="h-56 bg-gray-200 rounded-xl" />
            ))}
          </div>
        </div>
      ) : rows.length === 0 ? (
        <div className="text-center py-16">
          <Store className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            {appliedSearch.trim() ? "Sin resultados" : "No hay proveedores"}
          </h2>
          <p className="text-gray-500 mb-6">
            {appliedSearch.trim()
              ? "Pruebe otro criterio de búsqueda o limpie los filtros."
              : "Agregue proveedores para usarlos en órdenes de compra."}
          </p>
          {companyId ? (
            <Button onClick={openCreate} className="bg-gradient-to-r from-blue-500 to-blue-600">
              <Plus className="w-4 h-4 mr-2" />
              {appliedSearch.trim() ? "Nuevo proveedor" : "Crear primer proveedor"}
            </Button>
          ) : null}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {rows.map((row) => (
            <Card
              key={String(row.id)}
              className="glass-card border-white/20 hover:shadow-xl transition-all duration-300"
            >
              <CardHeader>
                <div className="flex items-start justify-between gap-2">
                  <div className="flex-1 min-w-0">
                    <CardTitle className="text-lg leading-tight line-clamp-2">{row.business_name}</CardTitle>
                    {row.trade_name ? (
                      <div className="flex items-center gap-1 mt-2">
                        <Building2 className="w-3.5 h-3.5 text-amber-600 shrink-0" />
                        <span className="text-xs font-semibold text-amber-800 truncate">{row.trade_name}</span>
                      </div>
                    ) : null}
                  </div>
                  <Badge className="shrink-0 bg-emerald-100 text-emerald-800">Activo</Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                {row.email ? (
                  <div className="flex items-center gap-2 text-sm text-gray-600 min-w-0">
                    <Mail className="w-4 h-4 shrink-0" />
                    <span className="truncate">{row.email}</span>
                  </div>
                ) : null}
                {row.phone ? (
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    <Phone className="w-4 h-4 shrink-0" />
                    {row.phone}
                  </div>
                ) : null}
                {!row.email && !row.phone ? (
                  <div className="text-sm text-gray-400">Sin correo ni teléfono</div>
                ) : null}
                <div className="flex items-start gap-2 text-sm text-gray-600">
                  <CreditCard className="w-4 h-4 shrink-0 mt-0.5" />
                  <span className="line-clamp-2">{row.payment_terms || "Sin forma de pago"}</span>
                </div>
                {row.address ? (
                  <div className="flex items-start gap-2 text-sm text-gray-600">
                    <MapPin className="w-4 h-4 shrink-0 mt-0.5" />
                    <span className="line-clamp-2">{row.address}</span>
                  </div>
                ) : null}
                <div className="text-sm text-gray-600">
                  <strong>RUT:</strong> {row.rut}
                </div>
                <div className="flex gap-2 mt-4">
                  <Button type="button" variant="outline" className="flex-1" onClick={() => openEdit(row)}>
                    <Edit className="w-4 h-4 mr-2" />
                    Editar
                  </Button>
                  <Button
                    type="button"
                    variant="outline"
                    className="flex-1 text-red-600 border-red-200 hover:bg-red-50"
                    disabled={deleteMutation.isPending}
                    onClick={() => {
                      if (typeof window !== "undefined" && window.confirm("¿Eliminar este proveedor?")) {
                        deleteMutation.mutate({ id: String(row.id) });
                      }
                    }}
                  >
                    <Trash2 className="w-4 h-4 mr-2" />
                    Eliminar
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
