"use client";

import { useState } from "react";

import { Trash2 } from "lucide-react";
import { toast } from "sonner";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";

import type { User } from "@/types/users";

interface DeleteUserDialogProps {
  user: User;
  onUserDeleted: () => void;
}

export function DeleteUserDialog({
  user,
  onUserDeleted,
}: DeleteUserDialogProps) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleDelete = async () => {
    setLoading(true);

    try {
      const response = await fetch(`/api/users/${user.id}`, {
        method: "DELETE",
      });

      const apiResponseSchema = z.object({
        success: z.boolean(),
        error: z.string().optional(),
      });
      const json: unknown = await response.json();
      const data = apiResponseSchema.parse(json);

      if (!response.ok || !data.success) {
        throw new Error(data.error ?? "Error al eliminar usuario");
      }

      toast.success("Usuario eliminado exitosamente");
      setOpen(false);
      onUserDeleted();
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : "Error al eliminar usuario",
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="ghost" size="icon" className="text-red-600">
          <Trash2 className="h-4 w-4" />
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Eliminar Usuario</DialogTitle>
          <DialogDescription>
            ¿Estás seguro de que deseas eliminar a{" "}
            <span className="font-semibold">{user.name}</span>? Esta acción no
            se puede deshacer.
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => setOpen(false)}
            disabled={loading}
          >
            Cancelar
          </Button>
          <Button
            type="button"
            variant="destructive"
            onClick={handleDelete}
            disabled={loading}
          >
            {loading ? "Eliminando..." : "Eliminar"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
