'use client';

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

interface MaintenanceUrgente {
    id: number;
    materielId: number;
    materielNom: string;
    materielType: string;
    typeMaintenance: 'URGENTE';
    statut: 'PLANIFIEE' | 'EN_COURS' | 'TERMINEE' | 'ANNULEE';
    priorite: 'CRITIQUE';
    dateCreation: string;
    datePlanifiee: string;
    dateDebut?: string;
    dateFin?: string;
    technicienId?: number;
    technicienNom?: string;
    description: string;
    problemeSignale: string;
    solutionApportee?: string;
    dureeEstimee: number;
    dureeReelle?: number;
    coutEstime?: number;
    coutReel?: number;
    impactProduction: 'AUCUN' | 'FAIBLE' | 'MOYEN' | 'ELEVE' | 'ARRET_TOTAL';
    tempsReponse: number; // en minutes
    tempsResolution?: number; // en minutes
    escalade: boolean;
    personneSignalement: string;
    chantierImpacte?: string;
    mesuresTemporaires?: string;
}

const MaintenanceUrgentePage = () => {
    const [maintenances, setMaintenances] = useState<MaintenanceUrgente[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [filterStatut, setFilterStatut] = useState<string | null>(null);
    const [filterImpact, setFilterImpact] = useState<string | null>(null);
    const [interventionDialog, setInterventionDialog] = useState(false);
    const [selectedMaintenance, setSelectedMaintenance] = useState<MaintenanceUrgente | null>(null);
    const [intervention, setIntervention] = useState({
        mesuresTemporaires: '',
        technicienId: 0,
        dateIntervention: new Date()
    });
    const [techniciens, setTechniciens] = useState<any[]>([]);
    const router = useRouter();

    const statutOptions = [
        { label: 'Tous', value: null },
        { label: 'Planifiée', value: 'PLANIFIEE' },
        { label: 'En cours', value: 'EN_COURS' },
        { label: 'Terminée', value: 'TERMINEE' },
        { label: 'Annulée', value: 'ANNULEE' }
    ];

    const impactOptions = [
        { label: 'Tous', value: null },
        { label: 'Aucun', value: 'AUCUN' },
        { label: 'Faible', value: 'FAIBLE' },
        { label: 'Moyen', value: 'MOYEN' },
        { label: 'Élevé', value: 'ELEVE' },
        { label: 'Arrêt total', value: 'ARRET_TOTAL' }
    ];

    useEffect(() => {
        loadMaintenancesUrgentes();
        loadTechniciens();
    }, [filterStatut, filterImpact]);

    const loadMaintenancesUrgentes = async () => {
        try {
            setLoading(true);
            console.log('🔄 Chargement des maintenances urgentes...');
            
            const params = new URLSearchParams();
            params.append('type', 'URGENTE');
            if (filterStatut) params.append('statut', filterStatut);
            if (filterImpact) params.append('impact', filterImpact);

            const response = await apiClient.get(`/api/maintenances/urgentes?${params.toString()}`);
            console.log('✅ Maintenances urgentes chargées:', response.data);
            setMaintenances(response.data || []);
        } catch (error) {
            console.error('❌ Erreur lors du chargement:', error);
            setMaintenances([]);
        } finally {
            setLoading(false);
        }
    };

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

    const escaladerMaintenance = async (maintenanceId: number) => {
        try {
            await apiClient.post(`/api/maintenances/${maintenanceId}/escalader`);
            console.log('✅ Maintenance escaladée');
            loadMaintenancesUrgentes();
        } catch (error) {
            console.error('❌ Erreur lors de l\'escalade:', error);
        }
    };

    const ouvrirIntervention = (maintenance: MaintenanceUrgente) => {
        setSelectedMaintenance(maintenance);
        setIntervention({
            mesuresTemporaires: maintenance.mesuresTemporaires || '',
            technicienId: maintenance.technicienId || 0,
            dateIntervention: new Date()
        });
        setInterventionDialog(true);
    };

    const planifierIntervention = async () => {
        if (!selectedMaintenance) return;

        try {
            await apiClient.post(`/api/maintenances/${selectedMaintenance.id}/intervention-urgente`, intervention);
            console.log('✅ Intervention urgente planifiée');
            setInterventionDialog(false);
            loadMaintenancesUrgentes();
        } catch (error) {
            console.error('❌ Erreur lors de la planification:', error);
        }
    };

    const demarrerMaintenance = async (maintenanceId: number) => {
        try {
            await apiClient.post(`/api/maintenances/${maintenanceId}/demarrer`);
            console.log('✅ Maintenance démarrée');
            loadMaintenancesUrgentes();
        } catch (error) {
            console.error('❌ Erreur lors du démarrage:', error);
        }
    };

    const terminerMaintenance = async (maintenanceId: number) => {
        try {
            await apiClient.post(`/api/maintenances/${maintenanceId}/terminer`);
            console.log('✅ Maintenance terminée');
            loadMaintenancesUrgentes();
        } catch (error) {
            console.error('❌ Erreur lors de la finalisation:', error);
        }
    };

    const statutBodyTemplate = (rowData: MaintenanceUrgente) => {
        const getStatutSeverity = (statut: string) => {
            switch (statut) {
                case 'PLANIFIEE': return 'danger'; // Urgent = rouge même planifié
                case 'EN_COURS': return 'warning';
                case 'TERMINEE': return 'success';
                case 'ANNULEE': return 'secondary';
                default: return 'secondary';
            }
        };

        return <Tag value={rowData.statut} severity={getStatutSeverity(rowData.statut)} />;
    };

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

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

    const materielBodyTemplate = (rowData: MaintenanceUrgente) => {
        return (
            <div className="flex flex-column gap-1">
                <span className="font-medium text-red-600">{rowData.materielNom}</span>
                <span className="text-sm text-500">{rowData.materielType}</span>
                {rowData.chantierImpacte && (
                    <span className="text-xs text-orange-500">
                        Chantier: {rowData.chantierImpacte}
                    </span>
                )}
            </div>
        );
    };

    const problemeBodyTemplate = (rowData: MaintenanceUrgente) => {
        return (
            <div className="max-w-20rem">
                <p className="m-0 text-sm line-height-3 font-medium text-red-600">
                    {rowData.problemeSignale.length > 100 
                        ? `${rowData.problemeSignale.substring(0, 100)}...`
                        : rowData.problemeSignale
                    }
                </p>
                <div className="text-xs text-500 mt-1">
                    Signalé par: {rowData.personneSignalement}
                </div>
            </div>
        );
    };

    const tempsBodyTemplate = (rowData: MaintenanceUrgente) => {
        const tempsEcoule = Math.floor((new Date().getTime() - new Date(rowData.dateCreation).getTime()) / (1000 * 60));
        const heures = Math.floor(tempsEcoule / 60);
        const minutes = tempsEcoule % 60;
        
        const couleur = tempsEcoule > 120 ? 'text-red-500' : 
                       tempsEcoule > 60 ? 'text-orange-500' : 'text-green-500';

        return (
            <div className="flex flex-column gap-1">
                <span className={`font-medium ${couleur}`}>
                    {heures > 0 ? `${heures}h ${minutes}min` : `${minutes}min`}
                </span>
                <span className="text-xs text-500">
                    Depuis signalement
                </span>
                {rowData.tempsResolution && (
                    <span className="text-xs text-green-600">
                        Résolu en {Math.floor(rowData.tempsResolution / 60)}h{rowData.tempsResolution % 60}min
                    </span>
                )}
            </div>
        );
    };

    const escaladeBodyTemplate = (rowData: MaintenanceUrgente) => {
        if (rowData.escalade) {
            return <Tag value="ESCALADÉ" severity="danger" />;
        }
        
        const tempsEcoule = Math.floor((new Date().getTime() - new Date(rowData.dateCreation).getTime()) / (1000 * 60));
        if (tempsEcoule > 120 && rowData.statut !== 'TERMINEE') {
            return (
                <Button
                    label="Escalader"
                    icon="pi pi-exclamation-triangle"
                    className="p-button-danger p-button-sm"
                    onClick={() => escaladerMaintenance(rowData.id)}
                />
            );
        }
        
        return <span className="text-500">Normal</span>;
    };

    const technicienBodyTemplate = (rowData: MaintenanceUrgente) => {
        if (rowData.technicienNom) {
            return (
                <div className="flex align-items-center gap-2">
                    <i className="pi pi-user text-blue-500" />
                    <span>{rowData.technicienNom}</span>
                </div>
            );
        }
        return (
            <Button
                label="Assigner"
                icon="pi pi-user-plus"
                className="p-button-danger p-button-sm"
                onClick={() => ouvrirIntervention(rowData)}
            />
        );
    };

    const mesuresBodyTemplate = (rowData: MaintenanceUrgente) => {
        if (rowData.mesuresTemporaires) {
            return (
                <div className="max-w-15rem">
                    <p className="m-0 text-sm line-height-3 text-blue-600">
                        {rowData.mesuresTemporaires.length > 80 
                            ? `${rowData.mesuresTemporaires.substring(0, 80)}...`
                            : rowData.mesuresTemporaires
                        }
                    </p>
                </div>
            );
        }
        return <span className="text-500">Aucune mesure</span>;
    };

    const actionBodyTemplate = (rowData: MaintenanceUrgente) => {
        return (
            <div className="flex gap-2">
                <Button
                    icon="pi pi-eye"
                    className="p-button-rounded p-button-info p-button-sm"
                    onClick={() => router.push(`/maintenance/${rowData.id}`)}
                    tooltip="Voir détails"
                />
                {rowData.statut === 'PLANIFIEE' && (
                    <>
                        <Button
                            icon="pi pi-cog"
                            className="p-button-rounded p-button-warning p-button-sm"
                            onClick={() => ouvrirIntervention(rowData)}
                            tooltip="Planifier intervention"
                        />
                        <Button
                            icon="pi pi-play"
                            className="p-button-rounded p-button-danger p-button-sm"
                            onClick={() => demarrerMaintenance(rowData.id)}
                            tooltip="Démarrer"
                        />
                    </>
                )}
                {rowData.statut === 'EN_COURS' && (
                    <Button
                        icon="pi pi-check"
                        className="p-button-rounded p-button-success p-button-sm"
                        onClick={() => terminerMaintenance(rowData.id)}
                        tooltip="Terminer"
                    />
                )}
            </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="Signaler Urgence"
                    icon="pi pi-exclamation-triangle"
                    className="p-button-danger"
                    onClick={() => router.push('/maintenance/signaler-urgence')}
                />
                <Button
                    label="Protocole Urgence"
                    icon="pi pi-book"
                    className="p-button-warning"
                    onClick={() => router.push('/maintenance/protocole-urgence')}
                />
                <Button
                    label="Équipes d'Astreinte"
                    icon="pi pi-users"
                    className="p-button-info"
                    onClick={() => router.push('/maintenance/astreinte')}
                />
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <div className="flex gap-2">
                <span className="p-input-icon-left">
                    <i className="pi pi-search" />
                    <InputText
                        type="search"
                        placeholder="Rechercher..."
                        value={globalFilter}
                        onChange={(e) => setGlobalFilter(e.target.value)}
                    />
                </span>
                <Button
                    icon="pi pi-refresh"
                    className="p-button-outlined"
                    onClick={loadMaintenancesUrgentes}
                    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 text-red-600">🚨 Maintenance Urgente</h2>
            <div className="flex gap-2 mt-2 md:mt-0">
                <Badge value={maintenances.filter(m => m.impactProduction === 'ARRET_TOTAL').length} severity="danger" />
                <span>Arrêt total</span>
                <Badge value={maintenances.filter(m => m.escalade).length} severity="warning" />
                <span>Escaladées</span>
                <Badge value={maintenances.filter(m => m.statut === 'EN_COURS').length} severity="info" />
                <span>En cours</span>
            </div>
        </div>
    );

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

                    {/* Filtres */}
                    <div className="grid mb-4">
                        <div className="col-12 md:col-4">
                            <label className="font-medium mb-2 block">Statut</label>
                            <Dropdown
                                value={filterStatut}
                                options={statutOptions}
                                onChange={(e) => setFilterStatut(e.value)}
                                placeholder="Tous les statuts"
                            />
                        </div>
                        <div className="col-12 md:col-4">
                            <label className="font-medium mb-2 block">Impact production</label>
                            <Dropdown
                                value={filterImpact}
                                options={impactOptions}
                                onChange={(e) => setFilterImpact(e.value)}
                                placeholder="Tous les impacts"
                            />
                        </div>
                        <div className="col-12 md:col-4">
                            <label className="font-medium mb-2 block">Actions</label>
                            <Button
                                label="Réinitialiser filtres"
                                icon="pi pi-filter-slash"
                                className="p-button-outlined w-full"
                                onClick={() => {
                                    setFilterStatut(null);
                                    setFilterImpact(null);
                                }}
                            />
                        </div>
                    </div>

                    <DataTable
                        value={maintenances}
                        loading={loading}
                        dataKey="id"
                        paginator
                        rows={10}
                        rowsPerPageOptions={[5, 10, 25]}
                        className="datatable-responsive"
                        paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                        currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} maintenances urgentes"
                        globalFilter={globalFilter}
                        emptyMessage="Aucune maintenance urgente trouvée."
                        header={header}
                        responsiveLayout="scroll"
                        rowClassName={(rowData) => rowData.impactProduction === 'ARRET_TOTAL' ? 'bg-red-50' : ''}
                    >
                        <Column field="statut" header="Statut" body={statutBodyTemplate} sortable style={{ width: '8rem' }} />
                        <Column field="impactProduction" header="Impact" body={impactBodyTemplate} sortable style={{ width: '8rem' }} />
                        <Column field="materielNom" header="Matériel" body={materielBodyTemplate} sortable />
                        <Column field="problemeSignale" header="Problème Urgent" body={problemeBodyTemplate} style={{ width: '18rem' }} />
                        <Column field="dateCreation" header="Temps" body={tempsBodyTemplate} sortable style={{ width: '10rem' }} />
                        <Column field="escalade" header="Escalade" body={escaladeBodyTemplate} style={{ width: '10rem' }} />
                        <Column field="technicienNom" header="Technicien" body={technicienBodyTemplate} style={{ width: '10rem' }} />
                        <Column field="mesuresTemporaires" header="Mesures" body={mesuresBodyTemplate} style={{ width: '12rem' }} />
                        <Column body={actionBodyTemplate} header="Actions" style={{ width: '12rem' }} />
                    </DataTable>
                </Card>
            </div>

            {/* Dialog Intervention Urgente */}
            <Dialog
                visible={interventionDialog}
                style={{ width: '50vw' }}
                header="🚨 Planifier Intervention Urgente"
                modal
                onHide={() => setInterventionDialog(false)}
                footer={
                    <div>
                        <Button
                            label="Annuler"
                            icon="pi pi-times"
                            className="p-button-outlined"
                            onClick={() => setInterventionDialog(false)}
                        />
                        <Button
                            label="Planifier"
                            icon="pi pi-check"
                            className="p-button-danger"
                            onClick={planifierIntervention}
                        />
                    </div>
                }
            >
                <div className="grid p-fluid">
                    <div className="col-12">
                        <label className="font-medium">Technicien d'intervention *</label>
                        <Dropdown
                            value={intervention.technicienId}
                            options={techniciens}
                            onChange={(e) => setIntervention({ ...intervention, technicienId: e.value })}
                            optionLabel="nom"
                            optionValue="id"
                            placeholder="Sélectionner un technicien disponible"
                            filter
                        />
                    </div>
                    <div className="col-12">
                        <label className="font-medium">Date/Heure d'intervention *</label>
                        <Calendar
                            value={intervention.dateIntervention}
                            onChange={(e) => setIntervention({ ...intervention, dateIntervention: e.value as Date })}
                            showTime
                            showIcon
                            dateFormat="dd/mm/yy"
                            timeFormat="24"
                            placeholder="Sélectionner date et heure"
                        />
                    </div>
                    <div className="col-12">
                        <label className="font-medium">Mesures temporaires</label>
                        <InputTextarea
                            value={intervention.mesuresTemporaires}
                            onChange={(e) => setIntervention({ ...intervention, mesuresTemporaires: e.target.value })}
                            rows={3}
                            placeholder="Décrivez les mesures temporaires mises en place..."
                        />
                    </div>
                </div>
            </Dialog>
        </div>
    );
};

export default MaintenanceUrgentePage;
