'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 { Dialog } from 'primereact/dialog';
import { Rating } from 'primereact/rating';
import { InputTextarea } from 'primereact/inputtextarea';
import { chantierService } from '../../../../services/api';
import { formatDate, formatCurrency } from '../../../../utils/formatters';
import type { Chantier } from '../../../../types/btp';

const ChantiersTerminesPage = () => {
    const [chantiers, setChantiers] = useState<Chantier[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedChantiers, setSelectedChantiers] = useState<Chantier[]>([]);
    const [detailDialog, setDetailDialog] = useState(false);
    const [selectedChantier, setSelectedChantier] = useState<Chantier | null>(null);
    const [satisfaction, setSatisfaction] = useState(5);
    const [notes, setNotes] = useState('');
    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 terminés
            const chantiersTermines = data.filter(chantier => chantier.statut === 'TERMINE');
            setChantiers(chantiersTermines);
        } catch (error) {
            console.error('Erreur lors du chargement des chantiers:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les chantiers terminés',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

    const calculateDuration = (dateDebut: string | Date, dateFinReelle: string | Date) => {
        const start = new Date(dateDebut);
        const end = new Date(dateFinReelle);
        const diffTime = end.getTime() - start.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        return diffDays;
    };

    const calculateDelay = (dateFinPrevue: string | Date, dateFinReelle: string | Date) => {
        const planned = new Date(dateFinPrevue);
        const actual = new Date(dateFinReelle);
        const diffTime = actual.getTime() - planned.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        return diffDays;
    };

    const isOnTime = (dateFinPrevue: string | Date, dateFinReelle: string | Date) => {
        const delay = calculateDelay(dateFinPrevue, dateFinReelle);
        return delay <= 0;
    };

    const isOnBudget = (montantPrevu: number, montantReel: number) => {
        return montantReel <= montantPrevu;
    };

    const getBudgetVariance = (montantPrevu: number, montantReel: number) => {
        return ((montantReel - montantPrevu) / montantPrevu) * 100;
    };

    const viewDetails = (chantier: Chantier) => {
        setSelectedChantier(chantier);
        setSatisfaction(5);
        setNotes('');
        setDetailDialog(true);
    };

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

    const generateReport = () => {
        const totalProjects = chantiers.length;
        const onTimeProjects = chantiers.filter(c => 
            c.dateFinReelle && isOnTime(c.dateFinPrevue, c.dateFinReelle)
        ).length;
        const onBudgetProjects = chantiers.filter(c => 
            isOnBudget(c.montantPrevu || 0, c.montantReel || 0)
        ).length;
        
        const totalBudget = chantiers.reduce((sum, c) => sum + (c.montantPrevu || 0), 0);
        const totalCost = chantiers.reduce((sum, c) => sum + (c.montantReel || 0), 0);
        
        const report = `
=== RAPPORT CHANTIERS TERMINÉS ===
Nombre total de chantiers: ${totalProjects}
Chantiers dans les délais: ${onTimeProjects} (${Math.round(onTimeProjects/totalProjects*100)}%)
Chantiers dans le budget: ${onBudgetProjects} (${Math.round(onBudgetProjects/totalProjects*100)}%)
Budget total prévu: ${formatCurrency(totalBudget)}
Coût total réel: ${formatCurrency(totalCost)}
Variance budgétaire: ${formatCurrency(totalCost - totalBudget)} (${Math.round(((totalCost - totalBudget)/totalBudget)*100)}%)
        `;
        
        const blob = new Blob([report], { type: 'text/plain;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `rapport_chantiers_termines_${new Date().toISOString().split('T')[0]}.txt`;
        link.click();
        
        toast.current?.show({
            severity: 'success',
            summary: 'Rapport généré',
            detail: 'Le rapport a été téléchargé',
            life: 3000
        });
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="my-2 flex gap-2">
                <h5 className="m-0 flex align-items-center">Chantiers terminés ({chantiers.length})</h5>
                <Button 
                    label="Générer rapport" 
                    icon="pi pi-file-excel" 
                    severity="help" 
                    size="small"
                    onClick={generateReport}
                />
            </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-eye" 
                    rounded 
                    severity="info" 
                    size="small"
                    tooltip="Voir détails"
                    onClick={() => viewDetails(rowData)}
                />
                <Button 
                    icon="pi pi-file-pdf" 
                    rounded 
                    severity="help" 
                    size="small"
                    tooltip="Générer facture"
                    onClick={() => {
                        toast.current?.show({
                            severity: 'info',
                            summary: 'Info',
                            detail: `Génération de facture pour ${rowData.nom}`,
                            life: 3000
                        });
                    }}
                />
            </div>
        );
    };

    const statusBodyTemplate = (rowData: Chantier) => {
        const onTime = rowData.dateFinReelle && isOnTime(rowData.dateFinPrevue, rowData.dateFinReelle);
        const onBudget = isOnBudget(rowData.montantPrevu || 0, rowData.montantReel || 0);
        
        return (
            <div className="flex align-items-center gap-2">
                <Tag value="Terminé" severity="info" />
                {onTime && <Tag value="Dans les délais" severity="success" />}
                {!onTime && <Tag value="En retard" severity="warning" />}
                {onBudget && <Tag value="Budget respecté" severity="success" />}
                {!onBudget && <Tag value="Dépassement" severity="danger" />}
            </div>
        );
    };

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

    const durationBodyTemplate = (rowData: Chantier) => {
        if (!rowData.dateDebut || !rowData.dateFinReelle) return '';
        
        const duration = calculateDuration(rowData.dateDebut, rowData.dateFinReelle);
        const delay = calculateDelay(rowData.dateFinPrevue, rowData.dateFinReelle);
        
        return (
            <div>
                <div>{duration} jour{duration > 1 ? 's' : ''}</div>
                {delay > 0 && (
                    <small className="text-orange-500">
                        +{delay} jour{delay > 1 ? 's' : ''} de retard
                    </small>
                )}
                {delay < 0 && (
                    <small className="text-green-500">
                        {Math.abs(delay)} jour{Math.abs(delay) > 1 ? 's' : ''} d'avance
                    </small>
                )}
            </div>
        );
    };

    const budgetBodyTemplate = (rowData: Chantier) => {
        const prevu = rowData.montantPrevu || 0;
        const reel = rowData.montantReel || 0;
        const variance = getBudgetVariance(prevu, reel);
        const onBudget = isOnBudget(prevu, reel);
        
        return (
            <div>
                <div>Prévu: {formatCurrency(prevu)}</div>
                <div>Réel: {formatCurrency(reel)}</div>
                <small className={onBudget ? 'text-green-500' : 'text-red-500'}>
                    {variance > 0 ? '+' : ''}{variance.toFixed(1)}%
                </small>
            </div>
        );
    };

    const header = (
        <div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h5 className="m-0">Chantiers terminés - Historique</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 detailDialogFooter = (
        <>
            <Button 
                label="Fermer" 
                icon="pi pi-times" 
                text 
                onClick={() => setDetailDialog(false)} 
            />
        </>
    );

    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 terminé trouvé."
                        header={header}
                        responsiveLayout="scroll"
                        loading={loading}
                        sortField="dateFinReelle"
                        sortOrder={-1}
                    >
                        <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="dateFinReelle" header="Date de fin" body={(rowData) => formatDate(rowData.dateFinReelle)} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="duration" header="Durée réelle" body={durationBodyTemplate} headerStyle={{ minWidth: '10rem' }} />
                        <Column field="statut" header="Statut" body={statusBodyTemplate} headerStyle={{ minWidth: '15rem' }} />
                        <Column field="budget" header="Budget" body={budgetBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
                        <Column body={actionBodyTemplate} headerStyle={{ minWidth: '8rem' }} />
                    </DataTable>

                    <Dialog 
                        visible={detailDialog} 
                        style={{ width: '600px' }} 
                        header={`Détails - ${selectedChantier?.nom}`}
                        modal 
                        className="p-fluid" 
                        footer={detailDialogFooter} 
                        onHide={() => setDetailDialog(false)}
                    >
                        {selectedChantier && (
                            <div className="formgrid grid">
                                <div className="field col-12">
                                    <h3 className="text-primary">Informations générales</h3>
                                </div>
                                
                                <div className="field col-12 md:col-6">
                                    <label className="font-bold">Client:</label>
                                    <p>{selectedChantier.client ? `${selectedChantier.client.prenom} ${selectedChantier.client.nom}` : ''}</p>
                                </div>

                                <div className="field col-12 md:col-6">
                                    <label className="font-bold">Adresse:</label>
                                    <p>{selectedChantier.adresse}</p>
                                </div>

                                <div className="field col-12">
                                    <label className="font-bold">Description:</label>
                                    <p>{selectedChantier.description || 'Aucune description'}</p>
                                </div>

                                <div className="field col-12">
                                    <h3 className="text-primary">Planning</h3>
                                </div>

                                <div className="field col-12 md:col-4">
                                    <label className="font-bold">Date début:</label>
                                    <p>{formatDate(selectedChantier.dateDebut)}</p>
                                </div>

                                <div className="field col-12 md:col-4">
                                    <label className="font-bold">Date fin prévue:</label>
                                    <p>{formatDate(selectedChantier.dateFinPrevue)}</p>
                                </div>

                                <div className="field col-12 md:col-4">
                                    <label className="font-bold">Date fin réelle:</label>
                                    <p>{selectedChantier.dateFinReelle ? formatDate(selectedChantier.dateFinReelle) : 'Non définie'}</p>
                                </div>

                                <div className="field col-12">
                                    <h3 className="text-primary">Budget</h3>
                                </div>

                                <div className="field col-12 md:col-6">
                                    <label className="font-bold">Budget prévu:</label>
                                    <p>{formatCurrency(selectedChantier.montantPrevu || 0)}</p>
                                </div>

                                <div className="field col-12 md:col-6">
                                    <label className="font-bold">Coût réel:</label>
                                    <p>{formatCurrency(selectedChantier.montantReel || 0)}</p>
                                </div>

                                <div className="field col-12">
                                    <h3 className="text-primary">Évaluation</h3>
                                </div>

                                <div className="field col-12">
                                    <label className="font-bold">Satisfaction client:</label>
                                    <Rating 
                                        value={satisfaction} 
                                        onChange={(e) => setSatisfaction(e.value || 0)} 
                                        stars={5} 
                                        className="mt-2"
                                    />
                                </div>

                                <div className="field col-12">
                                    <label className="font-bold">Notes:</label>
                                    <InputTextarea 
                                        value={notes} 
                                        onChange={(e) => setNotes(e.target.value)} 
                                        rows={3} 
                                        placeholder="Notes sur le chantier..."
                                    />
                                </div>
                            </div>
                        )}
                    </Dialog>
                </Card>
            </div>
        </div>
    );
};

export default ChantiersTerminesPage;


