import { useState, useEffect } from 'react';
import { CheckCircle, MoreVertical, Eye, Star } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { Button } from '@/components/ui/button';
import { rhService } from '@/services/rhService';
import { PerformanceEvaluationDTO } from '@/types/rh';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { StatusBadge } from '@/components/common/StatusBadge';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

export function PerformanceEvaluationsPage() {
    const [evaluations, setEvaluations] = useState<PerformanceEvaluationDTO[]>([]);
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState(0);
    const [totalPages, setTotalPages] = useState(0);
    const [totalElements, setTotalElements] = useState(0);
    const [isFinalizeDialogOpen, setIsFinalizeDialogOpen] = useState(false);
    const [selectedEvaluation, setSelectedEvaluation] = useState<PerformanceEvaluationDTO | null>(null);

    useEffect(() => {
        loadEvaluations();
    }, [page]);

    const loadEvaluations = async () => {
        try {
            setLoading(true);
            const response = await rhService.getEvaluations({
                page,
                size: 20,
                sortBy: 'evaluationDate',
                sortDirection: 'DESC',
            });
            setEvaluations(response.content);
            setTotalPages(response.totalPages);
            setTotalElements(response.totalElements);
        } catch (error) {
            toast.error('Erro ao carregar avaliações');
        } finally {
            setLoading(false);
        }
    };

    const handleFinalize = (evaluation: PerformanceEvaluationDTO) => {
        setSelectedEvaluation(evaluation);
        setIsFinalizeDialogOpen(true);
    };

    const handleFinalizeConfirm = async () => {
        if (!selectedEvaluation) return;
        try {
            await rhService.finalizeEvaluation(selectedEvaluation.id);
            toast.success('Avaliação finalizada com sucesso. Promoções automáticas foram processadas se aplicável.');
            setIsFinalizeDialogOpen(false);
            setSelectedEvaluation(null);
            loadEvaluations();
        } catch (error: any) {
            toast.error(error.message || 'Erro ao finalizar avaliação');
        }
    };

    const columns = [
        {
            key: 'agentName',
            header: 'Agente',
            cell: (ev: PerformanceEvaluationDTO) => ev.agentName || ev.agentId,
        },
        {
            key: 'evaluationDate',
            header: 'Data',
            cell: (ev: PerformanceEvaluationDTO) => format(new Date(ev.evaluationDate), 'dd/MM/yyyy'),
        },
        {
            key: 'score',
            header: 'Pontuação',
            cell: (ev: PerformanceEvaluationDTO) => (
                <div className="flex items-center gap-2">
                    <span className="font-bold">{ev.score}</span>
                    <span className="text-xs text-muted-foreground">/ 20</span>
                </div>
            ),
        },
        {
            key: 'mention',
            header: 'Menção',
            cell: (ev: PerformanceEvaluationDTO) => {
                const isGood = ['BOM', 'MUITO BOM', 'EXCELENTE'].includes(ev.mention.toUpperCase());
                return (
                    <span className={`font-semibold ${isGood ? 'text-green-600' : 'text-amber-600'}`}>
                        {ev.mention}
                    </span>
                );
            },
        },
        {
            key: 'status',
            header: 'Status',
            cell: (ev: PerformanceEvaluationDTO) => (
                <StatusBadge status={ev.status === 'FINALIZED' ? 'completed' : 'draft'} />
            ),
        },
        {
            key: 'actions',
            header: 'Ações',
            cell: (ev: PerformanceEvaluationDTO) => (
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="sm">
                            <MoreVertical className="h-4 w-4" />
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                        <DropdownMenuItem>
                            <Eye className="mr-2 h-4 w-4" />
                            Ver Detalhes
                        </DropdownMenuItem>
                        {ev.status === 'DRAFT' && (
                            <DropdownMenuItem onClick={() => handleFinalize(ev)}>
                                <CheckCircle className="mr-2 h-4 w-4" />
                                Finalizar
                            </DropdownMenuItem>
                        )}
                    </DropdownMenuContent>
                </DropdownMenu>
            ),
        },
    ];

    return (
        <div className="space-y-6">
            <PageHeader
                title="Avaliações de Desempenho"
                description="Gestão de avaliações e progressões automáticas de carreira"
                icon={Star}
            />

            <ServerDataTable
                data={evaluations}
                columns={columns}
                loading={loading}
                page={page}
                totalPages={totalPages}
                totalElements={totalElements}
                onPageChange={setPage}
                emptyMessage="Nenhuma avaliação encontrada"
            />

            <ConfirmDialog
                open={isFinalizeDialogOpen}
                onOpenChange={setIsFinalizeDialogOpen}
                title="Finalizar Avaliação"
                description="Ao finalizar, a menção será gravada permanentemente. Se o agente completar 3 anos consecutivos com menção 'Bom' ou superior, uma promoção automática será gerada. Deseja continuar?"
                onConfirm={handleFinalizeConfirm}
            />
        </div>
    );
}
