'use client';
export const dynamic = 'force-dynamic';


import React, { useState, useEffect } from 'react';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { Tag } from 'primereact/tag';
import { Card } from 'primereact/card';
import { Toolbar } from 'primereact/toolbar';
import { Badge } from 'primereact/badge';
import { Dialog } from 'primereact/dialog';
import { Toast } from 'primereact/toast';
import { ConfirmDialog } from 'primereact/confirmdialog';
import { useRouter } from 'next/navigation';
import { apiClient } from '../../../services/api-client';

interface Equipe {
    id: number;
    nom: string;
    description: string;
    specialite: string;
    statut: 'ACTIVE' | 'INACTIVE' | 'EN_MISSION' | 'DISPONIBLE';
    chefEquipeId?: number;
    chefEquipeNom?: string;
    nombreEmployes: number;
    employes: Array<{
        id: number;
        nom: string;
        prenom: string;
        metier: string;
    }>;
    chantierActuel?: string;
    dateCreation: string;
    competencesEquipe: string[];
    tauxOccupation: number;
}

const EquipesPage = () => {
    const [equipes, setEquipes] = useState<Equipe[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedEquipes, setSelectedEquipes] = useState<Equipe[]>([]);
    const [deleteDialog, setDeleteDialog] = useState(false);
    const [equipeToDelete, setEquipeToDelete] = useState<Equipe | null>(null);
    const router = useRouter();

    const specialiteOptions = [
        { label: 'Toutes', value: null },
        { label: 'Gros œuvre', value: 'GROS_OEUVRE' },
        { label: 'Second œuvre', value: 'SECOND_OEUVRE' },
        { label: 'Finitions', value: 'FINITIONS' },
        { label: 'Électricité', value: 'ELECTRICITE' },
        { label: 'Plomberie', value: 'PLOMBERIE' },
        { label: 'Charpente', value: 'CHARPENTE' },
        { label: 'Couverture', value: 'COUVERTURE' },
        { label: 'Terrassement', value: 'TERRASSEMENT' }
    ];

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

    const loadEquipes = async () => {
        try {
            setLoading(true);
            console.log('🔄 Chargement des équipes...');
            const response = await apiClient.get('/api/equipes');
            console.log('✅ Équipes chargées:', response.data);
            setEquipes(response.data || []);
        } catch (error) {
            console.error('❌ Erreur lors du chargement des équipes:', error);
            setEquipes([]);
        } finally {
            setLoading(false);
        }
    };

    const confirmDeleteEquipe = (equipe: Equipe) => {
        setEquipeToDelete(equipe);
        setDeleteDialog(true);
    };

    const deleteEquipe = async () => {
        if (equipeToDelete) {
            try {
                await apiClient.delete(`/api/equipes/${equipeToDelete.id}`);
                setEquipes(equipes.filter(e => e.id !== equipeToDelete.id));
                setDeleteDialog(false);
                setEquipeToDelete(null);
                console.log('✅ Équipe supprimée avec succès');
            } catch (error) {
                console.error('❌ Erreur lors de la suppression:', error);
            }
        }
    };

    const toggleStatutEquipe = async (equipe: Equipe) => {
        try {
            const newStatut = equipe.statut === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';
            const endpoint = newStatut === 'ACTIVE' ? 'activer' : 'desactiver';
            
            await apiClient.post(`/api/equipes/${equipe.id}/${endpoint}`);
            
            setEquipes(equipes.map(e => 
                e.id === equipe.id ? { ...e, statut: newStatut } : e
            ));
            
            console.log(`✅ Statut équipe ${newStatut.toLowerCase()}`);
        } catch (error) {
            console.error('❌ Erreur lors du changement de statut:', error);
        }
    };

    const statutBodyTemplate = (rowData: Equipe) => {
        const getSeverity = (statut: string) => {
            switch (statut) {
                case 'ACTIVE': return 'success';
                case 'INACTIVE': return 'danger';
                case 'EN_MISSION': return 'warning';
                case 'DISPONIBLE': return 'info';
                default: return 'secondary';
            }
        };

        return <Tag value={rowData.statut} severity={getSeverity(rowData.statut) as any} />;
    };

    const specialiteBodyTemplate = (rowData: Equipe) => {
        const getSpecialiteColor = (specialite: string) => {
            const colors: { [key: string]: string } = {
                'GROS_OEUVRE': 'danger',
                'SECOND_OEUVRE': 'warning',
                'FINITIONS': 'success',
                'ELECTRICITE': 'info',
                'PLOMBERIE': 'primary',
                'CHARPENTE': 'help',
                'COUVERTURE': 'secondary',
                'TERRASSEMENT': 'contrast'
            };
            return colors[specialite] || 'secondary';
        };

        return <Tag value={rowData.specialite} severity={getSpecialiteColor(rowData.specialite) as any} />;
    };

    const chefEquipeBodyTemplate = (rowData: Equipe) => {
        if (rowData.chefEquipeNom) {
            return (
                <div className="flex align-items-center gap-2">
                    <i className="pi pi-user text-blue-500" />
                    <span>{rowData.chefEquipeNom}</span>
                </div>
            );
        }
        return <span className="text-500">Non assigné</span>;
    };

    const employesBodyTemplate = (rowData: Equipe) => {
        return (
            <div className="flex align-items-center gap-2">
                <Badge value={rowData.nombreEmployes} severity="info" />
                <span>employés</span>
                {rowData.employes && rowData.employes.length > 0 && (
                    <div className="flex flex-wrap gap-1">
                        {rowData.employes.slice(0, 2).map((emp, index) => (
                            <Tag key={index} value={`${emp.prenom} ${emp.nom}`} className="p-tag-sm" />
                        ))}
                        {rowData.employes.length > 2 && (
                            <Badge value={`+${rowData.employes.length - 2}`} severity={"secondary" as any} />
                        )}
                    </div>
                )}
            </div>
        );
    };

    const occupationBodyTemplate = (rowData: Equipe) => {
        const getOccupationColor = (taux: number) => {
            if (taux >= 90) return 'danger';
            if (taux >= 70) return 'warning';
            if (taux >= 40) return 'success';
            return 'info';
        };

        return (
            <div className="flex align-items-center gap-2">
                <Tag value={`${rowData.tauxOccupation}%`} severity={getOccupationColor(rowData.tauxOccupation)} />
                {rowData.chantierActuel && (
                    <small className="text-500">{rowData.chantierActuel}</small>
                )}
            </div>
        );
    };

    const competencesBodyTemplate = (rowData: Equipe) => {
        return (
            <div className="flex flex-wrap gap-1">
                {rowData.competencesEquipe?.slice(0, 3).map((comp, index) => (
                    <Tag key={index} value={comp} className="p-tag-sm" />
                ))}
                {rowData.competencesEquipe?.length > 3 && (
                    <Badge value={`+${rowData.competencesEquipe.length - 3}`} severity="info" />
                )}
            </div>
        );
    };

    const actionBodyTemplate = (rowData: Equipe) => {
        return (
            <div className="flex gap-2">
                <Button
                    icon="pi pi-eye"
                    className="p-button-rounded p-button-info p-button-sm"
                    onClick={() => router.push(`/equipes/${rowData.id}`)}
                    tooltip="Voir détails"
                />
                <Button
                    icon="pi pi-pencil"
                    className="p-button-rounded p-button-success p-button-sm"
                    onClick={() => router.push(`/equipes/${rowData.id}/edit`)}
                    tooltip="Modifier"
                />
                <Button
                    icon="pi pi-calendar"
                    className="p-button-rounded p-button-warning p-button-sm"
                    onClick={() => router.push(`/planning?equipeId=${rowData.id}`)}
                    tooltip="Planning"
                />
                <Button
                    icon={rowData.statut === 'ACTIVE' ? 'pi pi-pause' : 'pi pi-play'}
                    className={`p-button-rounded p-button-sm ${
                        rowData.statut === 'ACTIVE' ? 'p-button-warning' : 'p-button-success'
                    }`}
                    onClick={() => toggleStatutEquipe(rowData)}
                    tooltip={rowData.statut === 'ACTIVE' ? 'Désactiver' : 'Activer'}
                />
                <Button
                    icon="pi pi-trash"
                    className="p-button-rounded p-button-danger p-button-sm"
                    onClick={() => confirmDeleteEquipe(rowData)}
                    tooltip="Supprimer"
                />
            </div>
        );
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="flex flex-wrap gap-2">
                <Button
                    label="Nouvelle Équipe"
                    icon="pi pi-plus"
                    className="p-button-success"
                    onClick={() => router.push('/equipes/nouvelle')}
                />
                <Button
                    label="Équipes Disponibles"
                    icon="pi pi-check-circle"
                    className="p-button-info"
                    onClick={() => router.push('/equipes/disponibles')}
                />
                <Button
                    label="Par Spécialité"
                    icon="pi pi-tags"
                    className="p-button-help"
                    onClick={() => router.push('/equipes/specialites')}
                />
                <Button
                    label="Équipe Optimale"
                    icon="pi pi-star"
                    className="p-button-warning"
                    onClick={() => router.push('/equipes/optimal')}
                />
                <Button
                    label="Statistiques"
                    icon="pi pi-chart-bar"
                    className="p-button-secondary"
                    onClick={() => router.push('/equipes/stats')}
                />
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <div className="flex gap-2">
                <span className="p-input-icon-left">
                    <i className="pi pi-search" />
                    <InputText
                        type="search"
                        placeholder="Rechercher..."
                        value={globalFilter}
                        onChange={(e) => setGlobalFilter(e.target.value)}
                    />
                </span>
                <Button
                    icon="pi pi-refresh"
                    className="p-button-outlined"
                    onClick={loadEquipes}
                    tooltip="Actualiser"
                />
            </div>
        );
    };

    const header = (
        <div className="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
            <h2 className="m-0">Gestion des Équipes</h2>
            <div className="flex gap-2 mt-2 md:mt-0">
                <Badge value={equipes.filter(e => e.statut === 'ACTIVE').length} severity="success" />
                <span>Actives</span>
                <Badge value={equipes.filter(e => e.statut === 'DISPONIBLE').length} severity="info" />
                <span>Disponibles</span>
                <Badge value={equipes.filter(e => e.statut === 'EN_MISSION').length} severity="warning" />
                <span>En mission</span>
            </div>
        </div>
    );

    return (
        <div className="grid">
            <div className="col-12">
                <Card>
                    <Toolbar 
                        className="mb-4" 
                        left={leftToolbarTemplate} 
                        right={rightToolbarTemplate}
                    />

                    <DataTable
                        value={equipes}
                        loading={loading}
                        dataKey="id"
                        paginator
                        rows={10}
                        rowsPerPageOptions={[5, 10, 25, 50]}
                        className="datatable-responsive"
                        paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                        currentPageReportTemplate="Affichage de {first} à {last} sur {totalRecords} équipes"
                        globalFilter={globalFilter}
                        emptyMessage="Aucune équipe trouvée."
                        header={header}
                        selection={selectedEquipes}
                        onSelectionChange={(e) => setSelectedEquipes(e.value)}
                        selectionMode="multiple"
                        responsiveLayout="scroll"
                    >
                        <Column selectionMode="multiple" headerStyle={{ width: '3rem' }} />
                        <Column field="nom" header="Nom" sortable />
                        <Column field="specialite" header="Spécialité" body={specialiteBodyTemplate} sortable />
                        <Column field="statut" header="Statut" body={statutBodyTemplate} sortable />
                        <Column field="chefEquipeNom" header="Chef d'équipe" body={chefEquipeBodyTemplate} sortable />
                        <Column field="nombreEmployes" header="Employés" body={employesBodyTemplate} sortable />
                        <Column field="tauxOccupation" header="Occupation" body={occupationBodyTemplate} sortable />
                        <Column field="competencesEquipe" header="Compétences" body={competencesBodyTemplate} />
                        <Column field="dateCreation" header="Créée le" sortable />
                        <Column body={actionBodyTemplate} header="Actions" style={{ minWidth: '14rem' }} />
                    </DataTable>
                </Card>
            </div>

            <ConfirmDialog
                visible={deleteDialog}
                onHide={() => setDeleteDialog(false)}
                message={`Êtes-vous sûr de vouloir supprimer l'équipe "${equipeToDelete?.nom}" ?`}
                header="Confirmation de suppression"
                icon="pi pi-exclamation-triangle"
                accept={deleteEquipe}
                reject={() => setDeleteDialog(false)}
                acceptLabel="Oui"
                rejectLabel="Non"
                acceptClassName="p-button-danger"
            />

            <Toast />
        </div>
    );
};

export default EquipesPage;

