'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Header } from '@/components/layouts/header';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, Button, Input } from '@horux/shared-ui';
import { useAuthStore } from '@/stores/auth-store';
import { isGlobalAdminRfc } from '@horux/shared';
import {
  getPaquetesCatalogoAdmin,
  updatePaqueteCatalogo,
  type PaqueteCatalogoAdmin,
} from '@/lib/api/facturacion';
import { formatCurrency } from '@/lib/utils';
import { Package, ShieldAlert, Loader2, CheckCircle2, AlertTriangle, Save } from 'lucide-react';

export default function TimbresCatalogoPage() {
  const { user } = useAuthStore();
  const queryClient = useQueryClient();
  const isGlobalAdmin = isGlobalAdminRfc(user?.tenantRfc, user?.role, user?.platformRoles);

  const { data: catalogo = [], isLoading } = useQuery({
    queryKey: ['timbres-paquetes-catalogo-admin'],
    queryFn: getPaquetesCatalogoAdmin,
    enabled: isGlobalAdmin,
  });

  if (!isGlobalAdmin) {
    return (
      <>
        <Header title="Catálogo de timbres" />
        <main className="p-6">
          <Card>
            <CardContent className="py-12 text-center">
              <ShieldAlert className="h-12 w-12 text-muted-foreground/40 mx-auto mb-3" />
              <p className="font-semibold">Acceso restringido</p>
              <p className="text-sm text-muted-foreground mt-1">Solo admin global puede editar el catálogo.</p>
            </CardContent>
          </Card>
        </main>
      </>
    );
  }

  return (
    <>
      <Header title="Catálogo de timbres adicionales" />
      <main className="p-6 space-y-6">
        <Card className="bg-muted/30 border-dashed">
          <CardContent className="py-4 text-sm flex items-start gap-2">
            <AlertTriangle className="h-4 w-4 text-amber-600 mt-0.5 flex-shrink-0" />
            <div>
              Los cambios de precio aplican <strong>sólo a compras nuevas</strong>.
              Los paquetes ya vendidos conservan el precio que pagó el cliente (snapshot).
              Desactivar un paquete lo oculta del catálogo público pero no afecta
              paquetes vigentes.
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <Package className="h-4 w-4" />
              Paquetes en el catálogo
            </CardTitle>
            <CardDescription>Edita precio o da de baja. Orden por cantidad ascendente.</CardDescription>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <p className="text-center py-8 text-muted-foreground">Cargando...</p>
            ) : catalogo.length === 0 ? (
              <p className="text-center py-8 text-muted-foreground">No hay paquetes en el catálogo.</p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b text-left text-muted-foreground">
                      <th className="pb-2 font-medium">Cantidad</th>
                      <th className="pb-2 font-medium">Precio actual</th>
                      <th className="pb-2 font-medium">Precio por timbre</th>
                      <th className="pb-2 font-medium">Estado</th>
                      <th className="pb-2 font-medium">Última actualización</th>
                      <th className="pb-2 font-medium text-right">Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {catalogo.map((p) => (
                      <PaqueteRow key={p.id} paquete={p} onSaved={() => queryClient.invalidateQueries({ queryKey: ['timbres-paquetes-catalogo-admin'] })} />
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </>
  );
}

function PaqueteRow({ paquete, onSaved }: { paquete: PaqueteCatalogoAdmin; onSaved: () => void }) {
  const [editing, setEditing] = useState(false);
  const [precio, setPrecio] = useState(paquete.precio.toString());
  const [active, setActive] = useState(paquete.active);
  const [saved, setSaved] = useState(false);

  const mutation = useMutation({
    mutationFn: () => updatePaqueteCatalogo(paquete.id, {
      precio: Number(precio),
      active,
    }),
    onSuccess: () => {
      setEditing(false);
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
      onSaved();
    },
    onError: (err: any) => {
      alert(err?.response?.data?.message || 'Error al guardar');
    },
  });

  const precioNum = Number(precio);
  const precioValido = precioNum > 0 && !isNaN(precioNum);
  const hasChanges = Number(precio) !== paquete.precio || active !== paquete.active;

  return (
    <tr className="border-b last:border-0">
      <td className="py-3 font-medium">{paquete.cantidad.toLocaleString('es-MX')}</td>
      <td className="py-3">
        {editing ? (
          <div className="flex items-center gap-1">
            <span className="text-muted-foreground">$</span>
            <Input
              type="number"
              step="0.01"
              value={precio}
              onChange={(e) => setPrecio(e.target.value)}
              className="w-28 h-8"
            />
          </div>
        ) : (
          <span className="font-medium">{formatCurrency(paquete.precio)}</span>
        )}
      </td>
      <td className="py-3 text-muted-foreground">
        {precioValido ? formatCurrency(precioNum / paquete.cantidad) : '—'}
      </td>
      <td className="py-3">
        {editing ? (
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={active}
              onChange={(e) => setActive(e.target.checked)}
              className="h-4 w-4 accent-primary"
            />
            <span className="text-xs">{active ? 'Activo' : 'Inactivo'}</span>
          </label>
        ) : (
          <span className={`inline-block px-2 py-0.5 rounded text-xs font-medium border ${paquete.active ? 'bg-green-50 text-green-700 border-green-200' : 'bg-slate-50 text-slate-500 border-slate-200'}`}>
            {paquete.active ? 'Activo' : 'Inactivo'}
          </span>
        )}
      </td>
      <td className="py-3 text-xs text-muted-foreground">
        {new Date(paquete.updatedAt).toLocaleString('es-MX', { dateStyle: 'short', timeStyle: 'short' })}
      </td>
      <td className="py-3 text-right">
        {saved ? (
          <span className="text-xs text-green-700 inline-flex items-center gap-1">
            <CheckCircle2 className="h-3 w-3" /> Guardado
          </span>
        ) : editing ? (
          <div className="flex items-center gap-1 justify-end">
            <Button
              size="sm"
              variant="outline"
              onClick={() => {
                setEditing(false);
                setPrecio(paquete.precio.toString());
                setActive(paquete.active);
              }}
              disabled={mutation.isPending}
            >
              Cancelar
            </Button>
            <Button
              size="sm"
              onClick={() => mutation.mutate()}
              disabled={mutation.isPending || !precioValido || !hasChanges}
            >
              {mutation.isPending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3 mr-1" />}
              Guardar
            </Button>
          </div>
        ) : (
          <Button size="sm" variant="outline" onClick={() => setEditing(true)}>
            Editar
          </Button>
        )}
      </td>
    </tr>
  );
}
