"use client";

import { useState, useEffect } from "react";
import { LuX, LuUser, LuLock, LuCircleUser, LuCheck, LuEyeOff, LuEye, LuUsers } from "react-icons/lu";
import { CreateUserInput } from "@/types/auth";

interface CreateUserDrawerProps {
    isOpen: boolean;
    onClose: () => void;
    onSuccess?: () => void;
    onCreateUser?: (data: CreateUserInput) => Promise<void>;
}

export default function CreateUserDrawer({
    isOpen,
    onClose,
    onSuccess,
    onCreateUser,
}: CreateUserDrawerProps) {
    const [name, setName] = useState("");
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [role, setRole] = useState("USER");
    const [showPassword, setShowPassword] = useState(false);
    const [error, setError] = useState("");
    const [isSubmitting, setIsSubmitting] = useState(false);

    // Cerrar con ESC
    useEffect(() => {
        const handleEsc = (e: KeyboardEvent) => {
            if (e.key === "Escape") onClose();
        };
        if (isOpen) {
            window.addEventListener("keydown", handleEsc);
        }
        return () => window.removeEventListener("keydown", handleEsc);
    }, [isOpen, onClose]);

    // Limpiar formulario al cerrar
    useEffect(() => {
        if (!isOpen) {
            setName("");
            setUsername("");
            setPassword("");
            setRole("USER");
            setError("");
        }
    }, [isOpen]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError("");
        setIsSubmitting(true);

        // Validaciones
        if (!name || !username || !password) {
            setError("Todos los campos son obligatorios.");
            setIsSubmitting(false);
            return;
        }

        if (username.length < 3) {
            setError("El nombre de usuario debe tener al menos 3 caracteres.");
            setIsSubmitting(false);
            return;
        }

        if (/\s/.test(username)) {
            setError("El nombre de usuario no puede contener espacios.");
            setIsSubmitting(false);
            return;
        }

        if (password.length < 6) {
            setError("La contraseña debe tener al menos 6 caracteres.");
            setIsSubmitting(false);
            return;
        }

        try {
            if (onCreateUser) {
                // Usar la función proporcionada por el padre (hook)
                await onCreateUser({ 
                    name, 
                    username, 
                    password, 
                    role: role as 'USER' | 'ADMIN' 
                });
                if (onSuccess) onSuccess();
                onClose();
            } else {
                // Fallback a fetch directo (compatibilidad)
                const res = await fetch("/api/employees", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ name, username, password, role }),
                });

                const data = await res.json();

                if (res.ok) {
                    if (onSuccess) onSuccess();
                    onClose();
                } else {
                    setError(data.error || "Error al registrar. Inténtalo de nuevo.");
                }
            }
        } catch (err) {
            setError(err instanceof Error ? err.message : "Ocurrió un error inesperado.");
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <>
            {/* Overlay */}
            <div
                className={`fixed inset-0 bg-overlay z-40 transition-opacity duration-300 ${isOpen ? "opacity-100" : "opacity-0 pointer-events-none"
                    }`}
                onClick={onClose}
            />

            {/* Drawer */}
            <div
                className={`fixed right-0 top-0 h-full w-full md:w-[450px] bg-background shadow-2xl z-50 transform transition-transform duration-300 ease-in-out flex flex-col ${isOpen ? "translate-x-0" : "translate-x-full"
                    }`}
            >
                {/* Header */}
                <div className="px-6 py-5 border-b border-border-subtle flex items-center justify-between">
                    <div>
                        <h2 className="text-xl font-bold text-text">Registrar Nuevo Usuario</h2>
                        <p className="text-sm text-text-subtle mt-0.5">
                            Ingresa los datos para crear una nueva cuenta
                        </p>
                    </div>
                    <button
                        onClick={onClose}
                        className="p-2 hover:bg-background-alt rounded-full transition-colors text-text-subtle hover:text-text-muted focus-ring"
                    >
                        <LuX className="h-6 w-6" />
                    </button>
                </div>

                {/* Form */}
                <form onSubmit={handleSubmit} id="create-user-form" className="flex-1 flex flex-col p-6 space-y-5 overflow-y-auto">
                    {error && (
                        <div className="p-3 text-sm text-destructive bg-destructive-background border border-destructive-border rounded-lg">
                            {error}
                        </div>
                    )}

                    {/* Nombre Completo */}
                    <div>
                        <label htmlFor="name" className="block text-sm font-semibold text-text mb-2">
                            Nombre Completo
                        </label>
                        <div className="relative">
                            <LuCircleUser className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-text-subtle" />
                            <input
                                id="name"
                                type="text"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                placeholder="Ej. Juan Pérez"
                                disabled={isSubmitting}
                                className="w-full pl-10 pr-4 py-3 border border-border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition-all disabled:bg-background-alt bg-background text-text placeholder-text-subtle"
                            />
                        </div>
                    </div>

                    {/* Nombre de Usuario */}
                    <div>
                        <label htmlFor="username" className="block text-sm font-semibold text-text mb-2">
                            Nombre de Usuario
                        </label>
                        <div className="relative">
                            <LuUser className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-text-subtle" />
                            <input
                                id="username"
                                type="text"
                                value={username}
                                onChange={(e) => setUsername(e.target.value.toLowerCase().trim())}
                                placeholder="Ej. usuario123"
                                disabled={isSubmitting}
                                className="w-full pl-10 pr-4 py-3 border border-border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition-all disabled:bg-background-alt bg-background text-text placeholder-text-subtle"
                            />
                        </div>
                        <p className="mt-1.5 text-xs text-text-muted flex items-center gap-1">
                            <span className="inline-block w-1 h-1 rounded-full bg-text-subtle"></span>
                            Sin espacios, mínimo 3 caracteres
                        </p>
                    </div>

                    {/* Contraseña */}
                    <div>
                        <label htmlFor="password" className="block text-sm font-semibold text-text mb-2">
                            Contraseña
                        </label>
                        <div className="relative">
                            <LuLock className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-text-subtle" />
                            <input
                                id="password"
                                type={showPassword ? "text" : "password"}
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                placeholder="Mínimo 6 caracteres"
                                disabled={isSubmitting}
                                className="w-full pl-10 pr-12 py-3 border border-border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition-all disabled:bg-background-alt bg-background text-text placeholder-text-subtle"
                            />
                            <button
                                type="button"
                                onClick={() => setShowPassword(!showPassword)}
                                className="absolute right-3 top-1/2 -translate-y-1/2 p-1 text-text-subtle hover:text-text"
                            >
                                {showPassword ? <LuEyeOff className="h-5 w-5" /> : <LuEye className="h-5 w-5" />}
                            </button>
                        </div>
                    </div>

                    {/* Tipo de Usuario */}
                    <div>
                        <label htmlFor="role" className="block text-sm font-semibold text-text mb-2">
                            Tipo de Usuario
                        </label>
                        <div className="relative">
                            <LuUsers className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-text-subtle" />
                            <select
                                id="role"
                                value={role}
                                onChange={(e) => setRole(e.target.value)}
                                disabled={isSubmitting}
                                className="w-full pl-10 pr-4 py-3 border border-border rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition-all appearance-none bg-background disabled:bg-background-alt text-text"
                            >
                                <option value="USER">Usuario Estándar</option>
                                <option value="ADMIN">Administrador</option>
                            </select>
                        </div>
                        <p className="mt-1.5 text-xs text-text-muted">
                            Selecciona el nivel de permisos que tendrá la cuenta.
                        </p>
                    </div>
                </form>

                {/* Footer */}
                <div className="border-t border-border-subtle px-6 py-4 space-y-3 bg-background">
                    <button
                        type="submit"
                        form="create-user-form"
                        disabled={isSubmitting}
                        className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-primary text-primary-foreground rounded-lg hover:bg-primary-hover transition-colors font-semibold shadow-sm shadow-primary/20 disabled:opacity-50 disabled:cursor-not-allowed focus-ring"
                    >
                        {isSubmitting ? (
                            <>
                                <div className="animate-spin rounded-full h-5 w-5 border-2 border-primary-foreground border-t-transparent"></div>
                                Creando...
                            </>
                        ) : (
                            <>
                                <LuCheck className="h-5 w-5" />
                                Crear Usuario
                            </>
                        )}
                    </button>
                    <button
                        type="button"
                        onClick={onClose}
                        disabled={isSubmitting}
                        className="w-full px-4 py-3 text-text font-medium hover:bg-background-alt rounded-lg transition-colors focus-ring"
                    >
                        Cancelar
                    </button>
                </div>
            </div>
        </>
    );
}
