'use client';

import React, { useState, useEffect } from 'react';
import { Panel } from 'primereact/panel';
import { Button } from 'primereact/button';
import { Message } from 'primereact/message';
import { Divider } from 'primereact/divider';
import { Toast } from 'primereact/toast';
import { useRef } from 'react';
import TestDataGenerator from '../../../../components/test/TestDataGenerator';
import TestResults from '../../../../components/test/TestResults';
import WorkflowTests from '../../../../components/test/WorkflowTests';
import SystemIntegrationTest from '../../../../components/test/SystemIntegrationTest';
import PhasesQuickPreview from '../../../../components/phases/PhasesQuickPreview';
import PhaseValidationPanel from '../../../../components/phases/PhaseValidationPanel';
import AtlantisResponsivePhasesTable from '../../../../components/phases/AtlantisResponsivePhasesTable';
import AtlantisAccessibilityControls from '../../../../components/phases/AtlantisAccessibilityControls';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Tag } from 'primereact/tag';
import { Badge } from 'primereact/badge';
import { Dialog } from 'primereact/dialog';
import testDataService from '../../../../services/testDataService';
import phaseValidationService from '../../../../services/phaseValidationService';
import type { PhaseChantier, Chantier, Client } from '../../../../types/btp';

interface TestData {
    client: Client;
    chantier: Chantier;
    phases: PhaseChantier[];
}

