'use client';
export const dynamic = 'force-dynamic';


import React, { useState, useEffect } from 'react';
import { Card } from 'primereact/card';
import { InputText } from 'primereact/inputtext';
import { InputTextarea } from 'primereact/inputtextarea';
import { Dropdown } from 'primereact/dropdown';
import { Calendar } from 'primereact/calendar';
import { InputNumber } from 'primereact/inputnumber';
import { Button } from 'primereact/button';
import { Toolbar } from 'primereact/toolbar';
import { Message } from 'primereact/message';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Tag } from 'primereact/tag';
import { useRouter } from 'next/navigation';
import { apiClient } from '../../../../services/api-client';

interface NouvelleMaintenance {
    materielId: number;
    typeMaintenance: 'PREVENTIVE' | 'CORRECTIVE' | 'PLANIFIEE' | 'URGENTE';
    priorite: 'BASSE' | 'NORMALE' | 'HAUTE' | 'CRITIQUE';
    datePlanifiee: Date | null;
    technicienId?: number;
    description: string;
    problemeSignale?: string;
    coutEstime?: number;
    dureeEstimee: number;
    observations?: string;
}

interface Materiel {
    id: number;
    nom: string;
    type: string;
    marque: string;
    modele: string;
    statut: string;
    derniereMaintenance?: string;
    prochaineMaintenance?: string;
}

interface Technicien {
    id: number;
    nom: string;
    prenom: string;
    specialites: string[];
    disponible: boolean;
}

