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


import React, { useState, useEffect } from 'react';
import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Tag } from 'primereact/tag';
import { Badge } from 'primereact/badge';
import { Toolbar } from 'primereact/toolbar';
import { ProgressBar } from 'primereact/progressbar';
import { Calendar } from 'primereact/calendar';
import { Dropdown } from 'primereact/dropdown';
import { InputNumber } from 'primereact/inputnumber';
import { Dialog } from 'primereact/dialog';
import { useRouter } from 'next/navigation';
import { apiClient } from '../../../../services/api-client';

interface PlanificationMaintenance {
    materielId: number;
    materielNom: string;
    materielType: string;
    derniereMaintenance?: string;
    prochaineMaintenance: string;
    frequenceMaintenance: number; // en jours
    heuresUtilisation: number;
    seuilMaintenanceHeures: number;
    pourcentageUsure: number;
    prioriteRecommandee: 'BASSE' | 'NORMALE' | 'HAUTE' | 'CRITIQUE';
    typeMaintenanceRecommande: 'PREVENTIVE' | 'CORRECTIVE';
    coutEstime: number;
    dureeEstimee: number;
    technicienRecommande?: {
        id: number;
        nom: string;
        specialites: string[];
        disponibilite: boolean;
    };
    risqueDefaillance: number; // pourcentage
    impactArret: 'FAIBLE' | 'MOYEN' | 'ELEVE' | 'CRITIQUE';
}

interface ConfigurationPlanification {
    periodeAnalyse: number; // en mois
    seuilUrgence: number; // pourcentage d'usure
    optimiserCouts: boolean;
    optimiserDisponibilite: boolean;
    prendreCompteMeteo: boolean;
    grouperMaintenances: boolean;
}

