'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 { Toast } from 'primereact/toast';
import { Dialog } from 'primereact/dialog';
import { InputText } from 'primereact/inputtext';
import { Dropdown } from 'primereact/dropdown';
import { Calendar } from 'primereact/calendar';
import { Slider } from 'primereact/slider';
import { Tag } from 'primereact/tag';
import { Card } from 'primereact/card';
import { ProgressBar } from 'primereact/progressbar';
import { Toolbar } from 'primereact/toolbar';
import { Badge } from 'primereact/badge';
import { Divider } from 'primereact/divider';
import { InputTextarea } from 'primereact/inputtextarea';
import { InputNumber } from 'primereact/inputnumber';
import { confirmDialog } from 'primereact/confirmdialog';
import { ConfirmDialog } from 'primereact/confirmdialog';
import { Page } from '@/types';
import phaseChantierService from '@/services/phaseChantierService';
import { PhaseChantier, StatutPhase } from '@/types/btp-extended';
import { 
    ActionButtonGroup, 
    ViewButton, 
    EditButton, 
    DeleteButton,
    StartButton
} from '../../../components/ui/ActionButton';

const PhasesChantierPage: Page = () => {
    const [phases, setPhases] = useState<PhaseChantier[]>([]);
    const [loading, setLoading] = useState(true);
    const [selectedPhases, setSelectedPhases] = useState<PhaseChantier[]>([]);
    const [phaseDialog, setPhaseDialog] = useState(false);
    const [deletePhaseDialog, setDeletePhaseDialog] = useState(false);
    const [currentPhase, setCurrentPhase] = useState<PhaseChantier | null>(null);
    const [submitted, setSubmitted] = useState(false);
    const [globalFilter, setGlobalFilter] = useState('');
    const [expandedRows, setExpandedRows] = useState<any>(null);
    const [filters, setFilters] = useState({
        statut: '',
        chantierId: '',
        enRetard: false
    });

    const toast = useRef<Toast>(null);
    const dt = useRef<DataTable<PhaseChantier[]>>(null);

    // État pour le formulaire de phase
    const [formData, setFormData] = useState({
        nom: '',
        description: '',
        dateDebutPrevue: null as Date | null,
        dateFinPrevue: null as Date | null,
        budgetPrevu: 0,
        statut: 'PLANIFIEE' as StatutPhase,
        critique: false,
        notes: '',
        ordreExecution: 1
    });

    const statutOptions = [
        { label: 'Planifiée', value: 'PLANIFIEE' },
        { label: 'En attente', value: 'EN_ATTENTE' },
        { label: 'En cours', value: 'EN_COURS' },
        { label: 'En pause', value: 'EN_PAUSE' },
        { label: 'Terminée', value: 'TERMINEE' },
        { label: 'Annulée', value: 'ANNULEE' },
        { label: 'En retard', value: 'EN_RETARD' }
    ];

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

    const loadPhases = async () => {
        try {
            setLoading(true);
            // Pour l'exemple, on charge toutes les phases. 
            // En production, on pourrait charger par chantier spécifique
            const data = await phaseChantierService.getByChantier(1); // ID exemple
            setPhases(data || []);
        } catch (error) {
            console.error('Erreur lors du chargement des phases:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de charger les phases',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

    const openNew = () => {
        setCurrentPhase(null);
        setFormData({
            nom: '',
            description: '',
            dateDebutPrevue: null,
            dateFinPrevue: null,
            budgetPrevu: 0,
            statut: 'PLANIFIEE',
            critique: false,
            notes: '',
            ordreExecution: 1
        });
        setSubmitted(false);
        setPhaseDialog(true);
    };

    const editPhase = (phase: PhaseChantier) => {
        setCurrentPhase(phase);
        setFormData({
            nom: phase.nom || '',
            description: phase.description || '',
            dateDebutPrevue: phase.dateDebutPrevue ? new Date(phase.dateDebutPrevue) : null,
            dateFinPrevue: phase.dateFinPrevue ? new Date(phase.dateFinPrevue) : null,
            budgetPrevu: phase.budgetPrevu || 0,
            statut: phase.statut,
            critique: phase.critique || false,
            notes: phase.notes || '',
            ordreExecution: phase.ordreExecution || 1
        });
        setSubmitted(false);
        setPhaseDialog(true);
    };

    const confirmDeletePhase = (phase: PhaseChantier) => {
        setCurrentPhase(phase);
        setDeletePhaseDialog(true);
    };

    const deletePhase = async () => {
        try {
            if (currentPhase?.id) {
                await phaseChantierService.delete(Number(currentPhase.id));
                await loadPhases();
                toast.current?.show({
                    severity: 'success',
                    summary: 'Succès',
                    detail: 'Phase supprimée avec succès',
                    life: 3000
                });
            }
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de la suppression',
                life: 3000
            });
        }
        setDeletePhaseDialog(false);
        setCurrentPhase(null);
    };

    const hideDialog = () => {
        setSubmitted(false);
        setPhaseDialog(false);
    };

    const hideDeleteDialog = () => {
        setDeletePhaseDialog(false);
    };

    const savePhase = async () => {
        setSubmitted(true);

        if (formData.nom.trim()) {
            try {
                const phaseData = {
                    ...formData,
                    dateDebutPrevue: formData.dateDebutPrevue?.toISOString(),
                    dateFinPrevue: formData.dateFinPrevue?.toISOString(),
                    chantierId: '1', // ID exemple - en production, viendrait du contexte
                    ordreExecution: formData.ordreExecution || 1
                };

                if (currentPhase?.id) {
                    await phaseChantierService.update(Number(currentPhase.id), phaseData);
                } else {
                    await phaseChantierService.create(phaseData);
                }

                await loadPhases();
                hideDialog();
                toast.current?.show({
                    severity: 'success',
                    summary: 'Succès',
                    detail: currentPhase ? 'Phase modifiée avec succès' : 'Phase créée avec succès',
                    life: 3000
                });
            } catch (error) {
                toast.current?.show({
                    severity: 'error',
                    summary: 'Erreur',
                    detail: 'Erreur lors de la sauvegarde',
                    life: 3000
                });
            }
        }
    };

    const onInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, name: string) => {
        const val = e.target.value || '';
        setFormData(prev => ({ ...prev, [name]: val }));
    };

    const onNumberInputChange = (value: number | null, name: string) => {
        setFormData(prev => ({ ...prev, [name]: value || 0 }));
    };

    const onDateChange = (value: Date | null, name: string) => {
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const onDropdownChange = (e: any, name: string) => {
        setFormData(prev => ({ ...prev, [name]: e.value }));
    };

    // Actions sur les phases
    const startPhase = async (phase: PhaseChantier) => {
        try {
            if (phase.id) {
                await phaseChantierService.start(Number(phase.id));
                await loadPhases();
                toast.current?.show({
                    severity: 'success',
                    summary: 'Succès',
                    detail: 'Phase démarrée',
                    life: 3000
                });
            }
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors du démarrage',
                life: 3000
            });
        }
    };

    const completePhase = async (phase: PhaseChantier) => {
        try {
            if (phase.id) {
                await phaseChantierService.complete(Number(phase.id));
                await loadPhases();
                toast.current?.show({
                    severity: 'success',
                    summary: 'Succès',
                    detail: 'Phase terminée',
                    life: 3000
                });
            }
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de la finalisation',
                life: 3000
            });
        }
    };

    const suspendPhase = async (phase: PhaseChantier) => {
        try {
            if (phase.id) {
                await phaseChantierService.suspend(Number(phase.id));
                await loadPhases();
                toast.current?.show({
                    severity: 'success',
                    summary: 'Succès',
                    detail: 'Phase suspendue',
                    life: 3000
                });
            }
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Erreur lors de la suspension',
                life: 3000
            });
        }
    };

    // Templates pour les colonnes
    const actionBodyTemplate = (rowData: PhaseChantier) => {
        return (
            <ActionButtonGroup>
                <EditButton
                    onClick={() => editPhase(rowData)}
                    tooltip="Modifier"
                />
                <DeleteButton
                    onClick={() => confirmDeletePhase(rowData)}
                    tooltip="Supprimer"
                />
                {rowData.statut === 'PLANIFIEE' && (
                    <StartButton
                        onClick={() => startPhase(rowData)}
                        tooltip="Démarrer"
                    />
                )}
                {rowData.statut === 'EN_COURS' && (
                    <>
                        <Button
                            icon="pi pi-pause"
                            rounded
                            severity="warning"
                            onClick={() => suspendPhase(rowData)}
                            tooltip="Suspendre"
                        />
                        <Button
                            icon="pi pi-check"
                            rounded
                            severity="success"
                            onClick={() => completePhase(rowData)}
                            tooltip="Terminer"
                        />
                    </>
                )}
            </ActionButtonGroup>
        );
    };

    const statutBodyTemplate = (rowData: PhaseChantier) => {
        const severity = phaseChantierService.getStatutColor(rowData.statut);
        const label = phaseChantierService.getStatutLabel(rowData.statut);
        
        return (
            <Tag 
                value={label} 
                style={{ backgroundColor: severity }}
                className="text-white"
            />
        );
    };

    const avancementBodyTemplate = (rowData: PhaseChantier) => {
        const value = rowData.pourcentageAvancement || 0;
        return (
            <div className="flex align-items-center gap-2">
                <ProgressBar 
                    value={value} 
                    className="w-8rem"
                    style={{ height: '0.5rem' }}
                />
                <span className="text-sm">{value.toFixed(1)}%</span>
            </div>
        );
    };

    const dateBodyTemplate = (date: string | null) => {
        return date ? new Date(date).toLocaleDateString('fr-FR') : '-';
    };

    const budgetBodyTemplate = (value: number) => {
        return new Intl.NumberFormat('fr-FR', {
            style: 'currency',
            currency: 'EUR'
        }).format(value || 0);
    };

    const retardBodyTemplate = (rowData: PhaseChantier) => {
        const isEnRetard = phaseChantierService.isEnRetard(rowData);
        if (!isEnRetard) return null;
        
        const retard = phaseChantierService.calculateRetard(rowData);
        return (
            <Badge
                value={`${retard}j`}
                severity="danger"
            />
        );
    };

    // Template pour les détails expandables
    const rowExpansionTemplate = (data: PhaseChantier) => {
        return (
            <div className="p-3">
                <h5>Détails de la phase: {data.nom}</h5>
                <div className="grid">
                    <div className="col-12 md:col-6">
                        <p><strong>Description:</strong> {data.description || 'Aucune description'}</p>
                        <p><strong>Prérequis:</strong> {data.prerequis || 'Aucun'}</p>
                        <p><strong>Livrables:</strong> {data.livrables || 'Non définis'}</p>
                    </div>
                    <div className="col-12 md:col-6">
                        <p><strong>Risques:</strong> {data.risques || 'Non identifiés'}</p>
                        <p><strong>Notes:</strong> {data.notes || 'Aucune note'}</p>
                        <p><strong>Phase critique:</strong> {data.critique ? 'Oui' : 'Non'}</p>
                    </div>
                </div>
            </div>
        );
    };

    // Statistiques rapides
    const stats = phaseChantierService.calculateStatistiques(phases);

    const leftToolbarTemplate = () => {
        return (
            <div className="flex flex-wrap gap-2">
                <Button 
                    label="Nouvelle Phase" 
                    icon="pi pi-plus" 
                    severity="success" 
                    onClick={openNew}
                />
                <Button 
                    label="Phases en Retard" 
                    icon="pi pi-exclamation-triangle" 
                    severity="warning" 
                    onClick={() => {/* TODO: Filtrer les phases en retard */}}
                />
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <div className="flex align-items-center gap-2">
                <span className="p-input-icon-left">
                    <i className="pi pi-search" />
                    <InputText
                        type="search"
                        placeholder="Rechercher..."
                        onInput={(e) => setGlobalFilter(e.currentTarget.value)}
                    />
                </span>
                <Button 
                    icon="pi pi-refresh" 
                    onClick={loadPhases} 
                    tooltip="Actualiser"
                />
            </div>
        );
    };

    return (
        <div className="grid">
            <div className="col-12">
                <Toast ref={toast} />
                <ConfirmDialog />
                
                {/* Statistiques rapides */}
                <div className="grid mb-4">
                    <div className="col-12 md:col-3">
                        <Card>
                            <div className="text-center">
                                <div className="text-2xl font-bold text-primary">{stats.total}</div>
                                <div className="text-sm text-color-secondary">Total phases</div>
                            </div>
                        </Card>
                    </div>
                    <div className="col-12 md:col-3">
                        <Card>
                            <div className="text-center">
                                <div className="text-2xl font-bold text-green-500">{stats.terminees}</div>
                                <div className="text-sm text-color-secondary">Terminées</div>
                            </div>
                        </Card>
                    </div>
                    <div className="col-12 md:col-3">
                        <Card>
                            <div className="text-center">
                                <div className="text-2xl font-bold text-blue-500">{stats.enCours}</div>
                                <div className="text-sm text-color-secondary">En cours</div>
                            </div>
                        </Card>
                    </div>
                    <div className="col-12 md:col-3">
                        <Card>
                            <div className="text-center">
                                <div className="text-2xl font-bold text-red-500">{stats.enRetard}</div>
                                <div className="text-sm text-color-secondary">En retard</div>
                            </div>
                        </Card>
                    </div>
                </div>

                <Card title="Gestion des Phases de Chantier">
                    <Toolbar className="mb-4" left={leftToolbarTemplate} right={rightToolbarTemplate} />

                    <DataTable
                        ref={dt}
                        value={phases}
                        selection={selectedPhases}
                        onSelectionChange={(e) => setSelectedPhases(e.value as PhaseChantier[])}
                        selectionMode="checkbox"
                        dataKey="id"
                        paginator
                        rows={10}
                        rowsPerPageOptions={[5, 10, 25]}
                        paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                        currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} phases"
                        globalFilter={globalFilter}
                        header="Liste des Phases de Chantier"
                        loading={loading}
                        expandedRows={expandedRows}
                        onRowToggle={(e) => setExpandedRows(e.data)}
                        rowExpansionTemplate={rowExpansionTemplate}
                        className="datatable-responsive"
                        emptyMessage="Aucune phase trouvée"
                    >
                        <Column expander style={{ width: '3rem' }} />
                        <Column selectionMode="multiple" style={{ width: '3rem' }} exportable={false} />
                        <Column field="nom" header="Nom" sortable style={{ minWidth: '12rem' }} />
                        <Column 
                            field="statut" 
                            header="Statut" 
                            body={statutBodyTemplate} 
                            sortable 
                            style={{ minWidth: '8rem' }} 
                        />
                        <Column 
                            field="pourcentageAvancement" 
                            header="Avancement" 
                            body={avancementBodyTemplate} 
                            sortable 
                            style={{ minWidth: '10rem' }} 
                        />
                        <Column 
                            field="dateDebutPrevue" 
                            header="Début prévu" 
                            body={(rowData) => dateBodyTemplate(rowData.dateDebutPrevue)} 
                            sortable 
                            style={{ minWidth: '8rem' }} 
                        />
                        <Column 
                            field="dateFinPrevue" 
                            header="Fin prévue" 
                            body={(rowData) => dateBodyTemplate(rowData.dateFinPrevue)} 
                            sortable 
                            style={{ minWidth: '8rem' }} 
                        />
                        <Column 
                            field="budgetPrevu" 
                            header="Budget" 
                            body={(rowData) => budgetBodyTemplate(rowData.budgetPrevu)} 
                            sortable 
                            style={{ minWidth: '8rem' }} 
                        />
                        <Column 
                            header="Retard" 
                            body={retardBodyTemplate} 
                            style={{ minWidth: '6rem' }} 
                        />
                        <Column 
                            body={actionBodyTemplate} 
                            exportable={false} 
                            style={{ minWidth: '12rem' }} 
                        />
                    </DataTable>
                </Card>

                {/* Dialog pour créer/modifier une phase */}
                <Dialog
                    visible={phaseDialog}
                    style={{ width: '600px' }}
                    header="Détails de la Phase"
                    modal
                    className="p-fluid"
                    footer={
                        <div>
                            <Button 
                                label="Annuler" 
                                icon="pi pi-times" 
                                outlined 
                                onClick={hideDialog} 
                            />
                            <Button 
                                label="Enregistrer" 
                                icon="pi pi-check" 
                                onClick={savePhase} 
                            />
                        </div>
                    }
                    onHide={hideDialog}
                >
                    <div className="field">
                        <label htmlFor="nom" className="font-bold">Nom *</label>
                        <InputText
                            id="nom"
                            value={formData.nom}
                            onChange={(e) => onInputChange(e, 'nom')}
                            required
                            autoFocus
                            className={submitted && !formData.nom ? 'p-invalid' : ''}
                        />
                        {submitted && !formData.nom && <small className="p-error">Le nom est obligatoire.</small>}
                    </div>

                    <div className="field">
                        <label htmlFor="description" className="font-bold">Description</label>
                        <InputTextarea
                            id="description"
                            value={formData.description}
                            onChange={(e) => onInputChange(e, 'description')}
                            rows={3}
                        />
                    </div>

                    <div className="formgrid grid">
                        <div className="field col">
                            <label htmlFor="dateDebutPrevue" className="font-bold">Date début prévue *</label>
                            <Calendar
                                id="dateDebutPrevue"
                                value={formData.dateDebutPrevue}
                                onChange={(e) => onDateChange(e.value, 'dateDebutPrevue')}
                                dateFormat="dd/mm/yy"
                                showIcon
                                className={submitted && !formData.dateDebutPrevue ? 'p-invalid' : ''}
                            />
                        </div>
                        <div className="field col">
                            <label htmlFor="dateFinPrevue" className="font-bold">Date fin prévue *</label>
                            <Calendar
                                id="dateFinPrevue"
                                value={formData.dateFinPrevue}
                                onChange={(e) => onDateChange(e.value, 'dateFinPrevue')}
                                dateFormat="dd/mm/yy"
                                showIcon
                                className={submitted && !formData.dateFinPrevue ? 'p-invalid' : ''}
                            />
                        </div>
                    </div>

                    <div className="formgrid grid">
                        <div className="field col">
                            <label htmlFor="budgetPrevu" className="font-bold">Budget prévu (€)</label>
                            <InputNumber
                                id="budgetPrevu"
                                value={formData.budgetPrevu}
                                onValueChange={(e) => onNumberInputChange(e.value, 'budgetPrevu')}
                                mode="currency"
                                currency="EUR"
                                locale="fr-FR"
                            />
                        </div>
                        <div className="field col">
                            <label htmlFor="statut" className="font-bold">Statut</label>
                            <Dropdown
                                id="statut"
                                value={formData.statut}
                                options={statutOptions}
                                onChange={(e) => onDropdownChange(e, 'statut')}
                                placeholder="Sélectionner un statut"
                            />
                        </div>
                    </div>

                    <div className="field">
                        <label htmlFor="notes" className="font-bold">Notes</label>
                        <InputTextarea
                            id="notes"
                            value={formData.notes}
                            onChange={(e) => onInputChange(e, 'notes')}
                            rows={2}
                        />
                    </div>
                </Dialog>

                {/* Dialog de confirmation de suppression */}
                <Dialog
                    visible={deletePhaseDialog}
                    style={{ width: '450px' }}
                    header="Confirmer"
                    modal
                    footer={
                        <div>
                            <Button 
                                label="Non" 
                                icon="pi pi-times" 
                                outlined 
                                onClick={hideDeleteDialog} 
                            />
                            <Button 
                                label="Oui" 
                                icon="pi pi-check" 
                                severity="danger" 
                                onClick={deletePhase} 
                            />
                        </div>
                    }
                    onHide={hideDeleteDialog}
                >
                    <div className="confirmation-content">
                        <i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} />
                        {currentPhase && (
                            <span>
                                Êtes-vous sûr de vouloir supprimer la phase <b>{currentPhase.nom}</b> ?
                            </span>
                        )}
                    </div>
                </Dialog>
            </div>
        </div>
    );
};

export default PhasesChantierPage;