'use client';

import React, { useState, useEffect } from 'react';
import { Card } from 'primereact/card';
import { Button } from 'primereact/button';
import { InputText } from 'primereact/inputtext';
import { Dropdown } from 'primereact/dropdown';
import { MultiSelect } from 'primereact/multiselect';
import { Calendar } from 'primereact/calendar';
import { InputNumber } from 'primereact/inputnumber';
import { Tag } from 'primereact/tag';
import { Badge } from 'primereact/badge';
import { Toolbar } from 'primereact/toolbar';
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { ProgressBar } from 'primereact/progressbar';
import { Message } from 'primereact/message';
import { useRouter } from 'next/navigation';
import { apiClient } from '../../../../services/api-client';

interface CriteresRecherche {
    specialite: string;
    competencesRequises: string[];
    nombreEmployesMin: number;
    nombreEmployesMax: number;
    dateDebut: Date | null;
    dateFin: Date | null;
    budgetMaxJournalier: number | null;
    localisation?: string;
    niveauExperienceMin: string;
    evaluationMin: number;
}

interface EquipeRecommandee {
    id: number;
    nom: string;
    specialite: string;
    nombreEmployes: number;
    chefEquipeNom?: string;
    competencesEquipe: string[];
    scoreCompatibilite: number; // sur 100
    coutJournalier: number;
    disponibilite: {
        dateDebut: string;
        dateFin: string;
        dureeDisponible: number;
    };
    evaluationPerformance: number;
    localisation: string;
    avantages: string[];
    inconvenients: string[];
    employes: Array<{
        id: number;
        nom: string;
        prenom: string;
        metier: string;
        niveauExperience: string;
        competences: string[];
    }>;
}