const PlanificationMaintenancePage = () => {
    const [planifications, setPlanifications] = useState<PlanificationMaintenance[]>([]);
    const [loading, setLoading] = useState(true);
    const [configuration, setConfiguration] = useState<ConfigurationPlanification>({
        periodeAnalyse: 6,
        seuilUrgence: 80,
        optimiserCouts: true,
        optimiserDisponibilite: true,
        prendreCompteMeteo: false,
        grouperMaintenances: true
    });
    const [configDialog, setConfigDialog] = useState(false);
    const [selectedMateriels, setSelectedMateriels] = useState<PlanificationMaintenance[]>([]);
    const [dateDebutPlanification, setDateDebutPlanification] = useState<Date>(new Date());
    const [dateFinPlanification, setDateFinPlanification] = useState<Date>(
        new Date(Date.now() + 6 * 30 * 24 * 60 * 60 * 1000) // +6 mois
    );
    const router = useRouter();

    useEffect(() => {
        loadPlanificationMaintenance();
    }, [configuration]);

    const loadPlanificationMaintenance = async () => {
        try {
            setLoading(true);
            console.log('🔄 Chargement de la planification maintenance...');
            
            const params = new URLSearchParams();
            params.append('periodeAnalyse', configuration.periodeAnalyse.toString());
            params.append('seuilUrgence', configuration.seuilUrgence.toString());
            params.append('optimiserCouts', configuration.optimiserCouts.toString());
            params.append('optimiserDisponibilite', configuration.optimiserDisponibilite.toString());
            params.append('grouper', configuration.grouperMaintenances.toString());

            const response = await apiClient.get(`/api/maintenances/planification-automatique?${params.toString()}`);
            console.log('✅ Planification chargée:', response.data);
            setPlanifications(response.data || []);
        } catch (error) {
            console.error('❌ Erreur lors du chargement de la planification:', error);
            setPlanifications([]);
        } finally {
            setLoading(false);
        }
    };

    const genererPlanningOptimal = async () => {
        try {
            console.log('🔄 Génération du planning optimal...');
            
            const params = {
                materiels: selectedMateriels.map(m => m.materielId),
                dateDebut: dateDebutPlanification.toISOString().split('T')[0],
                dateFin: dateFinPlanification.toISOString().split('T')[0],
                configuration
            };

            const response = await apiClient.post('/api/maintenances/generer-planning-optimal', params);
            console.log('✅ Planning optimal généré:', response.data);
            
            // Rediriger vers le calendrier avec le nouveau planning
            router.push('/maintenance/calendrier?planning=optimal');
        } catch (error) {
            console.error('❌ Erreur lors de la génération du planning:', error);
        }
    };

    const planifierMaintenanceAutomatique = async (materielId: number) => {
        try {
            await apiClient.post(`/api/maintenances/planifier-automatique/${materielId}`);
            console.log('✅ Maintenance planifiée automatiquement');
            loadPlanificationMaintenance();
        } catch (error) {
            console.error('❌ Erreur lors de la planification automatique:', error);
        }
    };

    const planifierToutesMaintenances = async () => {
        try {
            console.log('🔄 Planification de toutes les maintenances...');
            await apiClient.post('/api/maintenances/planifier-toutes-automatique', configuration);
            console.log('✅ Toutes les maintenances planifiées');
            loadPlanificationMaintenance();
        } catch (error) {
            console.error('❌ Erreur lors de la planification globale:', error);
        }
    };

    const materielBodyTemplate = (rowData: PlanificationMaintenance) => {
        return (
            <div className="flex flex-column gap-1">
                <span className="font-medium">{rowData.materielNom}</span>
                <span className="text-sm text-500">{rowData.materielType}</span>
            </div>
        );
    };

    const usureBodyTemplate = (rowData: PlanificationMaintenance) => {
        const couleur = rowData.pourcentageUsure > 80 ? 'danger' : 
                      rowData.pourcentageUsure > 60 ? 'warning' : 'success';
        
        return (
            <div className="flex flex-column gap-2">
                <div className="flex align-items-center gap-2">
                    <ProgressBar 
                        value={rowData.pourcentageUsure} 
                        className="flex-1"
                        color={couleur === 'danger' ? '#f87171' : couleur === 'warning' ? '#fbbf24' : '#10b981'}
                    />
                    <span className="text-sm font-medium">{rowData.pourcentageUsure}%</span>
                </div>
                <div className="text-xs text-500">
                    {rowData.heuresUtilisation}h / {rowData.seuilMaintenanceHeures}h
                </div>
            </div>
        );
    };

    const risqueBodyTemplate = (rowData: PlanificationMaintenance) => {
        const couleur = rowData.risqueDefaillance > 70 ? 'danger' : 
                      rowData.risqueDefaillance > 40 ? 'warning' : 'success';
        
        return (
            <div className="flex align-items-center gap-2">
                <ProgressBar 
                    value={rowData.risqueDefaillance} 
                    className="flex-1"
                    color={couleur === 'danger' ? '#f87171' : couleur === 'warning' ? '#fbbf24' : '#10b981'}
                />
                <span className="text-sm font-medium">{rowData.risqueDefaillance}%</span>
            </div>
        );
    };

    const prioriteBodyTemplate = (rowData: PlanificationMaintenance) => {
        const getPrioriteSeverity = (priorite: string) => {
            switch (priorite) {
                case 'BASSE': return 'info';
                case 'NORMALE': return 'success';
                case 'HAUTE': return 'warning';
                case 'CRITIQUE': return 'danger';
                default: return 'secondary';
            }
        };

        return <Tag value={rowData.prioriteRecommandee} severity={getPrioriteSeverity(rowData.prioriteRecommandee)} />;
    };

    const impactBodyTemplate = (rowData: PlanificationMaintenance) => {
        const getImpactSeverity = (impact: string) => {
            switch (impact) {
                case 'FAIBLE': return 'info';
                case 'MOYEN': return 'warning';
                case 'ELEVE': return 'danger';
                case 'CRITIQUE': return 'danger';
                default: return 'secondary';
            }
        };

        return <Tag value={rowData.impactArret} severity={getImpactSeverity(rowData.impactArret)} />;
    };

    const dateBodyTemplate = (rowData: PlanificationMaintenance) => {
        const prochaineMaintenance = new Date(rowData.prochaineMaintenance);
        const joursRestants = Math.ceil((prochaineMaintenance.getTime() - new Date().getTime()) / (1000 * 3600 * 24));
        const isUrgent = joursRestants <= 7;
        const isRetard = joursRestants < 0;

        return (
            <div className="flex flex-column gap-1">
                <span className={`font-medium ${isRetard ? 'text-red-500' : isUrgent ? 'text-orange-500' : ''}`}>
                    {prochaineMaintenance.toLocaleDateString('fr-FR')}
                </span>
                <span className="text-xs text-500">
                    {isRetard ? `Retard: ${Math.abs(joursRestants)} j` : 
                     isUrgent ? `Urgent: ${joursRestants} j` : 
                     `Dans ${joursRestants} jours`}
                </span>
                {rowData.derniereMaintenance && (
                    <span className="text-xs text-500">
                        Dernière: {new Date(rowData.derniereMaintenance).toLocaleDateString('fr-FR')}
                    </span>
                )}
            </div>
        );
    };

    const technicienBodyTemplate = (rowData: PlanificationMaintenance) => {
        if (rowData.technicienRecommande) {
            return (
                <div className="flex flex-column gap-1">
                    <span className="font-medium">{rowData.technicienRecommande.nom}</span>
                    <div className="flex gap-1">
                        {rowData.technicienRecommande.specialites.slice(0, 2).map((spec, index) => (
                            <Tag key={index} value={spec} className="p-tag-sm" />
                        ))}
                    </div>
                    {rowData.technicienRecommande.disponibilite ? (
                        <Tag value="Disponible" severity="success" className="p-tag-sm" />
                    ) : (
                        <Tag value="Occupé" severity="warning" className="p-tag-sm" />
                    )}
                </div>
            );
        }
        return <span className="text-500">À assigner</span>;
    };

    const coutBodyTemplate = (rowData: PlanificationMaintenance) => {
        return (
            <div className="flex flex-column gap-1">
                <span className="font-medium">{rowData.coutEstime.toLocaleString('fr-FR')} €</span>
                <span className="text-sm text-500">{rowData.dureeEstimee}h estimées</span>
            </div>
        );
    };

    const actionBodyTemplate = (rowData: PlanificationMaintenance) => {
        return (
            <div className="flex gap-2">
                <Button
                    icon="pi pi-calendar-plus"
                    className="p-button-rounded p-button-success p-button-sm"
                    onClick={() => planifierMaintenanceAutomatique(rowData.materielId)}
                    tooltip="Planifier automatiquement"
                />
                <Button
                    icon="pi pi-pencil"
                    className="p-button-rounded p-button-info p-button-sm"
                    onClick={() => router.push(`/maintenance/nouveau?materielId=${rowData.materielId}&type=${rowData.typeMaintenanceRecommande}`)}
                    tooltip="Planifier manuellement"
                />
                <Button
                    icon="pi pi-eye"
                    className="p-button-rounded p-button-secondary p-button-sm"
                    onClick={() => router.push(`/materiels/${rowData.materielId}`)}
                    tooltip="Voir matériel"
                />
            </div>
        );
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="flex flex-wrap gap-2">
                <Button
                    label="Retour Maintenance"
                    icon="pi pi-arrow-left"
                    className="p-button-outlined"
                    onClick={() => router.push('/maintenance')}
                />
                <Button
                    label="Planifier Toutes"
                    icon="pi pi-calendar-plus"
                    className="p-button-success"
                    onClick={planifierToutesMaintenances}
                />
                <Button
                    label="Planning Optimal"
                    icon="pi pi-cog"
                    className="p-button-info"
                    onClick={genererPlanningOptimal}
                    disabled={selectedMateriels.length === 0}
                />
                <Button
                    label="Configuration"
                    icon="pi pi-sliders-h"
                    className="p-button-secondary"
                    onClick={() => setConfigDialog(true)}
                />
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <div className="flex gap-2">
                <Button
                    label="Exporter"
                    icon="pi pi-download"
                    className="p-button-outlined"
                    onClick={() => router.push('/maintenance/export-planification')}
                />
                <Button
                    icon="pi pi-refresh"
                    className="p-button-outlined"
                    onClick={loadPlanificationMaintenance}
                    tooltip="Actualiser"
                />
            </div>
        );
    };

    const header = (
        <div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h2 className="m-0">Planification Automatique de Maintenance</h2>
            <div className="flex gap-2 mt-2 md:mt-0">
                <Badge value={planifications.filter(p => p.prioriteRecommandee === 'CRITIQUE').length} severity="danger" />
                <span>Critiques</span>
                <Badge value={planifications.filter(p => p.pourcentageUsure > 80).length} severity="warning" />
                <span>Usure élevée</span>
                <Badge value={planifications.filter(p => p.risqueDefaillance > 70).length} severity="info" />
                <span>Risque élevé</span>
            </div>
        </div>
    );

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

            {/* Paramètres de planification */}
            <div className="col-12">
                <Card title="Paramètres de Planification" className="mb-4">
                    <div className="grid">
                        <div className="col-12 md:col-3">
                            <label className="font-medium mb-2 block">Période d'analyse</label>
                            <Dropdown
                                value={configuration.periodeAnalyse}
                                options={[
                                    { label: '3 mois', value: 3 },
                                    { label: '6 mois', value: 6 },
                                    { label: '12 mois', value: 12 },
                                    { label: '24 mois', value: 24 }
                                ]}
                                onChange={(e) => setConfiguration({ ...configuration, periodeAnalyse: e.value })}
                            />
                        </div>
                        <div className="col-12 md:col-3">
                            <label className="font-medium mb-2 block">Date début planning</label>
                            <Calendar
                                value={dateDebutPlanification}
                                onChange={(e) => setDateDebutPlanification(e.value as Date)}
                                showIcon
                                dateFormat="dd/mm/yy"
                            />
                        </div>
                        <div className="col-12 md:col-3">
                            <label className="font-medium mb-2 block">Date fin planning</label>
                            <Calendar
                                value={dateFinPlanification}
                                onChange={(e) => setDateFinPlanification(e.value as Date)}
                                showIcon
                                dateFormat="dd/mm/yy"
                            />
                        </div>
                        <div className="col-12 md:col-3">
                            <label className="font-medium mb-2 block">Seuil urgence (%)</label>
                            <InputNumber
                                value={configuration.seuilUrgence}
                                onValueChange={(e) => setConfiguration({ ...configuration, seuilUrgence: e.value || 80 })}
                                min={50}
                                max={95}
                                suffix="%"
                            />
                        </div>
                    </div>
                </Card>
            </div>

            {/* Tableau de planification */}
            <div className="col-12">
                <Card>
                    <DataTable
                        value={planifications}
                        loading={loading}
                        dataKey="materielId"
                        paginator
                        rows={10}
                        rowsPerPageOptions={[5, 10, 25, 50]}
                        className="datatable-responsive"
                        paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                        currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} matériels"
                        emptyMessage="Aucune planification trouvée."
                        header={header}
                        selection={selectedMateriels}
                        onSelectionChange={(e) => setSelectedMateriels(e.value)}
                        selectionMode="checkbox"
                        responsiveLayout="scroll"
                    >
                        <Column selectionMode="multiple" headerStyle={{ width: '3rem' }} />
                        <Column field="prioriteRecommandee" header="Priorité" body={prioriteBodyTemplate} sortable style={{ width: '8rem' }} />
                        <Column field="materielNom" header="Matériel" body={materielBodyTemplate} sortable />
                        <Column field="pourcentageUsure" header="Usure" body={usureBodyTemplate} sortable style={{ width: '12rem' }} />
                        <Column field="risqueDefaillance" header="Risque" body={risqueBodyTemplate} sortable style={{ width: '10rem' }} />
                        <Column field="impactArret" header="Impact" body={impactBodyTemplate} sortable style={{ width: '8rem' }} />
                        <Column field="prochaineMaintenance" header="Prochaine maintenance" body={dateBodyTemplate} sortable style={{ width: '12rem' }} />
                        <Column field="technicienRecommande" header="Technicien" body={technicienBodyTemplate} style={{ width: '12rem' }} />
                        <Column field="coutEstime" header="Coût" body={coutBodyTemplate} sortable style={{ width: '10rem' }} />
                        <Column body={actionBodyTemplate} header="Actions" style={{ width: '12rem' }} />
                    </DataTable>
                </Card>
            </div>

            {/* Dialog Configuration */}
            <Dialog
                visible={configDialog}
                style={{ width: '50vw' }}
                header="Configuration de la Planification"
                modal
                onHide={() => setConfigDialog(false)}
                footer={
                    <div>
                        <Button
                            label="Annuler"
                            icon="pi pi-times"
                            className="p-button-outlined"
                            onClick={() => setConfigDialog(false)}
                        />
                        <Button
                            label="Appliquer"
                            icon="pi pi-check"
                            className="p-button-success"
                            onClick={() => {
                                setConfigDialog(false);
                                loadPlanificationMaintenance();
                            }}
                        />
                    </div>
                }
            >
                <div className="grid">
                    <div className="col-12">
                        <h4>Optimisations</h4>
                        <div className="field-checkbox">
                            <input
                                type="checkbox"
                                id="optimiserCouts"
                                checked={configuration.optimiserCouts}
                                onChange={(e) => setConfiguration({ ...configuration, optimiserCouts: e.target.checked })}
                            />
                            <label htmlFor="optimiserCouts" className="ml-2">Optimiser les coûts</label>
                        </div>
                        <div className="field-checkbox">
                            <input
                                type="checkbox"
                                id="optimiserDisponibilite"
                                checked={configuration.optimiserDisponibilite}
                                onChange={(e) => setConfiguration({ ...configuration, optimiserDisponibilite: e.target.checked })}
                            />
                            <label htmlFor="optimiserDisponibilite" className="ml-2">Optimiser la disponibilité</label>
                        </div>
                        <div className="field-checkbox">
                            <input
                                type="checkbox"
                                id="grouperMaintenances"
                                checked={configuration.grouperMaintenances}
                                onChange={(e) => setConfiguration({ ...configuration, grouperMaintenances: e.target.checked })}
                            />
                            <label htmlFor="grouperMaintenances" className="ml-2">Grouper les maintenances</label>
                        </div>
                        <div className="field-checkbox">
                            <input
                                type="checkbox"
                                id="prendreCompteMeteo"
                                checked={configuration.prendreCompteMeteo}
                                onChange={(e) => setConfiguration({ ...configuration, prendreCompteMeteo: e.target.checked })}
                            />
                            <label htmlFor="prendreCompteMeteo" className="ml-2">Prendre en compte la météo</label>
                        </div>
                    </div>
                </div>
            </Dialog>
        </div>
    );
};

export default PlanificationMaintenancePage;
