"use client";

import { useState } from "react";
import { LuX } from "react-icons/lu";
import { FiAlertTriangle } from "react-icons/fi";

interface Employee {
  id: string;
  name: string | null;
  username: string;
  _count?: {
    documents: number;
  };
}

interface DeleteConfirmModalProps {
  employee: Employee;
  onClose: () => void;
  onSuccess?: () => void;
  onConfirm?: () => Promise<void>;
  isDeleting?: boolean;
}

export default function DeleteConfirmModal({
  employee,
  onClose,
  onSuccess,
  onConfirm,
  isDeleting: parentIsDeleting,
}: DeleteConfirmModalProps) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [confirmText, setConfirmText] = useState("");

  const isDeleting = parentIsDeleting !== undefined ? parentIsDeleting : loading;

  const handleDelete = async () => {
    if (confirmText !== "ELIMINAR") {
      setError("Debes escribir ELIMINAR para confirmar");
      return;
    }

    setError("");
    setLoading(true);

    try {
      if (onConfirm) {
        // Usar la función proporcionada por el padre (hook)
        await onConfirm();
        if (onSuccess) onSuccess();
      } else {
        // Fallback a fetch directo (compatibilidad)
        const response = await fetch(`/api/employees/${employee.id}`, {
          method: "DELETE",
        });

        const data = await response.json();

        if (data.success) {
          if (onSuccess) onSuccess();
        } else {
          setError(data.error || "Error al eliminar el empleado");
        }
      }
    } catch (error) {
      setError(error instanceof Error ? error.message : "Error de conexión al eliminar el empleado");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-background border border-border rounded-lg max-w-md w-full p-6">
        <div className="flex items-start justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="bg-destructive/10 p-2 rounded-full">
              <FiAlertTriangle className="h-6 w-6 text-destructive" />
            </div>
            <h2 className="text-xl font-bold text-text">
              Eliminar Empleado
            </h2>
          </div>
          <button
            onClick={onClose}
            className="text-text-muted hover:text-text"
          >
            <LuX className="h-6 w-6" />
          </button>
        </div>

        <div className="space-y-4">
          {error && (
            <div className="bg-destructive/10 border border-destructive/20 text-destructive px-4 py-3 rounded">
              {error}
            </div>
          )}

          <div className="bg-amber-500/10 border border-amber-500/20 rounded-lg p-4">
            <p className="text-sm text-amber-600 dark:text-amber-400">
              <strong>¡Advertencia!</strong> Esta acción no se puede deshacer.
            </p>
          </div>

          <div className="space-y-2">
            <p className="text-text">
              Estás a punto de eliminar al empleado:
            </p>
            <div className="bg-background-alt p-3 rounded-lg border border-border">
              <p className="font-semibold text-text">
                {employee.name || "Sin nombre"}
              </p>
              <p className="text-sm text-text-muted">@{employee.username}</p>
              {employee._count && employee._count.documents > 0 && (
                <p className="text-sm text-destructive mt-2">
                  ⚠️ Tiene {employee._count.documents} documento(s) asociado(s)
                  que también se eliminarán
                </p>
              )}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-text mb-2">
              Para confirmar, escribe <strong>ELIMINAR</strong> en el campo de
              abajo:
            </label>
            <input
              type="text"
              value={confirmText}
              onChange={(e) => setConfirmText(e.target.value)}
              className="w-full px-3 py-2 bg-background border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-destructive text-text"
              placeholder="ELIMINAR"
            />
          </div>

          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-2 bg-background border border-border text-text rounded-lg hover:bg-background-alt focus:outline-none focus:ring-2 focus:ring-border"
              disabled={isDeleting}
            >
              Cancelar
            </button>
            <button
              type="button"
              onClick={handleDelete}
              className="flex-1 px-4 py-2 bg-destructive text-destructive-foreground rounded-lg hover:bg-destructive/90 focus:outline-none focus:ring-2 focus:ring-destructive disabled:opacity-50 disabled:cursor-not-allowed"
              disabled={isDeleting || confirmText !== "ELIMINAR"}
            >
              {isDeleting ? (
                <div className="flex items-center justify-center gap-2">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-destructive-foreground"></div>
                  Eliminando...
                </div>
              ) : (
                "Eliminar empleado"
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