const EquipeOptimalePage = () => {
    const [criteres, setCriteres] = useState<CriteresRecherche>({
        specialite: '',
        competencesRequises: [],
        nombreEmployesMin: 3,
        nombreEmployesMax: 8,
        dateDebut: null,
        dateFin: null,
        budgetMaxJournalier: null,
        niveauExperienceMin: 'DEBUTANT',
        evaluationMin: 3
    });
    const [equipesRecommandees, setEquipesRecommandees] = useState<EquipeRecommandee[]>([]);
    const [loading, setLoading] = useState(false);
    const [rechercheLancee, setRechercheLancee] = useState(false);
    const router = useRouter();

    const specialiteOptions = [
        { 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' }
    ];

    const competencesOptions = [
        { label: 'Maçonnerie', value: 'MACONNERIE' },
        { label: 'Coffrage', value: 'COFFRAGE' },
        { label: 'Ferraillage', value: 'FERRAILLAGE' },
        { label: 'Électricité générale', value: 'ELECTRICITE_GENERALE' },
        { label: 'Plomberie sanitaire', value: 'PLOMBERIE_SANITAIRE' },
        { label: 'Chauffage', value: 'CHAUFFAGE' },
        { label: 'Charpente bois', value: 'CHARPENTE_BOIS' },
        { label: 'Couverture tuile', value: 'COUVERTURE_TUILE' },
        { label: 'Peinture', value: 'PEINTURE' },
        { label: 'Carrelage', value: 'CARRELAGE' },
        { label: 'Terrassement', value: 'TERRASSEMENT' }
    ];

    const niveauExperienceOptions = [
        { label: 'Débutant', value: 'DEBUTANT' },
        { label: 'Intermédiaire', value: 'INTERMEDIAIRE' },
        { label: 'Confirmé', value: 'CONFIRME' },
        { label: 'Expert', value: 'EXPERT' }
    ];

    const rechercherEquipesOptimales = async () => {
        if (!criteres.specialite) {
            return;
        }

        try {
            setLoading(true);
            setRechercheLancee(true);
            console.log('🔄 Recherche d\'équipes optimales...', criteres);

            const response = await apiClient.post('/api/equipes/recommandations', criteres);
            console.log('✅ Équipes recommandées:', response.data);
            setEquipesRecommandees(response.data || []);
        } catch (error) {
            console.error('❌ Erreur lors de la recherche:', error);
            setEquipesRecommandees([]);
        } finally {
            setLoading(false);
        }
    };

    const getScoreColor = (score: number) => {
        if (score >= 90) return 'success';
        if (score >= 75) return 'info';
        if (score >= 60) return 'warning';
        return 'danger';
    };

    const scoreBodyTemplate = (rowData: EquipeRecommandee) => {
        return (
            <div className="flex align-items-center gap-2">
                <Tag value={`${rowData.scoreCompatibilite}%`} severity={getScoreColor(rowData.scoreCompatibilite)} />
                <ProgressBar value={rowData.scoreCompatibilite} className="w-6rem" />
            </div>
        );
    };

    const specialiteBodyTemplate = (rowData: EquipeRecommandee) => {
        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 competencesBodyTemplate = (rowData: EquipeRecommandee) => {
        const competencesCorrespondantes = rowData.competencesEquipe.filter(comp => 
            criteres.competencesRequises.includes(comp)
        );

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

    const disponibiliteBodyTemplate = (rowData: EquipeRecommandee) => {
        return (
            <div className="flex flex-column gap-1">
                <span className="font-medium">
                    {new Date(rowData.disponibilite.dateDebut).toLocaleDateString('fr-FR')} - 
                    {new Date(rowData.disponibilite.dateFin).toLocaleDateString('fr-FR')}
                </span>
                <span className="text-sm text-500">
                    {rowData.disponibilite.dureeDisponible} jours
                </span>
            </div>
        );
    };

    const coutBodyTemplate = (rowData: EquipeRecommandee) => {
        const isInBudget = !criteres.budgetMaxJournalier || rowData.coutJournalier <= criteres.budgetMaxJournalier;
        
        return (
            <div className="flex flex-column gap-1">
                <span className={`font-medium ${isInBudget ? 'text-green-500' : 'text-red-500'}`}>
                    {rowData.coutJournalier.toLocaleString('fr-FR')} €/jour
                </span>
                <span className="text-sm text-500">
                    {rowData.nombreEmployes} employés
                </span>
            </div>
        );
    };

    const performanceBodyTemplate = (rowData: EquipeRecommandee) => {
        return (
            <div className="flex align-items-center gap-2">
                <Tag value={`${rowData.evaluationPerformance}/5`} severity="success" />
                <div className="flex">
                    {[1, 2, 3, 4, 5].map((star) => (
                        <i
                            key={star}
                            className={`pi pi-star${star <= rowData.evaluationPerformance ? '-fill' : ''} text-yellow-500`}
                            style={{ fontSize: '0.8rem' }}
                        />
                    ))}
                </div>
            </div>
        );
    };

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

    const actionBodyTemplate = (rowData: EquipeRecommandee) => {
        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-calendar-plus"
                    className="p-button-rounded p-button-success p-button-sm"
                    onClick={() => router.push(`/planning/assigner?equipeId=${rowData.id}`)}
                    tooltip="Assigner"
                />
                <Button
                    icon="pi pi-users"
                    className="p-button-rounded p-button-warning p-button-sm"
                    onClick={() => router.push(`/equipes/${rowData.id}/employes`)}
                    tooltip="Voir employés"
                />
            </div>
        );
    };

    const leftToolbarTemplate = () => {
        return (
            <div className="flex flex-wrap gap-2">
                <Button
                    label="Retour aux équipes"
                    icon="pi pi-arrow-left"
                    className="p-button-outlined"
                    onClick={() => router.push('/equipes')}
                />
                <Button
                    label="Équipes disponibles"
                    icon="pi pi-check-circle"
                    className="p-button-info"
                    onClick={() => router.push('/equipes/disponibles')}
                />
            </div>
        );
    };

    const rightToolbarTemplate = () => {
        return (
            <div className="flex gap-2">
                <Button
                    label="Réinitialiser"
                    icon="pi pi-refresh"
                    className="p-button-outlined"
                    onClick={() => {
                        setCriteres({
                            specialite: '',
                            competencesRequises: [],
                            nombreEmployesMin: 3,
                            nombreEmployesMax: 8,
                            dateDebut: null,
                            dateFin: null,
                            budgetMaxJournalier: null,
                            niveauExperienceMin: 'DEBUTANT',
                            evaluationMin: 3
                        });
                        setEquipesRecommandees([]);
                        setRechercheLancee(false);
                    }}
                />
                <Button
                    label="Rechercher"
                    icon="pi pi-search"
                    className="p-button-success"
                    loading={loading}
                    onClick={rechercherEquipesOptimales}
                    disabled={!criteres.specialite}
                />
            </div>
        );
    };

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

            {/* Formulaire de critères */}
            <div className="col-12 lg:col-4">
                <Card title="Critères de recherche" className="h-full">
                    <div className="p-fluid">
                        <div className="field">
                            <label htmlFor="specialite" className="font-medium">Spécialité *</label>
                            <Dropdown
                                id="specialite"
                                value={criteres.specialite}
                                options={specialiteOptions}
                                onChange={(e) => setCriteres({ ...criteres, specialite: e.value })}
                                placeholder="Sélectionner une spécialité"
                            />
                        </div>

                        <div className="field">
                            <label htmlFor="competences" className="font-medium">Compétences requises</label>
                            <MultiSelect
                                id="competences"
                                value={criteres.competencesRequises}
                                options={competencesOptions}
                                onChange={(e) => setCriteres({ ...criteres, competencesRequises: e.value })}
                                placeholder="Sélectionner les compétences"
                                filter
                            />
                        </div>

                        <div className="grid">
                            <div className="col-6">
                                <div className="field">
                                    <label className="font-medium">Employés min</label>
                                    <InputNumber
                                        value={criteres.nombreEmployesMin}
                                        onValueChange={(e) => setCriteres({ ...criteres, nombreEmployesMin: e.value || 1 })}
                                        min={1}
                                        max={20}
                                    />
                                </div>
                            </div>
                            <div className="col-6">
                                <div className="field">
                                    <label className="font-medium">Employés max</label>
                                    <InputNumber
                                        value={criteres.nombreEmployesMax}
                                        onValueChange={(e) => setCriteres({ ...criteres, nombreEmployesMax: e.value || 8 })}
                                        min={1}
                                        max={20}
                                    />
                                </div>
                            </div>
                        </div>

                        <div className="grid">
                            <div className="col-6">
                                <div className="field">
                                    <label className="font-medium">Date début</label>
                                    <Calendar
                                        value={criteres.dateDebut}
                                        onChange={(e) => setCriteres({ ...criteres, dateDebut: e.value as Date })}
                                        showIcon
                                        dateFormat="dd/mm/yy"
                                    />
                                </div>
                            </div>
                            <div className="col-6">
                                <div className="field">
                                    <label className="font-medium">Date fin</label>
                                    <Calendar
                                        value={criteres.dateFin}
                                        onChange={(e) => setCriteres({ ...criteres, dateFin: e.value as Date })}
                                        showIcon
                                        dateFormat="dd/mm/yy"
                                    />
                                </div>
                            </div>
                        </div>

                        <div className="field">
                            <label className="font-medium">Budget max/jour (€)</label>
                            <InputNumber
                                value={criteres.budgetMaxJournalier}
                                onValueChange={(e) => setCriteres({ ...criteres, budgetMaxJournalier: e.value })}
                                mode="currency"
                                currency="EUR"
                                locale="fr-FR"
                            />
                        </div>

                        <div className="field">
                            <label className="font-medium">Niveau d'expérience minimum</label>
                            <Dropdown
                                value={criteres.niveauExperienceMin}
                                options={niveauExperienceOptions}
                                onChange={(e) => setCriteres({ ...criteres, niveauExperienceMin: e.value })}
                            />
                        </div>

                        <div className="field">
                            <label className="font-medium">Évaluation minimum</label>
                            <InputNumber
                                value={criteres.evaluationMin}
                                onValueChange={(e) => setCriteres({ ...criteres, evaluationMin: e.value || 1 })}
                                min={1}
                                max={5}
                                suffix="/5"
                            />
                        </div>

                        <div className="field">
                            <label className="font-medium">Localisation</label>
                            <InputText
                                value={criteres.localisation || ''}
                                onChange={(e) => setCriteres({ ...criteres, localisation: e.target.value })}
                                placeholder="Ville ou région"
                            />
                        </div>
                    </div>
                </Card>
            </div>

            {/* Résultats */}
            <div className="col-12 lg:col-8">
                <Card>
                    {!rechercheLancee ? (
                        <div className="text-center p-6">
                            <i className="pi pi-search text-6xl text-300 mb-4" />
                            <h3 className="text-500">Recherche d'équipe optimale</h3>
                            <p className="text-600 mb-4">
                                Remplissez les critères de recherche et cliquez sur "Rechercher" 
                                pour obtenir les meilleures recommandations d'équipes.
                            </p>
                            <Message 
                                severity="info" 
                                text="L'algorithme prend en compte la compatibilité des compétences, la disponibilité, les performances passées et le budget." 
                            />
                        </div>
                    ) : loading ? (
                        <div className="text-center p-6">
                            <i className="pi pi-spin pi-spinner text-4xl text-blue-500 mb-4" />
                            <h3>Recherche en cours...</h3>
                            <p className="text-600">Analyse des équipes disponibles et calcul des scores de compatibilité.</p>
                        </div>
                    ) : equipesRecommandees.length === 0 ? (
                        <div className="text-center p-6">
                            <i className="pi pi-exclamation-triangle text-6xl text-orange-500 mb-4" />
                            <h3 className="text-500">Aucune équipe trouvée</h3>
                            <p className="text-600">
                                Aucune équipe ne correspond à vos critères. 
                                Essayez d'assouplir certains paramètres.
                            </p>
                        </div>
                    ) : (
                        <>
                            <div className="flex justify-content-between align-items-center mb-4">
                                <h3 className="m-0">Équipes recommandées</h3>
                                <div className="flex gap-2">
                                    <Badge value={equipesRecommandees.length} severity="success" />
                                    <span>équipes trouvées</span>
                                </div>
                            </div>

                            <DataTable
                                value={equipesRecommandees}
                                responsiveLayout="scroll"
                                sortField="scoreCompatibilite"
                                sortOrder={-1}
                                paginator
                                rows={5}
                                emptyMessage="Aucune équipe recommandée"
                            >
                                <Column field="scoreCompatibilite" header="Score" body={scoreBodyTemplate} sortable />
                                <Column field="nom" header="Nom" sortable />
                                <Column field="specialite" header="Spécialité" body={specialiteBodyTemplate} />
                                <Column field="competencesEquipe" header="Compétences" body={competencesBodyTemplate} />
                                <Column field="disponibilite" header="Disponibilité" body={disponibiliteBodyTemplate} />
                                <Column field="coutJournalier" header="Coût" body={coutBodyTemplate} sortable />
                                <Column field="evaluationPerformance" header="Performance" body={performanceBodyTemplate} sortable />
                                <Column field="avantages" header="Avantages" body={avantagesBodyTemplate} />
                                <Column body={actionBodyTemplate} header="Actions" style={{ minWidth: '10rem' }} />
                            </DataTable>
                        </>
                    )}
                </Card>
            </div>
        </div>
    );
};

export default EquipeOptimalePage;
