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


import React, { useState, useEffect } from 'react';
import RoleProtectedPage from '@/components/RoleProtectedPage';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { Dropdown } from 'primereact/dropdown';
import { Tag } from 'primereact/tag';
import { Card } from 'primereact/card';
import { Toolbar } from 'primereact/toolbar';
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 Employe {
    id: number;
    nom: string;
    prenom: string;
    email: string;
    telephone: string;
    metier: string;
    statut: 'ACTIF' | 'INACTIF' | 'CONGE' | 'FORMATION';
    dateEmbauche: string;
    salaire: number;
    equipeId?: number;
    competences: string[];
    certifications: string[];
}

const EmployesPageContent = () => {
    const [employes, setEmployes] = useState<Employe[]>([]);
    const [loading, setLoading] = useState(true);
    const [globalFilter, setGlobalFilter] = useState('');
    const [selectedEmployes, setSelectedEmployes] = useState<Employe[]>([]);
    const [deleteDialog, setDeleteDialog] = useState(false);
    const [employeToDelete, setEmployeToDelete] = useState<Employe | null>(null);
    const router = useRouter();

    const statutOptions = [
        { label: 'Tous', value: null },
        { label: 'Actif', value: 'ACTIF' },
        { label: 'Inactif', value: 'INACTIF' },
        { label: 'Congé', value: 'CONGE' },
        { label: 'Formation', value: 'FORMATION' }
    ];

    const metierOptions = [
        { label: 'Tous', value: null },
        { 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(() => {
        loadEmployes();
    }, []);

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

    const confirmDeleteEmploye = (employe: Employe) => {
        setEmployeToDelete(employe);
        setDeleteDialog(true);
    };

    const deleteEmploye = async () => {
        if (employeToDelete) {
            try {
                await apiClient.delete(`/api/employes/${employeToDelete.id}`);
                setEmployes(employes.filter(e => e.id !== employeToDelete.id));
                setDeleteDialog(false);
                setEmployeToDelete(null);
                console.log('✅ Employé supprimé avec succès');
            } catch (error) {
                console.error('❌ Erreur lors de la suppression:', error);
            }
        }
    };

    const toggleStatutEmploye = async (employe: Employe) => {
        try {
            const newStatut = employe.statut === 'ACTIF' ? 'INACTIF' : 'ACTIF';
            const endpoint = newStatut === 'ACTIF' ? 'activer' : 'desactiver';
            
            await apiClient.post(`/api/employes/${employe.id}/${endpoint}`);
            
            setEmployes(employes.map(e => 
                e.id === employe.id ? { ...e, statut: newStatut } : e
            ));
            
            console.log(`✅ Statut employé ${newStatut.toLowerCase()}`);
        } catch (error) {
            console.error('❌ Erreur lors du changement de statut:', error);
        }
    };

    const statutBodyTemplate = (rowData: Employe) => {
        const getSeverity = (statut: string) => {
            switch (statut) {
                case 'ACTIF': return 'success';
                case 'INACTIF': return 'danger';
                case 'CONGE': return 'warning';
                case 'FORMATION': return 'info';
                default: return 'secondary';
            }
        };

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

    const actionBodyTemplate = (rowData: Employe) => {
        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-pencil"
                    className="p-button-rounded p-button-success p-button-sm"
                    onClick={() => router.push(`/employes/${rowData.id}/edit`)}
                    tooltip="Modifier"
                />
                <Button
                    icon={rowData.statut === 'ACTIF' ? 'pi pi-pause' : 'pi pi-play'}
                    className={`p-button-rounded p-button-sm ${
                        rowData.statut === 'ACTIF' ? 'p-button-warning' : 'p-button-success'
                    }`}
                    onClick={() => toggleStatutEmploye(rowData)}
                    tooltip={rowData.statut === 'ACTIF' ? 'Désactiver' : 'Activer'}
                />
                <Button
                    icon="pi pi-trash"
                    className="p-button-rounded p-button-danger p-button-sm"
                    onClick={() => confirmDeleteEmploye(rowData)}
                    tooltip="Supprimer"
                />
            </div>
        );
    };

    const competencesBodyTemplate = (rowData: Employe) => {
        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 && (
                    <Tag value={`+${rowData.competences.length - 3}`} className="p-tag-sm" />
                )}
            </div>
        );
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="flex flex-wrap gap-2">
                <Button
                    label="Nouvel Employé"
                    icon="pi pi-plus"
                    className="p-button-success"
                    onClick={() => router.push('/employes/nouveau')}
                />
                <Button
                    label="Employés Actifs"
                    icon="pi pi-check-circle"
                    className="p-button-info"
                    onClick={() => router.push('/employes/actifs')}
                />
                <Button
                    label="Disponibles"
                    icon="pi pi-calendar-check"
                    className="p-button-help"
                    onClick={() => router.push('/employes/disponibles')}
                />
                <Button
                    label="Statistiques"
                    icon="pi pi-chart-bar"
                    className="p-button-secondary"
                    onClick={() => router.push('/employes/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={loadEmployes}
                    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 Employés</h2>
            <span className="block mt-2 md:mt-0 p-input-icon-left">
                <i className="pi pi-search" />
                <InputText
                    type="search"
                    placeholder="Recherche globale..."
                    value={globalFilter}
                    onChange={(e) => setGlobalFilter(e.target.value)}
                />
            </span>
        </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"
                        globalFilter={globalFilter}
                        emptyMessage="Aucun employé trouvé."
                        header={header}
                        selection={selectedEmployes}
                        onSelectionChange={(e) => setSelectedEmployes(e.value)}
                        selectionMode="multiple"
                        responsiveLayout="scroll"
                    >
                        <Column selectionMode="multiple" headerStyle={{ width: '3rem' }} />
                        <Column field="nom" header="Nom" sortable />
                        <Column field="prenom" header="Prénom" sortable />
                        <Column field="email" header="Email" sortable />
                        <Column field="metier" header="Métier" sortable />
                        <Column field="statut" header="Statut" body={statutBodyTemplate} sortable />
                        <Column field="competences" header="Compétences" body={competencesBodyTemplate} />
                        <Column field="dateEmbauche" header="Date d'embauche" sortable />
                        <Column body={actionBodyTemplate} header="Actions" style={{ minWidth: '12rem' }} />
                    </DataTable>
                </Card>
            </div>

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

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

const EmployesPage = () => {
    return (
        <RoleProtectedPage
            requiredPage="EMPLOYES"
            fallbackMessage="Vous devez avoir un rôle de manager ou supérieur pour accéder aux employés."
        >
            <EmployesPageContent />
        </RoleProtectedPage>
    );
};

export default EmployesPage;
