'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 { Calendar } from 'primereact/calendar';
import { Dropdown } from 'primereact/dropdown';
import { ProgressBar } from 'primereact/progressbar';
import { useRouter } from 'next/navigation';
import { apiClient } from '../../../../services/api-client';

interface MaintenancePreventive {
    id: number;
    materielId: number;
    materielNom: string;
    materielType: string;
    typeMaintenance: 'PREVENTIVE';
    statut: 'PLANIFIEE' | 'EN_COURS' | 'TERMINEE' | 'EN_RETARD';
    priorite: 'BASSE' | 'NORMALE' | 'HAUTE' | 'CRITIQUE';
    datePlanifiee: string;
    dateDebut?: string;
    dateFin?: string;
    technicienId?: number;
    technicienNom?: string;
    description: string;
    dureeEstimee: number;
    dureeReelle?: number;
    coutEstime?: number;
    coutReel?: number;
    prochaineMaintenance?: string;
    frequenceMaintenance: number; // en jours
    derniereMaintenance?: string;
    heuresUtilisation: number;
    seuilMaintenanceHeures: number;
    pourcentageUsure: number;
}

const MaintenancePreventivePage = () => {
    const [maintenances, setMaintenances] = useState<MaintenancePreventive[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [filterStatut, setFilterStatut] = useState<string | null>(null);
    const [filterPriorite, setFilterPriorite] = useState<string | null>(null);
    const [dateDebut, setDateDebut] = useState<Date | null>(null);
    const [dateFin, setDateFin] = useState<Date | null>(null);
    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: 'En retard', value: 'EN_RETARD' }
    ];

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

    useEffect(() => {
        loadMaintenancesPreventives();
    }, [filterStatut, filterPriorite, dateDebut, dateFin]);

    const loadMaintenancesPreventives = async () => {
        try {
            setLoading(true);
            console.log('🔄 Chargement des maintenances préventives...');
            
            const params = new URLSearchParams();
            params.append('type', 'PREVENTIVE');
            if (filterStatut) params.append('statut', filterStatut);
            if (filterPriorite) params.append('priorite', filterPriorite);
            if (dateDebut) params.append('dateDebut', dateDebut.toISOString().split('T')[0]);
            if (dateFin) params.append('dateFin', dateFin.toISOString().split('T')[0]);

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

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

    const demarrerMaintenance = async (maintenanceId: number) => {
        try {
            await apiClient.post(`/api/maintenances/${maintenanceId}/demarrer`);
            console.log('✅ Maintenance démarrée');
            loadMaintenancesPreventives();
        } 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');
            loadMaintenancesPreventives();
        } catch (error) {
            console.error('❌ Erreur lors de la finalisation:', error);
        }
    };

    const statutBodyTemplate = (rowData: MaintenancePreventive) => {
        const getStatutSeverity = (statut: string) => {
            switch (statut) {
                case 'PLANIFIEE': return 'info';
                case 'EN_COURS': return 'warning';
                case 'TERMINEE': return 'success';
                case 'EN_RETARD': return 'danger';
                default: return 'secondary';
            }
        };

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

    const prioriteBodyTemplate = (rowData: MaintenancePreventive) => {
        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.priorite} severity={getPrioriteSeverity(rowData.priorite)} />;
    };

    const materielBodyTemplate = (rowData: MaintenancePreventive) => {
        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: MaintenancePreventive) => {
        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 frequenceBodyTemplate = (rowData: MaintenancePreventive) => {
        const joursDepuisDerniere = rowData.derniereMaintenance ? 
            Math.floor((new Date().getTime() - new Date(rowData.derniereMaintenance).getTime()) / (1000 * 3600 * 24)) : 0;
        
        const pourcentageFrequence = (joursDepuisDerniere / rowData.frequenceMaintenance) * 100;
        const couleur = pourcentageFrequence > 100 ? 'danger' : 
                      pourcentageFrequence > 80 ? 'warning' : 'success';

        return (
            <div className="flex flex-column gap-1">
                <span className="text-sm font-medium">
                    Tous les {rowData.frequenceMaintenance} jours
                </span>
                {rowData.derniereMaintenance && (
                    <div className="text-xs text-500">
                        Dernière: {new Date(rowData.derniereMaintenance).toLocaleDateString('fr-FR')}
                        <br />
                        Il y a {joursDepuisDerniere} jours
                    </div>
                )}
                {rowData.prochaineMaintenance && (
                    <div className="text-xs text-orange-500">
                        Prochaine: {new Date(rowData.prochaineMaintenance).toLocaleDateString('fr-FR')}
                    </div>
                )}
            </div>
        );
    };

    const dateBodyTemplate = (rowData: MaintenancePreventive) => {
        const datePlanifiee = new Date(rowData.datePlanifiee);
        const isRetard = datePlanifiee < new Date() && rowData.statut !== 'TERMINEE';
        const joursRestants = Math.ceil((datePlanifiee.getTime() - new Date().getTime()) / (1000 * 3600 * 24));

        return (
            <div className="flex flex-column gap-1">
                <span className={`font-medium ${isRetard ? 'text-red-500' : ''}`}>
                    {datePlanifiee.toLocaleDateString('fr-FR')}
                </span>
                {!isRetard && joursRestants >= 0 && (
                    <span className="text-xs text-500">
                        Dans {joursRestants} jour{joursRestants > 1 ? 's' : ''}
                    </span>
                )}
                {isRetard && (
                    <Tag value={`Retard: ${Math.abs(joursRestants)} j`} severity="danger" className="p-tag-sm" />
                )}
            </div>
        );
    };

    const technicienBodyTemplate = (rowData: MaintenancePreventive) => {
        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-outlined p-button-sm"
                onClick={() => router.push(`/maintenance/${rowData.id}/assigner`)}
            />
        );
    };

    const actionBodyTemplate = (rowData: MaintenancePreventive) => {
        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-play"
                        className="p-button-rounded p-button-warning 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"
                    />
                )}
                <Button
                    icon="pi pi-calendar-plus"
                    className="p-button-rounded p-button-secondary p-button-sm"
                    onClick={() => planifierMaintenanceAutomatique(rowData.materielId)}
                    tooltip="Planifier prochaine"
                />
            </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="Nouvelle Préventive"
                    icon="pi pi-plus"
                    className="p-button-success"
                    onClick={() => router.push('/maintenance/nouveau?type=PREVENTIVE')}
                />
                <Button
                    label="Planification Auto"
                    icon="pi pi-cog"
                    className="p-button-info"
                    onClick={() => router.push('/maintenance/planification')}
                />
                <Button
                    label="Calendrier"
                    icon="pi pi-calendar"
                    className="p-button-secondary"
                    onClick={() => router.push('/maintenance/calendrier')}
                />
            </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={loadMaintenancesPreventives}
                    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">Maintenance Préventive</h2>
            <div className="flex gap-2 mt-2 md:mt-0">
                <Badge value={maintenances.filter(m => m.statut === 'EN_RETARD').length} severity="danger" />
                <span>En retard</span>
                <Badge value={maintenances.filter(m => m.pourcentageUsure > 80).length} severity="warning" />
                <span>Usure critique</span>
                <Badge value={maintenances.filter(m => m.statut === 'PLANIFIEE').length} severity="info" />
                <span>Planifiées</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-2">
                            <label className="font-medium mb-2 block">Statut</label>
                            <Dropdown
                                value={filterStatut}
                                options={statutOptions}
                                onChange={(e) => setFilterStatut(e.value)}
                                placeholder="Tous"
                            />
                        </div>
                        <div className="col-12 md:col-2">
                            <label className="font-medium mb-2 block">Priorité</label>
                            <Dropdown
                                value={filterPriorite}
                                options={prioriteOptions}
                                onChange={(e) => setFilterPriorite(e.value)}
                                placeholder="Toutes"
                            />
                        </div>
                        <div className="col-12 md:col-2">
                            <label className="font-medium mb-2 block">Date début</label>
                            <Calendar
                                value={dateDebut}
                                onChange={(e) => setDateDebut(e.value as Date)}
                                showIcon
                                dateFormat="dd/mm/yy"
                                placeholder="Date début"
                            />
                        </div>
                        <div className="col-12 md:col-2">
                            <label className="font-medium mb-2 block">Date fin</label>
                            <Calendar
                                value={dateFin}
                                onChange={(e) => setDateFin(e.value as Date)}
                                showIcon
                                dateFormat="dd/mm/yy"
                                placeholder="Date fin"
                            />
                        </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);
                                    setFilterPriorite(null);
                                    setDateDebut(null);
                                    setDateFin(null);
                                }}
                            />
                        </div>
                    </div>

                    <DataTable
                        value={maintenances}
                        loading={loading}
                        dataKey="id"
                        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} maintenances préventives"
                        globalFilter={globalFilter}
                        emptyMessage="Aucune maintenance préventive trouvée."
                        header={header}
                        responsiveLayout="scroll"
                    >
                        <Column field="priorite" header="Priorité" body={prioriteBodyTemplate} sortable style={{ width: '8rem' }} />
                        <Column field="materielNom" header="Matériel" body={materielBodyTemplate} sortable />
                        <Column field="statut" header="Statut" body={statutBodyTemplate} sortable style={{ width: '8rem' }} />
                        <Column field="pourcentageUsure" header="Usure" body={usureBodyTemplate} sortable style={{ width: '12rem' }} />
                        <Column field="frequenceMaintenance" header="Fréquence" body={frequenceBodyTemplate} style={{ width: '12rem' }} />
                        <Column field="datePlanifiee" header="Date planifiée" body={dateBodyTemplate} sortable style={{ width: '10rem' }} />
                        <Column field="technicienNom" header="Technicien" body={technicienBodyTemplate} style={{ width: '10rem' }} />
                        <Column field="description" header="Description" style={{ width: '15rem' }} />
                        <Column body={actionBodyTemplate} header="Actions" style={{ width: '12rem' }} />
                    </DataTable>
                </Card>
            </div>
        </div>
    );
};

export default MaintenancePreventivePage;
