'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 { InputText } from 'primereact/inputtext';
import { Card } from 'primereact/card';
import { Toast } from 'primereact/toast';
import { Toolbar } from 'primereact/toolbar';
import { Tag } from 'primereact/tag';
import { ProgressBar } from 'primereact/progressbar';
import { Dialog } from 'primereact/dialog';
import { Calendar } from 'primereact/calendar';
import { InputNumber } from 'primereact/inputnumber';
import { chantierService } from '../../../../services/api';
import { formatDate, formatCurrency } from '../../../../utils/formatters';
import type { Chantier, StatutChantier } from '../../../../types/btp';

const ChantiersEnCoursPage = () => {
    const [chantiers, setChantiers] = useState<Chantier[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedChantiers, setSelectedChantiers] = useState<Chantier[]>([]);
    const [updateDialog, setUpdateDialog] = useState(false);
    const [selectedChantier, setSelectedChantier] = useState<Chantier | null>(null);
    const [updateData, setUpdateData] = useState({ dateFinReelle: null, montantReel: 0 });
    const toast = useRef<Toast>(null);
    const dt = useRef<DataTable<Chantier[]>>(null);

    useEffect(() => {
        loadChantiers();
    }, []);

    const loadChantiers = async () => {
        try {
            setLoading(true);
            const data = await chantierService.getAll();
            // Filtrer seulement les chantiers en cours
            const chantiersEnCours = data.filter(chantier => chantier.statut === 'EN_COURS');
            setChantiers(chantiersEnCours);
        } catch (error) {
            console.error('Erreur lors du chargement des chantiers:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les chantiers en cours',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

    const calculateProgress = (chantier: Chantier) => {
        if (!chantier.dateDebut || !chantier.dateFinPrevue) return 0;
        
        const now = new Date();
        const start = new Date(chantier.dateDebut);
        const end = new Date(chantier.dateFinPrevue);
        const totalDays = (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
        const elapsedDays = (now.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
        
        return Math.min(Math.max((elapsedDays / totalDays) * 100, 0), 100);
    };

    const isLate = (chantier: Chantier) => {
        if (!chantier.dateFinPrevue) return false;
        const today = new Date();
        const endDate = new Date(chantier.dateFinPrevue);
        return today > endDate;
    };

    const markAsCompleted = (chantier: Chantier) => {
        setSelectedChantier(chantier);
        setUpdateData({
            dateFinReelle: new Date(),
            montantReel: chantier.montantReel || chantier.montantPrevu || 0
        });
        setUpdateDialog(true);
    };

    const handleCompleteChantier = async () => {
        if (!selectedChantier) return;

        try {
            const updatedChantier = {
                ...selectedChantier,
                statut: 'TERMINE' as StatutChantier,
                dateFinReelle: updateData.dateFinReelle,
                montantReel: updateData.montantReel
            };

            await chantierService.update(selectedChantier.id, updatedChantier);
            
            // Retirer le chantier de la liste car il n'est plus "en cours"
            setChantiers(prev => prev.filter(c => c.id !== selectedChantier.id));
            setUpdateDialog(false);
            
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Chantier marqué comme terminé',
                life: 3000
            });
        } catch (error) {
            console.error('Erreur lors de la mise à jour:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de mettre à jour le chantier',
                life: 3000
            });
        }
    };

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

    const leftToolbarTemplate = () => {
        return (
            <div className="my-2">
                <h5 className="m-0">Chantiers en cours ({chantiers.length})</h5>
            </div>
        );
    };

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

    const actionBodyTemplate = (rowData: Chantier) => {
        return (
            <div className="flex gap-2">
                <Button 
                    icon="pi pi-check" 
                    rounded 
                    severity="success" 
                    size="small"
                    tooltip="Marquer comme terminé"
                    onClick={() => markAsCompleted(rowData)}
                />
                <Button 
                    icon="pi pi-eye" 
                    rounded 
                    severity="info" 
                    size="small"
                    tooltip="Voir détails"
                    onClick={() => {
                        toast.current?.show({
                            severity: 'info',
                            summary: 'Info',
                            detail: `Détails du chantier ${rowData.nom}`,
                            life: 3000
                        });
                    }}
                />
            </div>
        );
    };

    const statusBodyTemplate = (rowData: Chantier) => {
        const late = isLate(rowData);
        return (
            <div className="flex align-items-center gap-2">
                <Tag value="En cours" severity="success" />
                {late && <Tag value="En retard" severity="danger" />}
            </div>
        );
    };

    const progressBodyTemplate = (rowData: Chantier) => {
        const progress = calculateProgress(rowData);
        const late = isLate(rowData);
        
        return (
            <div className="flex align-items-center gap-2">
                <ProgressBar 
                    value={progress} 
                    style={{ height: '6px', width: '100px' }}
                    color={late ? '#ef4444' : undefined}
                />
                <span className={`text-sm ${late ? 'text-red-500' : ''}`}>
                    {Math.round(progress)}%
                </span>
            </div>
        );
    };

    const clientBodyTemplate = (rowData: Chantier) => {
        if (!rowData.client) return '';
        return `${rowData.client.prenom} ${rowData.client.nom}`;
    };

    const dateBodyTemplate = (rowData: Chantier, field: string) => {
        const date = (rowData as any)[field];
        const late = field === 'dateFinPrevue' && isLate(rowData);
        
        return (
            <span className={late ? 'text-red-500 font-bold' : ''}>
                {date ? formatDate(date) : ''}
                {late && <i className="pi pi-exclamation-triangle ml-1"></i>}
            </span>
        );
    };

    const budgetBodyTemplate = (rowData: Chantier) => {
        const prevu = rowData.montantPrevu || 0;
        const reel = rowData.montantReel || 0;
        const progress = calculateProgress(rowData);
        const estimated = prevu * (progress / 100);
        
        return (
            <div className="text-sm">
                <div>Prévu: {formatCurrency(prevu)}</div>
                <div className="text-600">Estimé: {formatCurrency(estimated)}</div>
            </div>
        );
    };

    const header = (
        <div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h5 className="m-0">Chantiers en cours de réalisation</h5>
            <span className="block mt-2 md:mt-0 p-input-icon-left">
                <i className="pi pi-search" />
                <InputText 
                    type="search" 
                    placeholder="Rechercher..." 
                    onInput={(e) => setGlobalFilter(e.currentTarget.value)} 
                />
            </span>
        </div>
    );

    const completeDialogFooter = (
        <>
            <Button 
                label="Annuler" 
                icon="pi pi-times" 
                text 
                onClick={() => setUpdateDialog(false)} 
            />
            <Button 
                label="Marquer comme terminé" 
                icon="pi pi-check" 
                text 
                onClick={handleCompleteChantier} 
            />
        </>
    );

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

                    <DataTable
                        ref={dt}
                        value={chantiers}
                        selection={selectedChantiers}
                        onSelectionChange={(e) => setSelectedChantiers(e.value)}
                        selectionMode="multiple"
                        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} chantiers"
                        globalFilter={globalFilter}
                        emptyMessage="Aucun chantier en cours trouvé."
                        header={header}
                        responsiveLayout="scroll"
                        loading={loading}
                    >
                        <Column selectionMode="multiple" headerStyle={{ width: '4rem' }} />
                        <Column field="nom" header="Nom" sortable headerStyle={{ minWidth: '12rem' }} />
                        <Column field="client" header="Client" body={clientBodyTemplate} sortable headerStyle={{ minWidth: '12rem' }} />
                        <Column field="adresse" header="Adresse" sortable headerStyle={{ minWidth: '12rem' }} />
                        <Column field="dateDebut" header="Date début" body={(rowData) => dateBodyTemplate(rowData, 'dateDebut')} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="dateFinPrevue" header="Date fin prévue" body={(rowData) => dateBodyTemplate(rowData, 'dateFinPrevue')} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="statut" header="Statut" body={statusBodyTemplate} headerStyle={{ minWidth: '10rem' }} />
                        <Column field="progress" header="Progression" body={progressBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
                        <Column field="budget" header="Budget" body={budgetBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
                        <Column body={actionBodyTemplate} headerStyle={{ minWidth: '8rem' }} />
                    </DataTable>

                    <Dialog 
                        visible={updateDialog} 
                        style={{ width: '450px' }} 
                        header="Finaliser le chantier" 
                        modal 
                        className="p-fluid" 
                        footer={completeDialogFooter} 
                        onHide={() => setUpdateDialog(false)}
                    >
                        <div className="formgrid grid">
                            <div className="field col-12">
                                <label htmlFor="dateFinReelle">Date de fin réelle</label>
                                <Calendar 
                                    id="dateFinReelle" 
                                    value={updateData.dateFinReelle} 
                                    onChange={(e) => setUpdateData(prev => ({ ...prev, dateFinReelle: e.value }))} 
                                    dateFormat="dd/mm/yy" 
                                    showIcon 
                                />
                            </div>

                            <div className="field col-12">
                                <label htmlFor="montantReel">Montant réel (€)</label>
                                <InputNumber 
                                    id="montantReel" 
                                    value={updateData.montantReel} 
                                    onValueChange={(e) => setUpdateData(prev => ({ ...prev, montantReel: e.value || 0 }))} 
                                    mode="currency" 
                                    currency="EUR" 
                                    locale="fr-FR" 
                                />
                            </div>
                        </div>
                    </Dialog>
                </Card>
            </div>
        </div>
    );
};

export default ChantiersEnCoursPage;



