'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 { useRouter } from 'next/navigation';
import { apiClient } from '../../../../services/api-client';

interface EmployeActif {
    id: number;
    nom: string;
    prenom: string;
    email: string;
    telephone: string;
    metier: string;
    statut: string;
    dateEmbauche: string;
    equipeId?: number;
    equipeNom?: string;
    competences: string[];
    certifications: string[];
    niveauExperience: string;
    disponible: boolean;
    chantierActuel?: string;
}

const EmployesActifsPage = () => {
    const [employes, setEmployes] = useState<EmployeActif[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const router = useRouter();

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

    const loadEmployesActifs = async () => {
        try {
            setLoading(true);
            console.log('🔄 Chargement des employés actifs...');
            const response = await apiClient.get('/api/employes/actifs');
            console.log('✅ Employés actifs chargés:', response.data);
            setEmployes(response.data || []);
        } catch (error) {
            console.error('❌ Erreur lors du chargement des employés actifs:', error);
            setEmployes([]);
        } finally {
            setLoading(false);
        }
    };

    const metierBodyTemplate = (rowData: EmployeActif) => {
        const getMetierColor = (metier: string) => {
            const colors: { [key: string]: string } = {
                'MACON': 'info',
                'ELECTRICIEN': 'warning',
                'PLOMBIER': 'primary',
                'CHARPENTIER': 'success',
                'PEINTRE': 'secondary',
                'CHEF_EQUIPE': 'danger',
                'CONDUCTEUR': 'help'
            };
            return colors[metier] || 'secondary';
        };

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

    const disponibiliteBodyTemplate = (rowData: EmployeActif) => {
        return (
            <div className="flex align-items-center gap-2">
                <i className={`pi ${rowData.disponible ? 'pi-check-circle text-green-500' : 'pi-times-circle text-red-500'}`} />
                <span>{rowData.disponible ? 'Disponible' : 'Occupé'}</span>
                {rowData.chantierActuel && (
                    <Badge value={rowData.chantierActuel} severity="info" />
                )}
            </div>
        );
    };

    const equipeBodyTemplate = (rowData: EmployeActif) => {
        if (rowData.equipeNom) {
            return <Tag value={rowData.equipeNom} severity="success" />;
        }
        return <span className="text-500">Non assigné</span>;
    };

    const experienceBodyTemplate = (rowData: EmployeActif) => {
        const getExperienceColor = (niveau: string) => {
            switch (niveau) {
                case 'DEBUTANT': return 'info';
                case 'INTERMEDIAIRE': return 'warning';
                case 'EXPERIMENTE': return 'success';
                case 'EXPERT': return 'danger';
                default: return 'secondary';
            }
        };

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

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

    const certificationsBodyTemplate = (rowData: EmployeActif) => {
        if (!rowData.certifications || rowData.certifications.length === 0) {
            return <span className="text-500">Aucune</span>;
        }

        return (
            <div className="flex flex-wrap gap-1">
                {rowData.certifications.slice(0, 2).map((cert, index) => (
                    <Tag key={index} value={cert} severity="info" className="p-tag-sm" />
                ))}
                {rowData.certifications.length > 2 && (
                    <Badge value={`+${rowData.certifications.length - 2}`} severity="info" />
                )}
            </div>
        );
    };

    const actionBodyTemplate = (rowData: EmployeActif) => {
        return (
            <div className="flex gap-2">
                <Button
                    icon="pi pi-eye"
                    className="p-button-rounded p-button-info p-button-sm"
                    onClick={() => router.push(`/employes/${rowData.id}`)}
                    tooltip="Voir détails"
                />
                <Button
                    icon="pi pi-calendar"
                    className="p-button-rounded p-button-success p-button-sm"
                    onClick={() => router.push(`/employes/${rowData.id}/planning`)}
                    tooltip="Planning"
                />
                <Button
                    icon="pi pi-users"
                    className="p-button-rounded p-button-help p-button-sm"
                    onClick={() => router.push(`/equipes?employeId=${rowData.id}`)}
                    tooltip="Affecter à une équipe"
                />
            </div>
        );
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="flex flex-wrap gap-2">
                <Button
                    label="Tous les employés"
                    icon="pi pi-arrow-left"
                    className="p-button-outlined"
                    onClick={() => router.push('/employes')}
                />
                <Button
                    label="Disponibles"
                    icon="pi pi-calendar-check"
                    className="p-button-success"
                    onClick={() => router.push('/employes/disponibles')}
                />
                <Button
                    label="Nouvel employé"
                    icon="pi pi-plus"
                    className="p-button-primary"
                    onClick={() => router.push('/employes/nouveau')}
                />
            </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={loadEmployesActifs}
                    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">Employés Actifs ({employes.length})</h2>
            <div className="flex gap-2 mt-2 md:mt-0">
                <Badge value={employes.filter(e => e.disponible).length} severity="success" />
                <span>Disponibles</span>
                <Badge value={employes.filter(e => !e.disponible).length} severity="warning" />
                <span>Occupés</span>
            </div>
        </div>
    );

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

                    <DataTable
                        value={employes}
                        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} employés actifs"
                        globalFilter={globalFilter}
                        emptyMessage="Aucun employé actif trouvé."
                        header={header}
                        responsiveLayout="scroll"
                    >
                        <Column field="nom" header="Nom" sortable />
                        <Column field="prenom" header="Prénom" sortable />
                        <Column field="metier" header="Métier" body={metierBodyTemplate} sortable />
                        <Column field="niveauExperience" header="Expérience" body={experienceBodyTemplate} sortable />
                        <Column field="equipeNom" header="Équipe" body={equipeBodyTemplate} sortable />
                        <Column field="disponible" header="Disponibilité" body={disponibiliteBodyTemplate} sortable />
                        <Column field="competences" header="Compétences" body={competencesBodyTemplate} />
                        <Column field="certifications" header="Certifications" body={certificationsBodyTemplate} />
                        <Column field="email" header="Email" sortable />
                        <Column body={actionBodyTemplate} header="Actions" style={{ minWidth: '10rem' }} />
                    </DataTable>
                </Card>
            </div>
        </div>
    );
};

export default EmployesActifsPage;
