// SaisiePage.tsx - Mise à jour avec user.id
import React, { useState } from 'react';
import type { User, EvaluationRecord, HistoryEntry, FieldChange } from './types';
import { generateId } from './types';
import './styles.css';

interface SaisiePageProps {
    onSave: (record: EvaluationRecord) => void;
    onCancel: () => void;
    user: User;
}

const SaisiePage: React.FC<SaisiePageProps> = ({ onSave, onCancel, user }) => {
    const [formData, setFormData] = useState({
        nom: '',
        prenom: '',
        formation: '',
        autoEvaluation: '',
        dateAction: '',
        commentaireFormateur: '',
        evaluationTuteur: '',
        dateActionTuteur: '',
        commentaireRRE: ''
    });

    const [creationReason, setCreationReason] = useState('');
    const [reasonError, setReasonError] = useState(false);

    const handleChange = (field: string, value: string) => {
        setFormData(prev => ({ ...prev, [field]: value }));
    };

    const handleApprenantChange = (value: string) => {
        if (value) {
            const [nom, prenom, formation] = value.split('|');
            setFormData(prev => ({ ...prev, nom, prenom, formation }));
        } else {
            setFormData(prev => ({ ...prev, nom: '', prenom: '', formation: '' }));
        }
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        // Vérifier la raison
        if (!creationReason.trim()) {
            setReasonError(true);
            return;
        }

        const now = new Date().toISOString();
        const recordId = generateId();

        // Créer l'entrée d'historique initiale
        const initialHistory: HistoryEntry = {
            id: generateId(),
            timestamp: now,
            userId: user.id || user.email,
            userName: user.nomComplet || user.name,
            userRole: user.role as 'formateur' | 'rre',
            action: 'creation',
            reason: creationReason.trim(),
            changes: []
        };

        // Créer l'enregistrement complet
        const newRecord: EvaluationRecord = {
            ...formData,
            id: recordId,
            campus: user.campus || 'CGY',
            createdAt: now,
            createdBy: user.id || user.email,
            createdByName: user.nomComplet || user.name,
            history: [initialHistory],
            autoEvaluation: formData.autoEvaluation as 'OUI' | 'NON' | 'EN COURS',
            evaluationTuteur: formData.evaluationTuteur as 'OUI' | 'NON' | 'EN COURS'
        };

        onSave(newRecord);
    };

    const formations = ['BTS NDRC 1 JV', 'BTS MCO 1', 'BTS GPME 2', 'Bachelor RH', 'Master Management'];

    // Liste d'apprenants (normalement cela viendrait d'une API/base de données)
    const apprenants = [
        { nom: 'Dupont', prenom: 'Marie', formation: 'BTS NDRC 1 JV' },
        { nom: 'Martin', prenom: 'Pierre', formation: 'BTS MCO 1' },
        { nom: 'Bernard', prenom: 'Sophie', formation: 'BTS GPME 2' },
        { nom: 'Dubois', prenom: 'Lucas', formation: 'Bachelor RH' },
        { nom: 'Thomas', prenom: 'Emma', formation: 'Master Management' }
    ];

    const isFormateur = user.role === 'formateur';
    const isRRE = user.role === 'rre';

    return (
        <div className="page-container">
            <nav className="navbar">
                <div className="nav-left">
                    <button onClick={onCancel} className="back-button">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                            <path d="M15 10H5M8 13l-3-3 3-3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                    </button>
                    <div className="nav-info">
                        <span className="nav-title">Nouvelle Évaluation</span>
                        <span className="nav-subtitle">Saisie complète</span>
                    </div>
                </div>
                <div className="nav-right">
                    <div className="user-info">
                        <div className="user-text">
                            <span className="user-name">{user.nomComplet || user.name}</span>
                            <span className="user-role">
                                {isFormateur ? 'Formateur Référent' : 'Responsable RRE'}
                            </span>
                        </div>
                        <div className="user-avatar">{user.name[0].toUpperCase()}</div>
                    </div>
                </div>
            </nav>

            <main className="form-main">
                <form onSubmit={handleSubmit} className="form-container">
                    {/* Section Apprenant */}
                    <div className="form-section">
                        <div className="section-header">
                            <div className="section-icon student">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                                    <circle cx="12" cy="8" r="4" stroke="currentColor" strokeWidth="2" />
                                    <path d="M4 20c0-4 3.58-7 8-7s8 3 8 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                                </svg>
                            </div>
                            <div>
                                <h2 className="section-title">Informations Apprenant</h2>
                                <p className="section-subtitle">Identification et formation</p>
                            </div>
                        </div>

                        <div className="form-grid">
                            <div className="form-field full-width">
                                <label className="field-label">Sélectionner un apprenant *</label>
                                <select
                                    value={formData.nom && formData.prenom ? `${formData.nom}|${formData.prenom}|${formData.formation}` : ''}
                                    onChange={(e) => handleApprenantChange(e.target.value)}
                                    className="field-select"
                                    required
                                >
                                    <option value="">Choisir un apprenant...</option>
                                    {apprenants.map((app, idx) => (
                                        <option key={idx} value={`${app.nom}|${app.prenom}|${app.formation}`}>
                                            {app.prenom} {app.nom} - {app.formation}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            {formData.nom && (
                                <div className="form-field full-width">
                                    <div className="selected-info">
                                        <div className="info-row">
                                            <span className="info-label">Nom:</span>
                                            <span className="info-value">{formData.nom}</span>
                                        </div>
                                        <div className="info-row">
                                            <span className="info-label">Prénom:</span>
                                            <span className="info-value">{formData.prenom}</span>
                                        </div>
                                        <div className="info-row">
                                            <span className="info-label">Formation:</span>
                                            <span className="info-value">{formData.formation}</span>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Section Formateur */}
                    <div className={`form-section ${isRRE ? 'disabled-section' : ''}`}>
                        <div className="section-header">
                            <div className="section-icon formateur">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                                    <rect x="3" y="4" width="18" height="16" rx="2" stroke="currentColor" strokeWidth="2" />
                                    <path d="M8 10h8M8 14h5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                                </svg>
                            </div>
                            <div>
                                <h2 className="section-title">Saisie Formateur Référent</h2>
                                <p className="section-subtitle">Suivi et commentaires</p>
                                {isRRE && <span className="disabled-badge">Section réservée au formateur</span>}
                            </div>
                        </div>

                        <div className="form-grid">
                            <div className="form-field">
                                <label className="field-label">Auto-évaluation du jeune</label>
                                <div className="radio-group">
                                    {['OUI', 'NON', 'EN COURS'].map(opt => (
                                        <label key={opt} className="radio-label">
                                            <input
                                                type="radio"
                                                name="autoEvaluation"
                                                value={opt}
                                                checked={formData.autoEvaluation === opt}
                                                onChange={(e) => handleChange('autoEvaluation', e.target.value)}
                                                className="radio-input"
                                                disabled={isRRE}
                                            />
                                            <span className={`radio-custom ${formData.autoEvaluation === opt ? 'active' : ''} ${isRRE ? 'disabled' : ''}`}>
                                                {opt}
                                            </span>
                                        </label>
                                    ))}
                                </div>
                            </div>
                            <div className="form-field">
                                <label className="field-label">Date d'action</label>
                                <input
                                    type="date"
                                    value={formData.dateAction}
                                    onChange={(e) => handleChange('dateAction', e.target.value)}
                                    className="field-input"
                                    disabled={isRRE}
                                />
                            </div>
                            <div className="form-field full-width">
                                <label className="field-label">Commentaire du formateur</label>
                                <textarea
                                    value={formData.commentaireFormateur}
                                    onChange={(e) => handleChange('commentaireFormateur', e.target.value)}
                                    placeholder={isRRE ? "Réservé au formateur" : "Ajoutez vos observations..."}
                                    className="field-textarea"
                                    rows={4}
                                    disabled={isRRE}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Section RRE */}
                    <div className={`form-section ${isFormateur ? 'disabled-section' : ''}`}>
                        <div className="section-header">
                            <div className="section-icon rre">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                                    <path d="M9 12l2 2 4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                    <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2" />
                                </svg>
                            </div>
                            <div>
                                <h2 className="section-title">Saisie Responsable RRE</h2>
                                <p className="section-subtitle">Validation tuteur</p>
                                {isFormateur && <span className="disabled-badge">Section réservée au RRE</span>}
                            </div>
                        </div>

                        <div className="form-grid">
                            <div className="form-field">
                                <label className="field-label">Évaluation par le tuteur</label>
                                <div className="radio-group">
                                    {['OUI', 'NON', 'EN COURS'].map(opt => (
                                        <label key={opt} className="radio-label">
                                            <input
                                                type="radio"
                                                name="evaluationTuteur"
                                                value={opt}
                                                checked={formData.evaluationTuteur === opt}
                                                onChange={(e) => handleChange('evaluationTuteur', e.target.value)}
                                                className="radio-input"
                                                disabled={isFormateur}
                                            />
                                            <span className={`radio-custom ${formData.evaluationTuteur === opt ? 'active' : ''} ${isFormateur ? 'disabled' : ''}`}>
                                                {opt}
                                            </span>
                                        </label>
                                    ))}
                                </div>
                            </div>
                            <div className="form-field">
                                <label className="field-label">Date d'action</label>
                                <input
                                    type="date"
                                    value={formData.dateActionTuteur}
                                    onChange={(e) => handleChange('dateActionTuteur', e.target.value)}
                                    className="field-input"
                                    disabled={isFormateur}
                                />
                            </div>
                            <div className="form-field full-width">
                                <label className="field-label">Commentaire RRE</label>
                                <textarea
                                    value={formData.commentaireRRE}
                                    onChange={(e) => handleChange('commentaireRRE', e.target.value)}
                                    placeholder={isFormateur ? "Réservé au RRE" : "Ajoutez vos observations..."}
                                    className="field-textarea"
                                    rows={4}
                                    disabled={isFormateur}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Raison de création */}
                    <div className="detail-section reason-section">
                        <h3 className="detail-section-title required-title">
                            <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                                <path d="M9 2v8M9 14h.01" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                            </svg>
                            Contexte de création
                            <span className="required-asterisk">*</span>
                        </h3>
                        <div className="form-field full-width">
                            <textarea
                                value={creationReason}
                                onChange={(e) => {
                                    setCreationReason(e.target.value);
                                    if (e.target.value.trim()) setReasonError(false);
                                }}
                                className={`field-textarea reason-textarea ${reasonError ? 'error' : ''}`}
                                rows={3}
                                placeholder="Décrivez le contexte de cette création (obligatoire pour l'audit)..."
                            />
                            {reasonError && (
                                <div className="field-error">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                                        <circle cx="8" cy="8" r="7" stroke="currentColor" strokeWidth="1.5" />
                                        <path d="M8 5v3M8 11h.01" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                    </svg>
                                    Le contexte de création est obligatoire pour la traçabilité
                                </div>
                            )}
                        </div>
                    </div>

                    <div className="form-actions">
                        <button type="button" onClick={onCancel} className="cancel-button">
                            Annuler
                        </button>
                        <button type="submit" className="submit-button">
                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                                <path d="M16 5L7 14 3 10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                            </svg>
                            Enregistrer l'évaluation
                        </button>
                    </div>
                </form>
            </main>
        </div>
    );
};

export default SaisiePage;