'use client';

import React, { useState, useRef, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { Dialog } from 'primereact/dialog';
import { InputText } from 'primereact/inputtext';
import { InputTextarea } from 'primereact/inputtextarea';
import { Calendar } from 'primereact/calendar';
import { InputNumber } from 'primereact/inputnumber';
import { Dropdown } from 'primereact/dropdown';
import { Checkbox } from 'primereact/checkbox';
import { Toast } from 'primereact/toast';
import { Toolbar } from 'primereact/toolbar';
import { Badge } from 'primereact/badge';

import PhasesTable from '../../../../../components/phases/PhasesTable';
import usePhasesManager from '../../../../../hooks/usePhasesManager';
import type { PhaseChantier, PhaseFormData } from '../../../../../types/btp-extended';

const PhasesCleanPage: React.FC = () => {
    const params = useParams();
    const chantierId = params?.id as string;
    const toast = useRef<Toast>(null);
    
    // Hook de gestion des phases
    const {
        phases,
        loading,
        selectedPhase,
        setSelectedPhase,
        loadPhases,
        createPhase,
        updatePhase,
        deletePhase,
        startPhase,
        setToastRef
    } = usePhasesManager({ chantierId });
    
    const [globalFilter, setGlobalFilter] = useState('');
    
    // États pour les dialogues
    const [showPhaseDialog, setShowPhaseDialog] = useState(false);
    const [editingPhase, setEditingPhase] = useState(false);
    
    // États pour les formulaires
    const [phaseForm, setPhaseForm] = useState<PhaseFormData>({
        nom: '',
        description: '',
        dateDebutPrevue: '',
        dateFinPrevue: '',
        dureeEstimeeHeures: 8,
        priorite: 'MOYENNE',
        critique: false,
        ordreExecution: 1,
        budgetPrevu: 0,
        coutReel: 0,
        prerequisPhases: [],
        competencesRequises: [],
        materielsNecessaires: [],
        fournisseursRecommandes: []
    });

    // Initialisation
    useEffect(() => {
        setToastRef(toast.current);
        if (chantierId) {
            loadPhases();
        }
    }, [chantierId, setToastRef, loadPhases]);

    // Gestionnaires d'événements
    const handleEditPhase = (phase: PhaseChantier) => {
        setSelectedPhase(phase);
        setEditingPhase(true);
        setPhaseForm({
            nom: phase.nom,
            description: phase.description || '',
            dateDebutPrevue: phase.dateDebutPrevue || '',
            dateFinPrevue: phase.dateFinPrevue || '',
            dureeEstimeeHeures: phase.dureeEstimeeHeures || 8,
            priorite: phase.priorite || 'MOYENNE',
            critique: phase.critique || false,
            ordreExecution: phase.ordreExecution || 1,
            budgetPrevu: phase.budgetPrevu || 0,
            coutReel: phase.coutReel || 0,
            prerequisPhases: phase.prerequisPhases || [],
            competencesRequises: phase.competencesRequises || [],
            materielsNecessaires: phase.materielsNecessaires || [],
            fournisseursRecommandes: phase.fournisseursRecommandes || []
        });
        setShowPhaseDialog(true);
    };

    const handleSavePhase = async () => {
        if (!phaseForm.nom.trim()) {
            toast.current?.show({
                severity: 'warn',
                summary: 'Données manquantes',
                detail: 'Veuillez remplir le nom de la phase',
                life: 3000
            });
            return;
        }

        try {
            const phaseData = {
                ...phaseForm,
                chantierId: chantierId
            };
            
            if (editingPhase && selectedPhase) {
                await updatePhase(selectedPhase.id!, phaseData);
            } else {
                await createPhase(phaseData);
            }
            
            setShowPhaseDialog(false);
            setEditingPhase(false);
            setSelectedPhase(null);
            resetPhaseForm();
            
        } catch (error) {
            console.error('Erreur lors de la sauvegarde de la phase:', error);
        }
    };

    const resetPhaseForm = () => {
        setPhaseForm({
            nom: '',
            description: '',
            dateDebutPrevue: '',
            dateFinPrevue: '',
            dureeEstimeeHeures: 8,
            priorite: 'MOYENNE',
            critique: false,
            ordreExecution: 1,
            budgetPrevu: 0,
            coutReel: 0,
            prerequisPhases: [],
            competencesRequises: [],
            materielsNecessaires: [],
            fournisseursRecommandes: []
        });
    };

    // Templates de la toolbar
    const toolbarStartTemplate = (
        <div className="flex align-items-center gap-2">
            <h5 className="m-0 text-color">Phases - Version Clean</h5>
            <Badge value={phases.length} />
        </div>
    );

    const toolbarEndTemplate = (
        <div className="flex gap-2">
            <span className="p-input-icon-left">
                <i className="pi pi-search" />
                <InputText
                    value={globalFilter}
                    onChange={(e) => setGlobalFilter(e.target.value)}
                    placeholder="Rechercher..."
                />
            </span>
            <Button
                label="Nouvelle phase"
                icon="pi pi-plus"
                className="p-button-success"
                onClick={() => {
                    resetPhaseForm();
                    setEditingPhase(false);
                    setShowPhaseDialog(true);
                }}
            />
        </div>
    );

    return (
        <div className="grid">
            <Toast ref={toast} />
            
            <div className="col-12">
                <Card>
                    <Toolbar 
                        start={toolbarStartTemplate} 
                        end={toolbarEndTemplate}
                        className="mb-4"
                    />
                    
                    <PhasesTable
                        phases={phases}
                        loading={loading}
                        chantierId={chantierId}
                        showStats={false}
                        showChantierColumn={false}
                        showSubPhases={true}
                        showBudget={true}
                        showExpansion={true}
                        actions={['view', 'edit', 'delete', 'start']}
                        onRefresh={loadPhases}
                        onPhaseEdit={handleEditPhase}
                        onPhaseDelete={deletePhase}
                        onPhaseStart={startPhase}
                        rows={15}
                        globalFilter={globalFilter}
                        showGlobalFilter={true}
                    />
                </Card>
            </div>

            {/* Dialog pour créer/modifier une phase */}
            <Dialog
                header={editingPhase ? "Modifier la phase" : "Nouvelle phase"}
                visible={showPhaseDialog}
                onHide={() => {
                    setShowPhaseDialog(false);
                    setEditingPhase(false);
                    resetPhaseForm();
                }}
                footer={
                    <div>
                        <Button 
                            label="Annuler" 
                            icon="pi pi-times" 
                            className="p-button-text" 
                            onClick={() => {
                                setShowPhaseDialog(false);
                                setEditingPhase(false);
                                resetPhaseForm();
                            }}
                        />
                        <Button 
                            label={editingPhase ? "Modifier" : "Créer"}
                            icon="pi pi-check" 
                            className="p-button-success" 
                            onClick={handleSavePhase}
                        />
                    </div>
                }
                style={{ width: '50vw', maxWidth: '600px' }}
                modal
            >
                <div className="grid">
                    <div className="col-12">
                        <div className="field">
                            <label htmlFor="phaseNom" className="font-semibold">
                                Nom de la phase <span className="text-red-500">*</span>
                            </label>
                            <InputText
                                id="phaseNom"
                                value={phaseForm.nom}
                                onChange={(e) => setPhaseForm(prev => ({ ...prev, nom: e.target.value }))}
                                className="w-full"
                                placeholder="Ex: Fondations, Gros œuvre..."
                            />
                        </div>
                    </div>
                    
                    <div className="col-12">
                        <div className="field">
                            <label htmlFor="phaseDescription" className="font-semibold">Description</label>
                            <InputTextarea
                                id="phaseDescription"
                                value={phaseForm.description}
                                onChange={(e) => setPhaseForm(prev => ({ ...prev, description: e.target.value }))}
                                className="w-full"
                                rows={3}
                                placeholder="Description détaillée de la phase..."
                            />
                        </div>
                    </div>
                    
                    <div className="col-12 md:col-6">
                        <div className="field">
                            <label htmlFor="phaseDuree" className="font-semibold">Durée estimée (heures)</label>
                            <InputNumber
                                id="phaseDuree"
                                value={phaseForm.dureeEstimeeHeures}
                                onChange={(e) => setPhaseForm(prev => ({ ...prev, dureeEstimeeHeures: e.value || 0 }))}
                                className="w-full"
                                min={1}
                                suffix=" h"
                            />
                        </div>
                    </div>
                    
                    <div className="col-12 md:col-6">
                        <div className="field">
                            <label htmlFor="phasePriorite" className="font-semibold">Priorité</label>
                            <Dropdown
                                id="phasePriorite"
                                value={phaseForm.priorite}
                                options={[
                                    { label: 'Faible', value: 'FAIBLE' },
                                    { label: 'Moyenne', value: 'MOYENNE' },
                                    { label: 'Élevée', value: 'ELEVEE' },
                                    { label: 'Critique', value: 'CRITIQUE' }
                                ]}
                                onChange={(e) => setPhaseForm(prev => ({ ...prev, priorite: e.value }))}
                                className="w-full"
                            />
                        </div>
                    </div>
                    
                    <div className="col-12">
                        <div className="field-checkbox">
                            <Checkbox
                                id="phaseCritique"
                                checked={phaseForm.critique}
                                onChange={(e) => setPhaseForm(prev => ({ ...prev, critique: e.checked }))}
                            />
                            <label htmlFor="phaseCritique" className="ml-2 font-semibold">
                                Phase critique
                            </label>
                        </div>
                    </div>
                </div>
            </Dialog>
        </div>
    );
};

export default PhasesCleanPage;