const TestPhasesPage: React.FC = () => {
    const [testData, setTestData] = useState<TestData[]>([]);
    const [selectedData, setSelectedData] = useState<TestData | null>(null);
    const [validationDialogVisible, setValidationDialogVisible] = useState(false);
    const [selectedPhase, setSelectedPhase] = useState<PhaseChantier | null>(null);
    const [loading, setLoading] = useState(false);
    const toast = useRef<Toast>(null);

    // Auto-générer des données de test au chargement
    useEffect(() => {
        generateInitialData();
    }, []);

    const generateInitialData = async () => {
        try {
            const initialData = testDataService.generateTestDataset(2);
            setTestData(initialData);
            if (initialData.length > 0) {
                setSelectedData(initialData[0]);
            }
            
            toast.current?.show({
                severity: 'success',
                summary: 'Données de test générées',
                detail: `${initialData.length} projets avec phases créés`,
                life: 3000
            });
        } catch (error) {
            toast.current?.show({
                severity: 'error',
                summary: 'Erreur',
                detail: 'Impossible de générer les données de test',
                life: 5000
            });
        }
    };

    const handleDataGenerated = (newData: any) => {
        if (Array.isArray(newData)) {
            setTestData(prev => [...prev, ...newData]);
            if (!selectedData && newData.length > 0) {
                setSelectedData(newData[0]);
            }
        } else {
            // Données individuelles (phases uniquement, etc.)
            const dataItem: TestData = {
                client: newData.client || testDataService.generateTestClient(Date.now()),
                chantier: newData.chantier || testDataService.generateTestChantier(Date.now(), 'MAISON_INDIVIDUELLE', newData.client),
                phases: newData.phases || []
            };
            setTestData(prev => [...prev, dataItem]);
            setSelectedData(dataItem);
        }

        toast.current?.show({
            severity: 'success',
            summary: 'Nouvelles données générées',
            detail: 'Les données ont été ajoutées avec succès',
            life: 3000
        });
    };

    const handlePhaseValidation = (phase: PhaseChantier) => {
        setSelectedPhase(phase);
        setValidationDialogVisible(true);
    };

    const handleStartPhase = (phaseId: string) => {
        if (!selectedData) return;

        const updatedPhases = selectedData.phases.map(p => 
            p.id === phaseId 
                ? { ...p, statut: 'EN_COURS' as const, dateDebutReelle: new Date().toISOString().split('T')[0] }
                : p
        );

        const updatedData = { ...selectedData, phases: updatedPhases };
        setSelectedData(updatedData);
        
        setTestData(prev => prev.map(item => 
            item.chantier.id === updatedData.chantier.id ? updatedData : item
        ));

        toast.current?.show({
            severity: 'info',
            summary: 'Phase démarrée',
            detail: `La phase a été mise en cours`,
            life: 3000
        });

        setValidationDialogVisible(false);
    };

    // Templates pour l'affichage du tableau
    const statusBodyTemplate = (rowData: PhaseChantier) => {
        const severity = rowData.statut === 'TERMINEE' ? 'success' : 
                        rowData.statut === 'EN_COURS' ? 'info' : 'secondary';
        
        return <Tag value={rowData.statut} severity={severity} />;
    };

    const progressBodyTemplate = (rowData: PhaseChantier) => {
        return (
            <div className="flex align-items-center gap-2">
                <span>{rowData.pourcentageAvancement || 0}%</span>
                <div className="w-4rem h-0.5rem bg-gray-200 border-round overflow-hidden">
                    <div 
                        className="h-full bg-primary border-round"
                        style={{ width: `${rowData.pourcentageAvancement || 0}%` }}
                    ></div>
                </div>
            </div>
        );
    };

    const validationBodyTemplate = (rowData: PhaseChantier) => {
        if (!selectedData) return null;

        const validation = phaseValidationService.validatePhaseStart(rowData, selectedData.phases);
        
        const severity = validation.readyToStart ? 'success' : 
                        validation.canStart ? 'warning' : 'danger';
        
        const icon = validation.readyToStart ? 'pi pi-check-circle' : 
                    validation.canStart ? 'pi pi-exclamation-triangle' : 'pi pi-times-circle';

        return (
            <div className="flex align-items-center gap-2">
                <i className={`${icon} text-${severity === 'danger' ? 'red' : severity === 'warning' ? 'yellow' : 'green'}-500`}></i>
                {validation.errors.length > 0 && (
                    <Badge value={validation.errors.length} severity="danger" />
                )}
                {validation.warnings.length > 0 && (
                    <Badge value={validation.warnings.length} severity="warning" />
                )}
                <Button
                    icon="pi pi-eye"
                    className="p-button-text p-button-sm"
                    onClick={() => handlePhaseValidation(rowData)}
                    tooltip="Voir la validation"
                />
            </div>
        );
    };

    const nameBodyTemplate = (rowData: PhaseChantier) => {
        const isSubPhase = !!rowData.phaseParent;
        
        return (
            <div className={`flex align-items-center gap-2 ${isSubPhase ? 'ml-4' : ''}`}>
                {isSubPhase && <i className="pi pi-arrow-right text-gray-400 text-xs"></i>}
                <span className={isSubPhase ? 'text-600' : 'font-semibold'}>
                    {rowData.nom}
                </span>
                {rowData.critique && (
                    <Tag value="Critique" severity="danger" className="text-xs" />
                )}
            </div>
        );
    };

    const actionsBodyTemplate = (rowData: PhaseChantier) => {
        if (!selectedData) return null;

        const validation = phaseValidationService.validatePhaseStart(rowData, selectedData.phases);
        
        return (
            <div className="flex gap-1">
                <Button
                    icon="pi pi-play"
                    className="p-button-success p-button-sm"
                    disabled={!validation.canStart || rowData.statut === 'TERMINEE'}
                    onClick={() => handleStartPhase(rowData.id!)}
                    tooltip="Démarrer"
                />
                <Button
                    icon="pi pi-eye"
                    className="p-button-outlined p-button-sm"
                    onClick={() => handlePhaseValidation(rowData)}
                    tooltip="Détails"
                />
            </div>
        );
    };

    return (
        <div className="grid">
            <Toast ref={toast} />
            
            <div className="col-12">
                <Panel header="Test du système de gestion des phases BTP" toggleable>
                    <Message 
                        severity="info" 
                        text="Cette page permet de tester le système complet de gestion des phases avec des données réalistes."
                        className="w-full mb-4"
                    />
                    
                    <TestResults className="mb-4" />
                    
                    <WorkflowTests className="mb-4" />
                    
                    <SystemIntegrationTest className="mb-4" />
                    
                    <TestDataGenerator 
                        onDataGenerated={handleDataGenerated}
                        className="mb-4"
                    />
                </Panel>
            </div>

            {testData.length > 0 && (
                <>
                    <div className="col-12 md:col-4">
                        <Panel header="Projets de test" toggleable>
                            {testData.map((data, index) => (
                                <div 
                                    key={data.chantier.id}
                                    className={`p-3 border-1 border-round cursor-pointer mb-2 ${
                                        selectedData?.chantier.id === data.chantier.id 
                                            ? 'border-primary bg-primary-50' 
                                            : 'surface-border hover:surface-100'
                                    }`}
                                    onClick={() => setSelectedData(data)}
                                >
                                    <div className="font-semibold">{data.chantier.nom}</div>
                                    <div className="text-600 text-sm">{data.client.nomComplet}</div>
                                    <div className="text-600 text-sm">
                                        {data.phases.length} phases • {data.chantier.typeChantier}
                                    </div>
                                </div>
                            ))}
                        </Panel>
                    </div>

                    <div className="col-12 md:col-8">
                        {selectedData && (
                            <>
                                <AtlantisAccessibilityControls className="mb-4" />
                                
                                <PhasesQuickPreview 
                                    phases={selectedData.phases}
                                    className="mb-4"
                                />

                                <AtlantisResponsivePhasesTable 
                                    phases={selectedData.phases}
                                    onPhaseSelect={setSelectedPhase}
                                    onPhaseStart={handleStartPhase}
                                    onPhaseValidate={handlePhaseValidation}
                                    className="mb-4"
                                />

                                <Panel header={`Détails - ${selectedData.chantier.nom}`} toggleable collapsed>
                                    <DataTable 
                                        value={selectedData.phases}
                                        size="small"
                                        className="p-datatable-sm"
                                        emptyMessage="Aucune phase trouvée"
                                    >
                                        <Column 
                                            field="nom" 
                                            header="Phase"
                                            body={nameBodyTemplate}
                                            style={{ width: '25%' }}
                                        />
                                        <Column 
                                            field="statut" 
                                            header="Statut"
                                            body={statusBodyTemplate}
                                            style={{ width: '10%' }}
                                        />
                                        <Column 
                                            field="pourcentageAvancement" 
                                            header="Avancement"
                                            body={progressBodyTemplate}
                                            style={{ width: '15%' }}
                                        />
                                        <Column 
                                            field="dateDebutPrevue" 
                                            header="Début prévu"
                                            body={(rowData) => rowData.dateDebutPrevue ? 
                                                new Date(rowData.dateDebutPrevue).toLocaleDateString('fr-FR') : '-'
                                            }
                                            style={{ width: '12%' }}
                                        />
                                        <Column 
                                            field="dateFinPrevue" 
                                            header="Fin prévue"
                                            body={(rowData) => rowData.dateFinPrevue ? 
                                                new Date(rowData.dateFinPrevue).toLocaleDateString('fr-FR') : '-'
                                            }
                                            style={{ width: '12%' }}
                                        />
                                        <Column 
                                            header="Validation"
                                            body={validationBodyTemplate}
                                            style={{ width: '15%' }}
                                        />
                                        <Column 
                                            header="Actions"
                                            body={actionsBodyTemplate}
                                            style={{ width: '11%' }}
                                        />
                                    </DataTable>
                                </Panel>
                            </>
                        )}
                    </div>
                </>
            )}

            <Dialog
                header="Validation des prérequis"
                visible={validationDialogVisible}
                onHide={() => setValidationDialogVisible(false)}
                style={{ width: '90vw', maxWidth: '800px' }}
                modal
            >
                {selectedPhase && selectedData && (
                    <PhaseValidationPanel
                        phase={selectedPhase}
                        allPhases={selectedData.phases}
                        onStartPhase={handleStartPhase}
                        onViewPrerequisite={(prereqId) => {
                            const prereq = selectedData.phases.find(p => p.id === prereqId);
                            if (prereq) {
                                setSelectedPhase(prereq);
                            }
                        }}
                    />
                )}
            </Dialog>
        </div>
    );
};

export default TestPhasesPage;