import { useState } from 'react';
import { Plus, Edit, Trash2, MoreVertical } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { usePositions } from '@/hooks/usePositions';
import { PositionDTO } from '@/types/org';
import { useToast } from '@/hooks/use-toast';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { PositionFormModal } from './components/PositionFormModal';

export function PositionList() {
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedPosition, setSelectedPosition] = useState<PositionDTO | null>(null);
    const [isFormOpen, setIsFormOpen] = useState(false);
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);
    const { toast } = useToast();

    const {
        positions,
        loading,
        error,
        page,
        totalPages,
        totalElements,
        setPage,
        createPosition,
        updatePosition,
    } = usePositions({
        page: 0,
        size: 20,
        sortBy: 'code',
        sortDirection: 'ASC',
    });

    const filteredPositions = positions.filter((pos) =>
        pos.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        pos.code.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const handleCreate = () => {
        setSelectedPosition(null);
        setIsFormOpen(true);
    };

    const handleEdit = (position: PositionDTO) => {
        setSelectedPosition(position);
        setIsFormOpen(true);
    };

    const handleDelete = (position: PositionDTO) => {
        setSelectedPosition(position);
        setIsDeleteOpen(true);
    };

    const handleDeleteConfirm = async () => {
        if (!selectedPosition) return;
        toast({
            title: 'Info',
            description: 'Funcionalidade de exclusão ainda não implementada na API',
        });
        setIsDeleteOpen(false);
        setSelectedPosition(null);
    };

    const handleFormSubmit = async (data: any) => {
        try {
            if (selectedPosition) {
                await updatePosition(selectedPosition.id, data);
                toast({
                    title: 'Sucesso',
                    description: 'Cargo atualizado com sucesso',
                });
            } else {
                await createPosition(data);
                toast({
                    title: 'Sucesso',
                    description: 'Cargo criado com sucesso',
                });
            }
            setIsFormOpen(false);
            setSelectedPosition(null);
        } catch (err: any) {
            toast({
                title: 'Erro',
                description: err.message || 'Erro ao salvar cargo',
                variant: 'destructive',
            });
        }
    };

    const columns = [
        {
            key: 'code',
            header: 'Código',
            cell: (pos: PositionDTO) => pos.code,
        },
        {
            key: 'title',
            header: 'Título',
            cell: (pos: PositionDTO) => <span className="font-medium">{pos.title}</span>,
        },
        {
            key: 'level',
            header: 'Nível',
            cell: (pos: PositionDTO) => pos.level,
        },
        {
            key: 'isManagerial',
            header: 'Chefia',
            cell: (pos: PositionDTO) => (
                <span className={pos.isManagerial ? 'text-green-600 font-bold' : 'text-gray-500'}>
                    {pos.isManagerial ? 'Sim' : 'Não'}
                </span>
            ),
        },
        {
            key: 'actions',
            header: 'Ações',
            cell: (pos: PositionDTO) => (
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="sm">
                            <MoreVertical className="h-4 w-4" />
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => handleEdit(pos)}>
                            <Edit className="mr-2 h-4 w-4" />
                            Editar
                        </DropdownMenuItem>
                        <DropdownMenuItem
                            onClick={() => handleDelete(pos)}
                            className="text-destructive"
                        >
                            <Trash2 className="mr-2 h-4 w-4" />
                            Excluir
                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenu>
            ),
        },
    ];

    return (
        <div className="space-y-6">
            <PageHeader
                title="Cargos e Funções"
                description="Gestão de Cargos, Funções e Categorias Profissionais"
            />

            <div className="flex items-center justify-end gap-4">
                <Button onClick={handleCreate}>
                    <Plus className="mr-2 h-4 w-4" />
                    Novo Cargo
                </Button>
            </div>

            <ServerDataTable
                data={filteredPositions}
                columns={columns}
                loading={loading}
                error={error}
                page={page}
                totalPages={totalPages}
                totalElements={totalElements}
                pageSize={20}
                onPageChange={setPage}
                onSearch={setSearchTerm}
                searchPlaceholder="Pesquisar por título ou código..."
                emptyMessage="Nenhum cargo encontrado"
            />

            <PositionFormModal
                open={isFormOpen}
                onOpenChange={setIsFormOpen}
                position={selectedPosition}
                onSubmit={handleFormSubmit}
            />

            <ConfirmDialog
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                title="Excluir Cargo"
                description={`Tem certeza que deseja excluir o cargo "${selectedPosition?.title}"?`}
                onConfirm={handleDeleteConfirm}
            />
        </div>
    );
}
