'use client';

export const dynamic = 'force-dynamic';

import React, { useState, useEffect, useRef } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { Dropdown } from 'primereact/dropdown';
import { Card } from 'primereact/card';
import { Toast } from 'primereact/toast';
import { Tag } from 'primereact/tag';
import { Toolbar } from 'primereact/toolbar';
import { materielService } from '../../../../services/api';
import { Materiel, TypeMateriel, StatutMateriel } from '../../../../types/btp';
import { formatCurrency } from '../../../../utils/formatters';

const MaterielsByTypePage = () => {
    const [materiels, setMateriels] = useState<Materiel[]>([]);
    const [selectedType, setSelectedType] = useState<TypeMateriel>(TypeMateriel.VEHICULE);
    const [loading, setLoading] = useState(true);
    const toast = useRef<Toast>(null);
    const dt = useRef<DataTable<Materiel[]>>(null);

    const typeOptions = Object.values(TypeMateriel).map(type => ({
        label: type.replace('_', ' '),
        value: type
    }));

    useEffect(() => {
        if (selectedType) {
            loadMaterielsByType();
        }
    }, [selectedType]);

    const loadMaterielsByType = async () => {
        try {
            setLoading(true);
            const data = await materielService.getByType(selectedType);
            setMateriels(data);
        } catch (error) {
            console.error('Erreur lors du chargement:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les matériels',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

    const exportCSV = () => {
        dt.current?.exportCSV();
    };

    const statutBodyTemplate = (rowData: Materiel) => {
        const getStatutSeverity = (statut?: StatutMateriel) => {
            switch (statut) {
                case StatutMateriel.DISPONIBLE:
                    return 'success';
                case StatutMateriel.UTILISE:
                    return 'warning';
                case StatutMateriel.MAINTENANCE:
                    return 'info';
                case StatutMateriel.HORS_SERVICE:
                    return 'danger';
                default:
                    return undefined;
            }
        };

        return (
            <Tag 
                value={rowData.statut?.replace('_', ' ')} 
                severity={getStatutSeverity(rowData.statut)} 
            />
        );
    };

    const valeurBodyTemplate = (rowData: Materiel) => {
        return formatCurrency(rowData.valeurActuelle || rowData.valeurAchat);
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="flex align-items-center gap-2">
                <h4 className="m-0">Matériels par Type</h4>
                <Dropdown
                    value={selectedType}
                    onChange={(e) => setSelectedType(e.value)}
                    options={typeOptions}
                    placeholder="Sélectionner un type"
                />
                <span className="text-500">({materiels.length} matériels)</span>
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <Button 
                label="Exporter" 
                icon="pi pi-upload" 
                severity="help" 
                className="p-button-text p-button-rounded"
                onClick={exportCSV} 
            />
        );
    };

    // Statistiques par statut
    const stats = materiels.reduce((acc, materiel) => {
        acc[materiel.statut] = (acc[materiel.statut] || 0) + 1;
        return acc;
    }, {} as Record<StatutMateriel, number>);

    return (
        <div className="grid">
            <div className="col-12">
                <Toast ref={toast} />

                {/* Cards de statistiques */}
                <div className="grid mb-4">
                    <div className="col-12 md:col-3">
                        <Card>
                            <div className="flex align-items-center">
                                <div className="mr-3">
                                    <i className="pi pi-check-circle text-green-500 text-3xl"></i>
                                </div>
                                <div>
                                    <div className="text-2xl font-semibold">
                                        {stats[StatutMateriel.DISPONIBLE] || 0}
                                    </div>
                                    <div className="text-500">Disponibles</div>
                                </div>
                            </div>
                        </Card>
                    </div>
                    
                    <div className="col-12 md:col-3">
                        <Card>
                            <div className="flex align-items-center">
                                <div className="mr-3">
                                    <i className="pi pi-play-circle text-orange-500 text-3xl"></i>
                                </div>
                                <div>
                                    <div className="text-2xl font-semibold">
                                        {stats[StatutMateriel.UTILISE] || 0}
                                    </div>
                                    <div className="text-500">En utilisation</div>
                                </div>
                            </div>
                        </Card>
                    </div>
                    
                    <div className="col-12 md:col-3">
                        <Card>
                            <div className="flex align-items-center">
                                <div className="mr-3">
                                    <i className="pi pi-wrench text-blue-500 text-3xl"></i>
                                </div>
                                <div>
                                    <div className="text-2xl font-semibold">
                                        {stats[StatutMateriel.MAINTENANCE] || 0}
                                    </div>
                                    <div className="text-500">En maintenance</div>
                                </div>
                            </div>
                        </Card>
                    </div>
                    
                    <div className="col-12 md:col-3">
                        <Card>
                            <div className="flex align-items-center">
                                <div className="mr-3">
                                    <i className="pi pi-times-circle text-red-500 text-3xl"></i>
                                </div>
                                <div>
                                    <div className="text-2xl font-semibold">
                                        {stats[StatutMateriel.HORS_SERVICE] || 0}
                                    </div>
                                    <div className="text-500">Hors service</div>
                                </div>
                            </div>
                        </Card>
                    </div>
                </div>

                <div className="card">
                    <Toolbar 
                        className="mb-4" 
                        left={leftToolbarTemplate} 
                        right={rightToolbarTemplate}
                    />

                    <DataTable
                        ref={dt}
                        value={materiels}
                        loading={loading}
                        paginator
                        rows={10}
                        rowsPerPageOptions={[5, 10, 25]}
                        paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                        currentPageReportTemplate="Affichage {first} à {last} de {totalRecords} matériels"
                        emptyMessage="Aucun matériel trouvé pour ce type."
                        sortField="nom"
                        sortOrder={1}
                    >
                        <Column field="nom" header="Nom" sortable />
                        <Column field="marque" header="Marque" sortable />
                        <Column field="modele" header="Modèle" sortable />
                        <Column field="numeroSerie" header="N° Série" />
                        <Column field="statut" header="Statut" body={statutBodyTemplate} sortable />
                        <Column field="localisation" header="Localisation" sortable />
                        <Column field="valeurActuelle" header="Valeur" body={valeurBodyTemplate} sortable />
                    </DataTable>
                </div>
            </div>
        </div>
    );
};

export default MaterielsByTypePage;