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


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

interface Maintenance {
    id: number;
    materielId: number;
    materielNom: string;
    materielType: string;
    typeMaintenance: 'PREVENTIVE' | 'CORRECTIVE' | 'PLANIFIEE' | 'URGENTE';
    statut: 'PLANIFIEE' | 'EN_COURS' | 'TERMINEE' | 'ANNULEE' | 'EN_ATTENTE';
    priorite: 'BASSE' | 'NORMALE' | 'HAUTE' | 'CRITIQUE';
    dateCreation: string;
    datePlanifiee: string;
    dateDebut?: string;
    dateFin?: string;
    technicienId?: number;
    technicienNom?: string;
    description: string;
    problemeSignale?: string;
    solutionApportee?: string;
    coutEstime?: number;
    coutReel?: number;
    piecesUtilisees: Array<{
        nom: string;
        quantite: number;
        cout: number;
    }>;
    dureeEstimee: number; // en heures
    dureeReelle?: number; // en heures
    prochaineMaintenance?: string;
    observations?: string;
}

const MaintenancePage = () => {
    const [maintenances, setMaintenances] = useState<Maintenance[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedMaintenances, setSelectedMaintenances] = useState<Maintenance[]>([]);
    const [deleteDialog, setDeleteDialog] = useState(false);
    const [maintenanceToDelete, setMaintenanceToDelete] = useState<Maintenance | null>(null);
    const [filterType, setFilterType] = useState<string | null>(null);
    const [filterStatut, setFilterStatut] = useState<string | null>(null);
    const [filterPriorite, setFilterPriorite] = useState<string | null>(null);
    const router = useRouter();

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

    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' },
        { label: 'En attente', value: 'EN_ATTENTE' }
    ];

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

    useEffect(() => {
        loadMaintenances();
    }, [filterType, filterStatut, filterPriorite]);

    const loadMaintenances = async () => {
        try {
            setLoading(true);
            console.log('🔄 Chargement des maintenances...');
            
            const params = new URLSearchParams();
            if (filterType) params.append('type', filterType);
            if (filterStatut) params.append('statut', filterStatut);
            if (filterPriorite) params.append('priorite', filterPriorite);

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

    const confirmDeleteMaintenance = (maintenance: Maintenance) => {
        setMaintenanceToDelete(maintenance);
        setDeleteDialog(true);
    };

    const deleteMaintenance = async () => {
        if (maintenanceToDelete) {
            try {
                await apiClient.delete(`/api/maintenances/${maintenanceToDelete.id}`);
                setMaintenances(maintenances.filter(m => m.id !== maintenanceToDelete.id));
                setDeleteDialog(false);
                setMaintenanceToDelete(null);
                console.log('✅ Maintenance supprimée avec succès');
            } catch (error) {
                console.error('❌ Erreur lors de la suppression:', error);
            }
        }
    };

    const changerStatutMaintenance = async (maintenance: Maintenance, nouveauStatut: string) => {
        try {
            await apiClient.post(`/api/maintenances/${maintenance.id}/statut`, { statut: nouveauStatut });
            
            setMaintenances(maintenances.map(m => 
                m.id === maintenance.id ? { ...m, statut: nouveauStatut as any } : m
            ));
            
            console.log(`✅ Statut maintenance changé: ${nouveauStatut}`);
        } catch (error) {
            console.error('❌ Erreur lors du changement de statut:', error);
        }
    };

    const typeBodyTemplate = (rowData: Maintenance) => {
        const getTypeSeverity = (type: string) => {
            switch (type) {
                case 'PREVENTIVE': return 'info';
                case 'CORRECTIVE': return 'warning';
                case 'PLANIFIEE': return 'success';
                case 'URGENTE': return 'danger';
                default: return 'secondary';
            }
        };

        return <Tag value={rowData.typeMaintenance} severity={getTypeSeverity(rowData.typeMaintenance)} />;
    };

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

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

    const prioriteBodyTemplate = (rowData: Maintenance) => {
        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: Maintenance) => {
        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 technicienBodyTemplate = (rowData: Maintenance) => {
        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 <span className="text-500">Non assigné</span>;
    };

    const dateBodyTemplate = (rowData: Maintenance) => {
        const datePlanifiee = new Date(rowData.datePlanifiee);
        const isUrgent = rowData.typeMaintenance === 'URGENTE';
        const isRetard = datePlanifiee < new Date() && rowData.statut !== 'TERMINEE';

        return (
            <div className="flex flex-column gap-1">
                <span className={`font-medium ${isRetard ? 'text-red-500' : ''}`}>
                    {datePlanifiee.toLocaleDateString('fr-FR')}
                </span>
                {isUrgent && <Tag value="URGENT" severity="danger" className="p-tag-sm" />}
                {isRetard && <Tag value="RETARD" severity="danger" className="p-tag-sm" />}
            </div>
        );
    };

    const coutBodyTemplate = (rowData: Maintenance) => {
        const coutAffiche = rowData.coutReel || rowData.coutEstime;
        const isReel = !!rowData.coutReel;

        return (
            <div className="flex flex-column gap-1">
                {coutAffiche && (
                    <span className={`font-medium ${isReel ? 'text-green-500' : 'text-orange-500'}`}>
                        {coutAffiche.toLocaleString('fr-FR')} €
                    </span>
                )}
                <span className="text-sm text-500">
                    {isReel ? 'Coût réel' : 'Coût estimé'}
                </span>
            </div>
        );
    };

    const dureeBodyTemplate = (rowData: Maintenance) => {
        const dureeAffichee = rowData.dureeReelle || rowData.dureeEstimee;
        const isReelle = !!rowData.dureeReelle;

        return (
            <div className="flex flex-column gap-1">
                <span className={`font-medium ${isReelle ? 'text-green-500' : 'text-orange-500'}`}>
                    {dureeAffichee}h
                </span>
                <span className="text-sm text-500">
                    {isReelle ? 'Durée réelle' : 'Durée estimée'}
                </span>
            </div>
        );
    };

    const actionBodyTemplate = (rowData: Maintenance) => {
        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"
                />
                <Button
                    icon="pi pi-pencil"
                    className="p-button-rounded p-button-success p-button-sm"
                    onClick={() => router.push(`/maintenance/${rowData.id}/edit`)}
                    tooltip="Modifier"
                />
                {rowData.statut === 'PLANIFIEE' && (
                    <Button
                        icon="pi pi-play"
                        className="p-button-rounded p-button-warning p-button-sm"
                        onClick={() => changerStatutMaintenance(rowData, 'EN_COURS')}
                        tooltip="Démarrer"
                    />
                )}
                {rowData.statut === 'EN_COURS' && (
                    <Button
                        icon="pi pi-check"
                        className="p-button-rounded p-button-success p-button-sm"
                        onClick={() => changerStatutMaintenance(rowData, 'TERMINEE')}
                        tooltip="Terminer"
                    />
                )}
                <Button
                    icon="pi pi-trash"
                    className="p-button-rounded p-button-danger p-button-sm"
                    onClick={() => confirmDeleteMaintenance(rowData)}
                    tooltip="Supprimer"
                />
            </div>
        );
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="flex flex-wrap gap-2">
                <Button
                    label="Nouvelle Maintenance"
                    icon="pi pi-plus"
                    className="p-button-success"
                    onClick={() => router.push('/maintenance/nouveau')}
                />
                <Button
                    label="Préventive"
                    icon="pi pi-calendar-clock"
                    className="p-button-info"
                    onClick={() => router.push('/maintenance/preventive')}
                />
                <Button
                    label="Corrective"
                    icon="pi pi-wrench"
                    className="p-button-warning"
                    onClick={() => router.push('/maintenance/corrective')}
                />
                <Button
                    label="Urgente"
                    icon="pi pi-exclamation-triangle"
                    className="p-button-danger"
                    onClick={() => router.push('/maintenance/urgente')}
                />
                <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={loadMaintenances}
                    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">Gestion de la Maintenance</h2>
            <div className="flex gap-2 mt-2 md:mt-0">
                <Badge value={maintenances.filter(m => m.statut === 'EN_COURS').length} severity="warning" />
                <span>En cours</span>
                <Badge value={maintenances.filter(m => m.typeMaintenance === 'URGENTE').length} severity="danger" />
                <span>Urgentes</span>
                <Badge value={maintenances.filter(m => new Date(m.datePlanifiee) < new Date() && m.statut !== 'TERMINEE').length} severity="danger" />
                <span>En retard</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-3">
                            <label className="font-medium mb-2 block">Type de maintenance</label>
                            <Dropdown
                                value={filterType}
                                options={typeOptions}
                                onChange={(e) => setFilterType(e.value)}
                                placeholder="Tous les types"
                            />
                        </div>
                        <div className="col-12 md:col-3">
                            <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-3">
                            <label className="font-medium mb-2 block">Priorité</label>
                            <Dropdown
                                value={filterPriorite}
                                options={prioriteOptions}
                                onChange={(e) => setFilterPriorite(e.value)}
                                placeholder="Toutes les priorités"
                            />
                        </div>
                        <div className="col-12 md:col-3">
                            <label className="font-medium mb-2 block">Actions</label>
                            <Button
                                label="Réinitialiser"
                                icon="pi pi-filter-slash"
                                className="p-button-outlined w-full"
                                onClick={() => {
                                    setFilterType(null);
                                    setFilterStatut(null);
                                    setFilterPriorite(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"
                        globalFilter={globalFilter}
                        emptyMessage="Aucune maintenance trouvée."
                        header={header}
                        selection={selectedMaintenances}
                        onSelectionChange={(e) => setSelectedMaintenances(e.value)}
                        selectionMode="checkbox"
                        responsiveLayout="scroll"
                    >
                        <Column selectionMode="multiple" headerStyle={{ width: '3rem' }} />
                        <Column field="typeMaintenance" header="Type" body={typeBodyTemplate} sortable />
                        <Column field="priorite" header="Priorité" body={prioriteBodyTemplate} sortable />
                        <Column field="materielNom" header="Matériel" body={materielBodyTemplate} sortable />
                        <Column field="statut" header="Statut" body={statutBodyTemplate} sortable />
                        <Column field="technicienNom" header="Technicien" body={technicienBodyTemplate} sortable />
                        <Column field="datePlanifiee" header="Date planifiée" body={dateBodyTemplate} sortable />
                        <Column field="coutEstime" header="Coût" body={coutBodyTemplate} sortable />
                        <Column field="dureeEstimee" header="Durée" body={dureeBodyTemplate} sortable />
                        <Column field="description" header="Description" />
                        <Column body={actionBodyTemplate} header="Actions" style={{ minWidth: '14rem' }} />
                    </DataTable>
                </Card>
            </div>

            <ConfirmDialog
                visible={deleteDialog}
                onHide={() => setDeleteDialog(false)}
                message={`Êtes-vous sûr de vouloir supprimer cette maintenance ?`}
                header="Confirmation de suppression"
                icon="pi pi-exclamation-triangle"
                accept={deleteMaintenance}
                reject={() => setDeleteDialog(false)}
                acceptLabel="Oui"
                rejectLabel="Non"
                acceptClassName="p-button-danger"
            />

            <Toast />
        </div>
    );
};

export default MaintenancePage;
