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

interface MaintenanceCorrective {
    id: number;
    materielId: number;
    materielNom: string;
    materielType: string;
    typeMaintenance: 'CORRECTIVE';
    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;
    dureeEstimee: number;
    dureeReelle?: number;
    coutEstime?: number;
    coutReel?: number;
    piecesUtilisees: Array<{
        nom: string;
        quantite: number;
        cout: number;
    }>;
    gravite: 'MINEURE' | 'MODEREE' | 'MAJEURE' | 'CRITIQUE';
    impactProduction: 'AUCUN' | 'FAIBLE' | 'MOYEN' | 'ELEVE';
    causeRacine?: string;
    actionPreventive?: string;
}

const MaintenanceCorrectivePage = () => {
    const [maintenances, setMaintenances] = useState<MaintenanceCorrective[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [filterStatut, setFilterStatut] = useState<string | null>(null);
    const [filterGravite, setFilterGravite] = useState<string | null>(null);
    const [filterImpact, setFilterImpact] = useState<string | null>(null);
    const [dateDebut, setDateDebut] = useState<Date | null>(null);
    const [dateFin, setDateFin] = useState<Date | null>(null);
    const [diagnosticDialog, setDiagnosticDialog] = useState(false);
    const [selectedMaintenance, setSelectedMaintenance] = useState<MaintenanceCorrective | null>(null);
    const [diagnostic, setDiagnostic] = useState({
        solutionApportee: '',
        causeRacine: '',
        actionPreventive: ''
    });
    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' },
        { label: 'En attente', value: 'EN_ATTENTE' }
    ];

    const graviteOptions = [
        { label: 'Toutes', value: null },
        { label: 'Mineure', value: 'MINEURE' },
        { label: 'Modérée', value: 'MODEREE' },
        { label: 'Majeure', value: 'MAJEURE' },
        { label: 'Critique', value: 'CRITIQUE' }
    ];

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

    useEffect(() => {
        loadMaintenancesCorrectives();
    }, [filterStatut, filterGravite, filterImpact, dateDebut, dateFin]);

    const loadMaintenancesCorrectives = async () => {
        try {
            setLoading(true);
            console.log('🔄 Chargement des maintenances correctives...');
            
            const params = new URLSearchParams();
            params.append('type', 'CORRECTIVE');
            if (filterStatut) params.append('statut', filterStatut);
            if (filterGravite) params.append('gravite', filterGravite);
            if (filterImpact) params.append('impact', filterImpact);
            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/correctives?${params.toString()}`);
            console.log('✅ Maintenances correctives chargées:', response.data);
            setMaintenances(response.data || []);
        } catch (error) {
            console.error('❌ Erreur lors du chargement:', error);
            setMaintenances([]);
        } finally {
            setLoading(false);
        }
    };

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

    const ouvrirDiagnostic = (maintenance: MaintenanceCorrective) => {
        setSelectedMaintenance(maintenance);
        setDiagnostic({
            solutionApportee: maintenance.solutionApportee || '',
            causeRacine: maintenance.causeRacine || '',
            actionPreventive: maintenance.actionPreventive || ''
        });
        setDiagnosticDialog(true);
    };

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

        try {
            await apiClient.put(`/api/maintenances/${selectedMaintenance.id}/diagnostic`, diagnostic);
            console.log('✅ Diagnostic sauvegardé');
            setDiagnosticDialog(false);
            loadMaintenancesCorrectives();
        } catch (error) {
            console.error('❌ Erreur lors de la sauvegarde:', error);
        }
    };

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

    const statutBodyTemplate = (rowData: MaintenanceCorrective) => {
        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 graviteBodyTemplate = (rowData: MaintenanceCorrective) => {
        const getGraviteSeverity = (gravite: string) => {
            switch (gravite) {
                case 'MINEURE': return 'info';
                case 'MODEREE': return 'warning';
                case 'MAJEURE': return 'danger';
                case 'CRITIQUE': return 'danger';
                default: return 'secondary';
            }
        };

        return <Tag value={rowData.gravite} severity={getGraviteSeverity(rowData.gravite)} />;
    };

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

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

    const materielBodyTemplate = (rowData: MaintenanceCorrective) => {
        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 problemeBodyTemplate = (rowData: MaintenanceCorrective) => {
        return (
            <div className="max-w-20rem">
                <p className="m-0 text-sm line-height-3">
                    {rowData.problemeSignale.length > 100 
                        ? `${rowData.problemeSignale.substring(0, 100)}...`
                        : rowData.problemeSignale
                    }
                </p>
            </div>
        );
    };

    const solutionBodyTemplate = (rowData: MaintenanceCorrective) => {
        if (rowData.solutionApportee) {
            return (
                <div className="max-w-20rem">
                    <p className="m-0 text-sm line-height-3 text-green-600">
                        {rowData.solutionApportee.length > 80 
                            ? `${rowData.solutionApportee.substring(0, 80)}...`
                            : rowData.solutionApportee
                        }
                    </p>
                </div>
            );
        }
        return <span className="text-500">En attente de diagnostic</span>;
    };

    const dateBodyTemplate = (rowData: MaintenanceCorrective) => {
        const dateCreation = new Date(rowData.dateCreation);
        const datePlanifiee = new Date(rowData.datePlanifiee);
        const delai = Math.ceil((datePlanifiee.getTime() - dateCreation.getTime()) / (1000 * 3600 * 24));

        return (
            <div className="flex flex-column gap-1">
                <span className="text-sm text-500">
                    Signalé: {dateCreation.toLocaleDateString('fr-FR')}
                </span>
                <span className="font-medium">
                    Planifié: {datePlanifiee.toLocaleDateString('fr-FR')}
                </span>
                <span className={`text-xs ${delai > 3 ? 'text-red-500' : 'text-green-500'}`}>
                    Délai: {delai} jour{delai > 1 ? 's' : ''}
                </span>
            </div>
        );
    };

    const technicienBodyTemplate = (rowData: MaintenanceCorrective) => {
        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 coutBodyTemplate = (rowData: MaintenanceCorrective) => {
        const coutTotal = rowData.coutReel || rowData.coutEstime || 0;
        const coutPieces = rowData.piecesUtilisees?.reduce((total, piece) => total + piece.cout, 0) || 0;

        return (
            <div className="flex flex-column gap-1">
                <span className="font-medium">
                    {coutTotal.toLocaleString('fr-FR')} €
                </span>
                {coutPieces > 0 && (
                    <span className="text-sm text-500">
                        Pièces: {coutPieces.toLocaleString('fr-FR')} €
                    </span>
                )}
            </div>
        );
    };

    const actionBodyTemplate = (rowData: MaintenanceCorrective) => {
        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-cog"
                            className="p-button-rounded p-button-secondary p-button-sm"
                            onClick={() => ouvrirDiagnostic(rowData)}
                            tooltip="Diagnostic"
                        />
                        <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-pencil"
                    className="p-button-rounded p-button-success p-button-sm"
                    onClick={() => router.push(`/maintenance/${rowData.id}/edit`)}
                    tooltip="Modifier"
                />
            </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 Corrective"
                    icon="pi pi-plus"
                    className="p-button-success"
                    onClick={() => router.push('/maintenance/nouveau?type=CORRECTIVE')}
                />
                <Button
                    label="Signaler Panne"
                    icon="pi pi-exclamation-triangle"
                    className="p-button-danger"
                    onClick={() => router.push('/maintenance/signaler-panne')}
                />
                <Button
                    label="Rapport"
                    icon="pi pi-file-pdf"
                    className="p-button-secondary"
                    onClick={() => router.push('/maintenance/rapport-corrective')}
                />
            </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={loadMaintenancesCorrectives}
                    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 Corrective</h2>
            <div className="flex gap-2 mt-2 md:mt-0">
                <Badge value={maintenances.filter(m => m.gravite === 'CRITIQUE').length} severity="danger" />
                <span>Critiques</span>
                <Badge value={maintenances.filter(m => m.impactProduction === 'ELEVE').length} severity="warning" />
                <span>Impact élevé</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-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">Gravité</label>
                            <Dropdown
                                value={filterGravite}
                                options={graviteOptions}
                                onChange={(e) => setFilterGravite(e.value)}
                                placeholder="Toutes"
                            />
                        </div>
                        <div className="col-12 md:col-2">
                            <label className="font-medium mb-2 block">Impact</label>
                            <Dropdown
                                value={filterImpact}
                                options={impactOptions}
                                onChange={(e) => setFilterImpact(e.value)}
                                placeholder="Tous"
                            />
                        </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-2">
                            <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={() => {
                                    setFilterStatut(null);
                                    setFilterGravite(null);
                                    setFilterImpact(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 correctives"
                        globalFilter={globalFilter}
                        emptyMessage="Aucune maintenance corrective trouvée."
                        header={header}
                        responsiveLayout="scroll"
                    >
                        <Column field="gravite" header="Gravité" body={graviteBodyTemplate} 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="statut" header="Statut" body={statutBodyTemplate} sortable style={{ width: '8rem' }} />
                        <Column field="problemeSignale" header="Problème" body={problemeBodyTemplate} style={{ width: '15rem' }} />
                        <Column field="solutionApportee" header="Solution" body={solutionBodyTemplate} style={{ width: '15rem' }} />
                        <Column field="dateCreation" header="Dates" body={dateBodyTemplate} sortable style={{ width: '12rem' }} />
                        <Column field="technicienNom" header="Technicien" body={technicienBodyTemplate} style={{ width: '10rem' }} />
                        <Column field="coutEstime" header="Coût" body={coutBodyTemplate} sortable style={{ width: '8rem' }} />
                        <Column body={actionBodyTemplate} header="Actions" style={{ width: '14rem' }} />
                    </DataTable>
                </Card>
            </div>

            {/* Dialog Diagnostic */}
            <Dialog
                visible={diagnosticDialog}
                style={{ width: '50vw' }}
                header="Diagnostic de maintenance"
                modal
                onHide={() => setDiagnosticDialog(false)}
                footer={
                    <div>
                        <Button
                            label="Annuler"
                            icon="pi pi-times"
                            className="p-button-outlined"
                            onClick={() => setDiagnosticDialog(false)}
                        />
                        <Button
                            label="Sauvegarder"
                            icon="pi pi-check"
                            className="p-button-success"
                            onClick={sauvegarderDiagnostic}
                        />
                    </div>
                }
            >
                <div className="grid p-fluid">
                    <div className="col-12">
                        <label className="font-medium">Solution apportée *</label>
                        <InputTextarea
                            value={diagnostic.solutionApportee}
                            onChange={(e) => setDiagnostic({ ...diagnostic, solutionApportee: e.target.value })}
                            rows={3}
                            placeholder="Décrivez la solution mise en œuvre..."
                        />
                    </div>
                    <div className="col-12">
                        <label className="font-medium">Cause racine</label>
                        <InputTextarea
                            value={diagnostic.causeRacine}
                            onChange={(e) => setDiagnostic({ ...diagnostic, causeRacine: e.target.value })}
                            rows={2}
                            placeholder="Identifiez la cause racine du problème..."
                        />
                    </div>
                    <div className="col-12">
                        <label className="font-medium">Action préventive</label>
                        <InputTextarea
                            value={diagnostic.actionPreventive}
                            onChange={(e) => setDiagnostic({ ...diagnostic, actionPreventive: e.target.value })}
                            rows={2}
                            placeholder="Proposez une action pour éviter la récurrence..."
                        />
                    </div>
                </div>
            </Dialog>
        </div>
    );
};

export default MaintenanceCorrectivePage;
