'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 { Calendar } from 'primereact/calendar';
import { chantierService } from '../../../../services/api';
import { formatDate, formatCurrency } from '../../../../utils/formatters';
import type { Chantier } from '../../../../types/btp';

const ChantiersPlanifiesPage = () => {
    const [chantiers, setChantiers] = useState<Chantier[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedChantiers, setSelectedChantiers] = useState<Chantier[]>([]);
    const [startDialog, setStartDialog] = useState(false);
    const [selectedChantier, setSelectedChantier] = useState<Chantier | null>(null);
    const [startDate, setStartDate] = useState<Date>(new Date());
    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 planifiés
            const chantiersPlanifies = data.filter(chantier => chantier.statut === 'PLANIFIE');
            setChantiers(chantiersPlanifies);
        } catch (error) {
            console.error('Erreur lors du chargement des chantiers:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les chantiers planifiés',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

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

    const isStartingSoon = (dateDebut: string | Date) => {
        const days = getDaysUntilStart(dateDebut);
        return days >= 0 && days <= 7; // Dans les 7 prochains jours
    };

    const isOverdue = (dateDebut: string | Date) => {
        const days = getDaysUntilStart(dateDebut);
        return days < 0; // Date de début dépassée
    };

    const startChantier = (chantier: Chantier) => {
        setSelectedChantier(chantier);
        setStartDate(new Date());
        setStartDialog(true);
    };

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

        try {
            const updatedChantier = {
                ...selectedChantier,
                statut: 'EN_COURS' as any,
                dateDebut: startDate.toISOString().split('T')[0]
            };

            await chantierService.update(selectedChantier.id, updatedChantier);
            
            // Retirer le chantier de la liste car il n'est plus "planifié"
            setChantiers(prev => prev.filter(c => c.id !== selectedChantier.id));
            setStartDialog(false);
            
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: 'Chantier démarré avec succès',
                life: 3000
            });
        } catch (error) {
            console.error('Erreur lors du démarrage:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de démarrer le chantier',
                life: 3000
            });
        }
    };

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

    const bulkStart = async () => {
        if (selectedChantiers.length === 0) {
            toast.current?.show({
                severity: 'warn',
                summary: 'Attention',
                detail: 'Veuillez sélectionner au moins un chantier',
                life: 3000
            });
            return;
        }

        try {
            await Promise.all(
                selectedChantiers.map(chantier => 
                    chantierService.update(chantier.id, {
                        ...chantier,
                        statut: 'EN_COURS' as any,
                        dateDebut: new Date().toISOString().split('T')[0]
                    })
                )
            );

            setChantiers(prev => prev.filter(c => !selectedChantiers.includes(c)));
            setSelectedChantiers([]);
            
            toast.current?.show({
                severity: 'success',
                summary: 'Succès',
                detail: `${selectedChantiers.length} chantier(s) démarré(s)`,
                life: 3000
            });
        } catch (error) {
            console.error('Erreur lors du démarrage en lot:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de démarrer les chantiers sélectionnés',
                life: 3000
            });
        }
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="my-2 flex gap-2">
                <h5 className="m-0 flex align-items-center">Chantiers planifiés ({chantiers.length})</h5>
                <Button 
                    label="Démarrer sélection" 
                    icon="pi pi-play" 
                    severity="success" 
                    size="small"
                    onClick={bulkStart}
                    disabled={selectedChantiers.length === 0}
                />
            </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-play" 
                    rounded 
                    severity="success" 
                    size="small"
                    tooltip="Démarrer le chantier"
                    onClick={() => startChantier(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 overdue = isOverdue(rowData.dateDebut);
        const startingSoon = isStartingSoon(rowData.dateDebut);
        
        return (
            <div className="flex align-items-center gap-2">
                <Tag value="Planifié" severity="info" />
                {overdue && <Tag value="En retard" severity="danger" />}
                {startingSoon && !overdue && <Tag value="Bientôt" severity="warning" />}
            </div>
        );
    };

    const dateDebutBodyTemplate = (rowData: Chantier) => {
        const overdue = isOverdue(rowData.dateDebut);
        const startingSoon = isStartingSoon(rowData.dateDebut);
        const days = getDaysUntilStart(rowData.dateDebut);
        
        let className = '';
        let icon = '';
        let suffix = '';
        
        if (overdue) {
            className = 'text-red-500 font-bold';
            icon = 'pi pi-exclamation-triangle';
            suffix = ` (${Math.abs(days)} jour${Math.abs(days) > 1 ? 's' : ''} de retard)`;
        } else if (startingSoon) {
            className = 'text-orange-500 font-bold';
            icon = 'pi pi-clock';
            suffix = ` (dans ${days} jour${days > 1 ? 's' : ''})`;
        } else if (days > 0) {
            suffix = ` (dans ${days} jour${days > 1 ? 's' : ''})`;
        }
        
        return (
            <div className={className}>
                {icon && <i className={`${icon} mr-1`}></i>}
                {formatDate(rowData.dateDebut)}
                <small className="block text-600">{suffix}</small>
            </div>
        );
    };

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

    const durationBodyTemplate = (rowData: Chantier) => {
        if (!rowData.dateDebut || !rowData.dateFinPrevue) return '';
        
        const start = new Date(rowData.dateDebut);
        const end = new Date(rowData.dateFinPrevue);
        const diffTime = end.getTime() - start.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        return `${diffDays} jour${diffDays > 1 ? 's' : ''}`;
    };

    const header = (
        <div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h5 className="m-0">Chantiers en attente de démarrage</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 startDialogFooter = (
        <>
            <Button 
                label="Annuler" 
                icon="pi pi-times" 
                text 
                onClick={() => setStartDialog(false)} 
            />
            <Button 
                label="Démarrer" 
                icon="pi pi-play" 
                text 
                onClick={handleStartChantier} 
            />
        </>
    );

    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 planifié trouvé."
                        header={header}
                        responsiveLayout="scroll"
                        loading={loading}
                        sortField="dateDebut"
                        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="adresse" header="Adresse" sortable headerStyle={{ minWidth: '12rem' }} />
                        <Column field="dateDebut" header="Date de début prévue" body={dateDebutBodyTemplate} sortable headerStyle={{ minWidth: '14rem' }} />
                        <Column field="dateFinPrevue" header="Date de fin prévue" body={(rowData) => formatDate(rowData.dateFinPrevue)} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column field="duration" header="Durée" body={durationBodyTemplate} headerStyle={{ minWidth: '8rem' }} />
                        <Column field="statut" header="Statut" body={statusBodyTemplate} headerStyle={{ minWidth: '12rem' }} />
                        <Column field="montantPrevu" header="Budget prévu" body={(rowData) => formatCurrency(rowData.montantPrevu)} sortable headerStyle={{ minWidth: '10rem' }} />
                        <Column body={actionBodyTemplate} headerStyle={{ minWidth: '8rem' }} />
                    </DataTable>

                    <Dialog 
                        visible={startDialog} 
                        style={{ width: '450px' }} 
                        header="Démarrer le chantier" 
                        modal 
                        className="p-fluid" 
                        footer={startDialogFooter} 
                        onHide={() => setStartDialog(false)}
                    >
                        <div className="formgrid grid">
                            <div className="field col-12">
                                <p>
                                    Confirmer le démarrage du chantier <strong>{selectedChantier?.nom}</strong> ?
                                </p>
                            </div>
                            
                            <div className="field col-12">
                                <label htmlFor="startDate">Date de démarrage effectif</label>
                                <Calendar 
                                    id="startDate" 
                                    value={startDate} 
                                    onChange={(e) => setStartDate(e.value || new Date())} 
                                    dateFormat="dd/mm/yy" 
                                    showIcon 
                                />
                            </div>
                        </div>
                    </Dialog>
                </Card>
            </div>
        </div>
    );
};

export default ChantiersPlanifiesPage;