const NouvellMaintenancePage = () => {
    const [maintenance, setMaintenance] = useState<NouvelleMaintenance>({
        materielId: 0,
        typeMaintenance: 'PREVENTIVE',
        priorite: 'NORMALE',
        datePlanifiee: null,
        description: '',
        dureeEstimee: 2
    });
    const [materiels, setMateriels] = useState<Materiel[]>([]);
    const [techniciens, setTechniciens] = useState<Technicien[]>([]);
    const [loading, setLoading] = useState(false);
    const [errors, setErrors] = useState<{ [key: string]: string }>({});
    const router = useRouter();

    const typeOptions = [
        { label: 'Préventive', value: 'PREVENTIVE' },
        { label: 'Corrective', value: 'CORRECTIVE' },
        { label: 'Planifiée', value: 'PLANIFIEE' },
        { label: 'Urgente', value: 'URGENTE' }
    ];

    const prioriteOptions = [
        { label: 'Basse', value: 'BASSE' },
        { label: 'Normale', value: 'NORMALE' },
        { label: 'Haute', value: 'HAUTE' },
        { label: 'Critique', value: 'CRITIQUE' }
    ];

    useEffect(() => {
        loadMateriels();
        loadTechniciens();
    }, []);

    const loadMateriels = async () => {
        try {
            console.log('🔄 Chargement des matériels...');
            const response = await apiClient.get('/api/materiels');
            console.log('✅ Matériels chargés:', response.data);
            setMateriels(response.data || []);
        } catch (error) {
            console.error('❌ Erreur lors du chargement des matériels:', error);
        }
    };

    const loadTechniciens = async () => {
        try {
            console.log('🔄 Chargement des techniciens...');
            const response = await apiClient.get('/api/employes/techniciens');
            console.log('✅ Techniciens chargés:', response.data);
            setTechniciens(response.data || []);
        } catch (error) {
            console.error('❌ Erreur lors du chargement des techniciens:', error);
        }
    };

    const validateForm = () => {
        const newErrors: { [key: string]: string } = {};

        if (!maintenance.materielId) {
            newErrors.materielId = 'Le matériel est requis';
        }

        if (!maintenance.description.trim()) {
            newErrors.description = 'La description est requise';
        }

        if (!maintenance.datePlanifiee) {
            newErrors.datePlanifiee = 'La date planifiée est requise';
        }

        if (maintenance.dureeEstimee <= 0) {
            newErrors.dureeEstimee = 'La durée estimée doit être positive';
        }

        if (maintenance.typeMaintenance === 'CORRECTIVE' && !maintenance.problemeSignale?.trim()) {
            newErrors.problemeSignale = 'Le problème signalé est requis pour une maintenance corrective';
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

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

        if (!validateForm()) {
            return;
        }

        try {
            setLoading(true);
            console.log('🔄 Création de la maintenance...', maintenance);

            const maintenanceData = {
                ...maintenance,
                datePlanifiee: maintenance.datePlanifiee?.toISOString().split('T')[0]
            };

            const response = await apiClient.post('/api/maintenances', maintenanceData);
            console.log('✅ Maintenance créée avec succès:', response.data);

            router.push('/maintenance');
        } catch (error) {
            console.error('❌ Erreur lors de la création:', error);
        } finally {
            setLoading(false);
        }
    };

    const materielOptionTemplate = (option: Materiel) => {
        return (
            <div className="flex align-items-center gap-2">
                <div>
                    <div className="font-medium">{option.nom}</div>
                    <div className="text-sm text-500">{option.type} - {option.marque} {option.modele}</div>
                </div>
            </div>
        );
    };

    const technicienOptionTemplate = (option: Technicien) => {
        return (
            <div className="flex align-items-center gap-2">
                <div>
                    <div className="font-medium">{option.prenom} {option.nom}</div>
                    <div className="text-sm text-500">
                        {option.specialites?.join(', ')}
                        {option.disponible ? (
                            <Tag value="Disponible" severity="success" className="ml-2 p-tag-sm" />
                        ) : (
                            <Tag value="Occupé" severity="warning" className="ml-2 p-tag-sm" />
                        )}
                    </div>
                </div>
            </div>
        );
    };

    const getStatutColor = (statut: string) => {
        switch (statut) {
            case 'DISPONIBLE': return 'success';
            case 'EN_UTILISATION': return 'warning';
            case 'EN_MAINTENANCE': return 'danger';
            case 'HORS_SERVICE': return 'danger';
            default: return 'secondary';
        }
    };

    const statutBodyTemplate = (rowData: Materiel) => {
        return <Tag value={rowData.statut} severity={getStatutColor(rowData.statut)} />;
    };

    const maintenanceBodyTemplate = (rowData: Materiel) => {
        return (
            <div className="flex flex-column gap-1">
                {rowData.derniereMaintenance && (
                    <span className="text-sm">
                        Dernière: {new Date(rowData.derniereMaintenance).toLocaleDateString('fr-FR')}
                    </span>
                )}
                {rowData.prochaineMaintenance && (
                    <span className="text-sm text-orange-500">
                        Prochaine: {new Date(rowData.prochaineMaintenance).toLocaleDateString('fr-FR')}
                    </span>
                )}
            </div>
        );
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="flex flex-wrap gap-2">
                <Button
                    label="Retour à la maintenance"
                    icon="pi pi-arrow-left"
                    className="p-button-outlined"
                    onClick={() => router.push('/maintenance')}
                />
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <div className="flex gap-2">
                <Button
                    label="Annuler"
                    icon="pi pi-times"
                    className="p-button-outlined"
                    onClick={() => router.push('/maintenance')}
                />
                <Button
                    label="Créer la maintenance"
                    icon="pi pi-check"
                    className="p-button-success"
                    loading={loading}
                    onClick={handleSubmit}
                />
            </div>
        );
    };

    return (
        <div className="grid">
            <div className="col-12">
                <Toolbar 
                    className="mb-4" 
                    left={leftToolbarTemplate} 
                    right={rightToolbarTemplate}
                />
            </div>

            <div className="col-12 lg:col-8">
                <Card title="Nouvelle Maintenance">
                    <form onSubmit={handleSubmit} className="p-fluid">
                        <div className="grid">
                            <div className="col-12 md:col-6">
                                <div className="field">
                                    <label htmlFor="materiel" className="font-medium">
                                        Matériel *
                                    </label>
                                    <Dropdown
                                        id="materiel"
                                        value={maintenance.materielId}
                                        options={materiels}
                                        onChange={(e) => setMaintenance({ ...maintenance, materielId: e.value })}
                                        optionLabel="nom"
                                        optionValue="id"
                                        placeholder="Sélectionner un matériel"
                                        itemTemplate={materielOptionTemplate}
                                        className={errors.materielId ? 'p-invalid' : ''}
                                        filter
                                    />
                                    {errors.materielId && <small className="p-error">{errors.materielId}</small>}
                                </div>
                            </div>

                            <div className="col-12 md:col-6">
                                <div className="field">
                                    <label htmlFor="technicien" className="font-medium">
                                        Technicien assigné
                                    </label>
                                    <Dropdown
                                        id="technicien"
                                        value={maintenance.technicienId}
                                        options={techniciens}
                                        onChange={(e) => setMaintenance({ ...maintenance, technicienId: e.value })}
                                        optionLabel="nom"
                                        optionValue="id"
                                        placeholder="Sélectionner un technicien"
                                        itemTemplate={technicienOptionTemplate}
                                        filter
                                        showClear
                                    />
                                </div>
                            </div>

                            <div className="col-12 md:col-4">
                                <div className="field">
                                    <label htmlFor="type" className="font-medium">
                                        Type de maintenance *
                                    </label>
                                    <Dropdown
                                        id="type"
                                        value={maintenance.typeMaintenance}
                                        options={typeOptions}
                                        onChange={(e) => setMaintenance({ ...maintenance, typeMaintenance: e.value })}
                                        placeholder="Sélectionner le type"
                                    />
                                </div>
                            </div>

                            <div className="col-12 md:col-4">
                                <div className="field">
                                    <label htmlFor="priorite" className="font-medium">
                                        Priorité *
                                    </label>
                                    <Dropdown
                                        id="priorite"
                                        value={maintenance.priorite}
                                        options={prioriteOptions}
                                        onChange={(e) => setMaintenance({ ...maintenance, priorite: e.value })}
                                        placeholder="Sélectionner la priorité"
                                    />
                                </div>
                            </div>

                            <div className="col-12 md:col-4">
                                <div className="field">
                                    <label htmlFor="datePlanifiee" className="font-medium">
                                        Date planifiée *
                                    </label>
                                    <Calendar
                                        id="datePlanifiee"
                                        value={maintenance.datePlanifiee}
                                        onChange={(e) => setMaintenance({ ...maintenance, datePlanifiee: e.value as Date })}
                                        showIcon
                                        dateFormat="dd/mm/yy"
                                        placeholder="Sélectionner une date"
                                        className={errors.datePlanifiee ? 'p-invalid' : ''}
                                        minDate={new Date()}
                                    />
                                    {errors.datePlanifiee && <small className="p-error">{errors.datePlanifiee}</small>}
                                </div>
                            </div>

                            <div className="col-12">
                                <div className="field">
                                    <label htmlFor="description" className="font-medium">
                                        Description *
                                    </label>
                                    <InputTextarea
                                        id="description"
                                        value={maintenance.description}
                                        onChange={(e) => setMaintenance({ ...maintenance, description: e.target.value })}
                                        rows={3}
                                        placeholder="Description détaillée de la maintenance à effectuer..."
                                        className={errors.description ? 'p-invalid' : ''}
                                    />
                                    {errors.description && <small className="p-error">{errors.description}</small>}
                                </div>
                            </div>

                            {maintenance.typeMaintenance === 'CORRECTIVE' && (
                                <div className="col-12">
                                    <div className="field">
                                        <label htmlFor="probleme" className="font-medium">
                                            Problème signalé *
                                        </label>
                                        <InputTextarea
                                            id="probleme"
                                            value={maintenance.problemeSignale || ''}
                                            onChange={(e) => setMaintenance({ ...maintenance, problemeSignale: e.target.value })}
                                            rows={2}
                                            placeholder="Description du problème rencontré..."
                                            className={errors.problemeSignale ? 'p-invalid' : ''}
                                        />
                                        {errors.problemeSignale && <small className="p-error">{errors.problemeSignale}</small>}
                                    </div>
                                </div>
                            )}

                            <div className="col-12 md:col-6">
                                <div className="field">
                                    <label htmlFor="duree" className="font-medium">
                                        Durée estimée (heures) *
                                    </label>
                                    <InputNumber
                                        id="duree"
                                        value={maintenance.dureeEstimee}
                                        onValueChange={(e) => setMaintenance({ ...maintenance, dureeEstimee: e.value || 0 })}
                                        min={0.5}
                                        max={100}
                                        step={0.5}
                                        suffix=" h"
                                        className={errors.dureeEstimee ? 'p-invalid' : ''}
                                    />
                                    {errors.dureeEstimee && <small className="p-error">{errors.dureeEstimee}</small>}
                                </div>
                            </div>

                            <div className="col-12 md:col-6">
                                <div className="field">
                                    <label htmlFor="cout" className="font-medium">
                                        Coût estimé (€)
                                    </label>
                                    <InputNumber
                                        id="cout"
                                        value={maintenance.coutEstime}
                                        onValueChange={(e) => setMaintenance({ ...maintenance, coutEstime: e.value || undefined })}
                                        min={0}
                                        mode="currency"
                                        currency="EUR"
                                        locale="fr-FR"
                                    />
                                </div>
                            </div>

                            <div className="col-12">
                                <div className="field">
                                    <label htmlFor="observations" className="font-medium">
                                        Observations
                                    </label>
                                    <InputTextarea
                                        id="observations"
                                        value={maintenance.observations || ''}
                                        onChange={(e) => setMaintenance({ ...maintenance, observations: e.target.value })}
                                        rows={2}
                                        placeholder="Observations particulières..."
                                    />
                                </div>
                            </div>
                        </div>
                    </form>
                </Card>
            </div>

            <div className="col-12 lg:col-4">
                <Card title="Matériels disponibles" className="mb-4">
                    <DataTable 
                        value={materiels.filter(m => m.statut !== 'HORS_SERVICE')} 
                        responsiveLayout="scroll"
                        paginator
                        rows={5}
                        emptyMessage="Aucun matériel disponible"
                    >
                        <Column field="nom" header="Nom" />
                        <Column field="type" header="Type" />
                        <Column field="statut" header="Statut" body={statutBodyTemplate} />
                        <Column field="derniereMaintenance" header="Maintenance" body={maintenanceBodyTemplate} />
                    </DataTable>
                </Card>

                <Card title="Conseils">
                    <div className="text-sm">
                        <p className="mb-2">
                            <i className="pi pi-info-circle text-blue-500 mr-2" />
                            Planifiez les maintenances préventives en avance.
                        </p>
                        <p className="mb-2">
                            <i className="pi pi-exclamation-triangle text-orange-500 mr-2" />
                            Les maintenances urgentes ont la priorité absolue.
                        </p>
                        <p className="mb-2">
                            <i className="pi pi-user text-green-500 mr-2" />
                            Assignez un technicien qualifié pour le type de matériel.
                        </p>
                        <p>
                            <i className="pi pi-euro text-purple-500 mr-2" />
                            Estimez le coût pour le suivi budgétaire.
                        </p>
                    </div>
                </Card>
            </div>
        </div>
    );
};

export default NouvellMaintenancePage;
