'use client';

import { useState, useEffect } from 'react';
import { Input, TagInput, Modal, Badge } from '@zen/core/shared/components';
import { useToast } from '@zen/core/toast';

const UserCreateModal = ({ isOpen, onClose, onSaved }) => {
    const toast = useToast();
    const [saving, setSaving] = useState(false);
    const [allRoles, setAllRoles] = useState([]);
    const [selectedRoleIds, setSelectedRoleIds] = useState([]);
    const [formData, setFormData] = useState({ name: '', email: '', password: '' });
    const [errors, setErrors] = useState({});
    const [error, setError] = useState('');

    useEffect(() => {
        if (!isOpen) return;
        setFormData({ name: '', email: '', password: '' });
        setSelectedRoleIds([]);
        setErrors({});
        setError('');
        fetchRoles();
    }, [isOpen]);

    const fetchRoles = async () => {
        try {
            const res = await fetch('/zen/api/roles', { credentials: 'include' });
            const data = await res.json();
            setAllRoles(data.roles || []);
        } catch {
            toast.error('Impossible de charger les rôles');
        }
    };

    const handleInputChange = (field, value) => {
        setFormData(prev => ({ ...prev, [field]: value }));
        if (errors[field]) setErrors(prev => ({ ...prev, [field]: null }));
        if (error) setError('');
    };

    const validate = () => {
        const newErrors = {};
        if (!formData.name.trim()) newErrors.name = 'Le nom est requis';
        if (!formData.email.trim()) newErrors.email = 'Le courriel est requis';
        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const handleSubmit = async () => {
        if (!validate()) return;
        setSaving(true);
        setError('');
        try {
            const res = await fetch('/zen/api/users', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({
                    name: formData.name.trim(),
                    email: formData.email.trim(),
                    password: formData.password || undefined,
                    roleIds: selectedRoleIds,
                }),
            });
            const data = await res.json();
            if (!res.ok) {
                setError(data.message || data.error || "Impossible de créer l'utilisateur");
                return;
            }
            if (data.invited) {
                toast.success('Utilisateur créé — invitation envoyée par courriel');
            } else {
                toast.success('Utilisateur créé');
            }
            onSaved?.();
            onClose();
        } catch {
            setError("Impossible de créer l'utilisateur");
        } finally {
            setSaving(false);
        }
    };

    const roleOptions = allRoles.map(r => ({
        value: r.id,
        label: r.name,
        color: r.color || '#6b7280',
        description: r.description || undefined,
    }));

    return (
        <Modal
            isOpen={isOpen}
            onClose={onClose}
            title="Nouvel utilisateur"
            onSubmit={handleSubmit}
            submitLabel="Créer"
            loading={saving}
            size="md"
        >
            <div className="flex flex-col gap-4">
                {error && (
                    <div className="p-3 bg-red-50 border border-red-200 rounded-lg dark:bg-red-500/10 dark:border-red-500/20">
                        <div className="flex items-center gap-2">
                            <div className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0" />
                            <span className="text-xs text-red-700 dark:text-red-400">{error}</span>
                        </div>
                    </div>
                )}

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <Input
                        label="Nom complet *"
                        value={formData.name}
                        onChange={(value) => handleInputChange('name', value)}
                        placeholder="Prénom Nom"
                        error={errors.name}
                    />
                    <Input
                        label="Courriel *"
                        type="email"
                        value={formData.email}
                        onChange={(value) => handleInputChange('email', value)}
                        placeholder="utilisateur@exemple.com"
                        error={errors.email}
                    />
                </div>

                <TagInput
                    label="Rôles"
                    options={roleOptions}
                    value={selectedRoleIds}
                    onChange={setSelectedRoleIds}
                    placeholder="Rechercher un rôle..."
                    renderTag={(opt, onRemove) => (
                        <Badge key={opt.value} color={opt.color} dot onRemove={onRemove}>{opt.label}</Badge>
                    )}
                />

                <div className="flex flex-col gap-1">
                    <Input
                        label="Mot de passe"
                        type="password"
                        value={formData.password}
                        onChange={(value) => handleInputChange('password', value)}
                        placeholder="Laisser vide pour envoyer une invitation"
                    />
                    <p className="text-xs text-neutral-500 dark:text-neutral-400">
                        Si vide, un courriel d'invitation sera envoyé pour que l'utilisateur crée son mot de passe.
                    </p>
                </div>
            </div>
        </Modal>
    );
};

export default UserCreateModal;
