'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 { Calendar } from 'primereact/calendar';
import { Dropdown } from 'primereact/dropdown';
import { Badge } from 'primereact/badge';
import { useRouter } from 'next/navigation';
import { apiClient } from '../../../../services/api-client';

interface EmployeDisponible {
    id: number;
    nom: string;
    prenom: string;
    email: string;
    telephone: string;
    metier: string;
    niveauExperience: string;
    competences: string[];
    certifications: string[];
    equipeId?: number;
    equipeNom?: string;
    prochainChantier?: string;
    dateProchainChantier?: string;
    disponibleJusquau?: string;
}

const EmployesDisponiblesPage = () => {
    const [employes, setEmployes] = useState<EmployeDisponible[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [dateRecherche, setDateRecherche] = useState<Date | null>(null);
    const [metierFiltre, setMetierFiltre] = useState<string>('');
    const router = useRouter();

    const metierOptions = [
        { label: 'Tous les métiers', value: '' },
        { label: 'Maçon', value: 'MACON' },
        { label: 'Électricien', value: 'ELECTRICIEN' },
        { label: 'Plombier', value: 'PLOMBIER' },
        { label: 'Charpentier', value: 'CHARPENTIER' },
        { label: 'Peintre', value: 'PEINTRE' },
        { label: 'Chef d\'équipe', value: 'CHEF_EQUIPE' },
        { label: 'Conducteur', value: 'CONDUCTEUR' }
    ];

    useEffect(() => {
        loadEmployesDisponibles();
    }, [dateRecherche, metierFiltre]);

    const loadEmployesDisponibles = async () => {
        try {
            setLoading(true);
            console.log('🔄 Chargement des employés disponibles...');
            
            let url = '/api/employes/disponibles';
            const params = new URLSearchParams();
            
            if (dateRecherche) {
                params.append('date', dateRecherche.toISOString().split('T')[0]);
            }
            if (metierFiltre) {
                params.append('metier', metierFiltre);
            }
            
            if (params.toString()) {
                url += `?${params.toString()}`;
            }
            
            const response = await apiClient.get(url);
            console.log('✅ Employés disponibles chargés:', response.data);
            setEmployes(response.data || []);
        } catch (error) {
            console.error('❌ Erreur lors du chargement des employés disponibles:', error);
            setEmployes([]);
        } finally {
            setLoading(false);
        }
    };

    const metierBodyTemplate = (rowData: EmployeDisponible) => {
        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 experienceBodyTemplate = (rowData: EmployeDisponible) => {
        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 disponibiliteBodyTemplate = (rowData: EmployeDisponible) => {
        return (
            <div className="flex flex-column gap-1">
                <div className="flex align-items-center gap-2">
                    <i className="pi pi-check-circle text-green-500" />
                    <span className="text-green-600 font-medium">Disponible</span>
                </div>
                {rowData.disponibleJusquau && (
                    <small className="text-500">
                        Jusqu'au {new Date(rowData.disponibleJusquau).toLocaleDateString('fr-FR')}
                    </small>
                )}
            </div>
        );
    };

    const prochainChantierBodyTemplate = (rowData: EmployeDisponible) => {
        if (rowData.prochainChantier) {
            return (
                <div className="flex flex-column gap-1">
                    <Tag value={rowData.prochainChantier} severity="warning" />
                    {rowData.dateProchainChantier && (
                        <small className="text-500">
                            Début: {new Date(rowData.dateProchainChantier).toLocaleDateString('fr-FR')}
                        </small>
                    )}
                </div>
            );
        }
        return <span className="text-500">Aucun</span>;
    };

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

    const actionBodyTemplate = (rowData: EmployeDisponible) => {
        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-plus"
                    className="p-button-rounded p-button-success p-button-sm"
                    onClick={() => router.push(`/planning?employeId=${rowData.id}`)}
                    tooltip="Planifier"
                />
                <Button
                    icon="pi pi-users"
                    className="p-button-rounded p-button-help p-button-sm"
                    onClick={() => router.push(`/equipes?assignEmploye=${rowData.id}`)}
                    tooltip="Affecter à une équipe"
                />
                <Button
                    icon="pi pi-send"
                    className="p-button-rounded p-button-warning p-button-sm"
                    onClick={() => router.push(`/chantiers?assignEmploye=${rowData.id}`)}
                    tooltip="Affecter à un chantier"
                />
            </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="Employés actifs"
                    icon="pi pi-check-circle"
                    className="p-button-info"
                    onClick={() => router.push('/employes/actifs')}
                />
                <Button
                    label="Planifier équipe"
                    icon="pi pi-users"
                    className="p-button-success"
                    onClick={() => router.push('/equipes/optimal')}
                />
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <div className="flex gap-2">
                <Calendar
                    value={dateRecherche}
                    onChange={(e) => setDateRecherche(e.value as Date)}
                    placeholder="Date de recherche"
                    dateFormat="dd/mm/yy"
                    showIcon
                />
                <Dropdown
                    value={metierFiltre}
                    options={metierOptions}
                    onChange={(e) => setMetierFiltre(e.value)}
                    placeholder="Filtrer par métier"
                />
                <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={loadEmployesDisponibles}
                    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 Disponibles ({employes.length})</h2>
            <div className="flex gap-2 mt-2 md:mt-0">
                <Badge value={employes.filter(e => !e.prochainChantier).length} severity="success" />
                <span>Libres</span>
                <Badge value={employes.filter(e => e.prochainChantier).length} severity="warning" />
                <span>Avec prochain chantier</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 disponibles"
                        globalFilter={globalFilter}
                        emptyMessage="Aucun employé disponible 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="disponible" header="Disponibilité" body={disponibiliteBodyTemplate} />
                        <Column field="prochainChantier" header="Prochain chantier" body={prochainChantierBodyTemplate} />
                        <Column field="competences" header="Compétences" body={competencesBodyTemplate} />
                        <Column field="email" header="Email" sortable />
                        <Column body={actionBodyTemplate} header="Actions" style={{ minWidth: '12rem' }} />
                    </DataTable>
                </Card>
            </div>
        </div>
    );
};

export default EmployesDisponiblesPage;
