import { useState, useEffect, useMemo, Fragment } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { toast } from "sonner";
import {
    SalaryCategoryDTO,
    SalaryGradeDTO,
    SalaryStepDTO,
    SalaryGridDTO,
    CareerRegimeDTO
} from "@/types/salary";
import { salaryService } from "@/services/salaryService";
import { careerRegimeService } from "@/services/careerRegimeService";
import { Plus, Search, Filter, ChevronDown, ChevronUp, Save, Trash2, Edit2, Coins, Briefcase, FileDown, FileSpreadsheet, FileText, Check, ChevronsUpDown, Settings } from "lucide-react";
import { cn } from "@/lib/utils";
import { exportSalaryToExcel, exportSalaryToPDF } from "@/utils/salaryExportUtils";
import { positionService, PositionDTO } from "@/services/positionService";
import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandInput,
    CommandItem,
    CommandList,
} from "@/components/ui/command";
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover";

import { SalarySettingsDialog } from "../components/SalarySettingsDialog";

// Combined Type for the Table Row
type SalaryRow = {
    grade: SalaryGradeDTO;
    categoryName: string;
    steps: {
        step: SalaryStepDTO;
        currentValue: number | null;
        gridEntry: SalaryGridDTO | null;
    }[];
};

export function SalaryStructurePage() {
    // Data State
    const [regimes, setRegimes] = useState<CareerRegimeDTO[]>([]);
    const [categories, setCategories] = useState<SalaryCategoryDTO[]>([]);
    const [rows, setRows] = useState<SalaryRow[]>([]);
    const [loading, setLoading] = useState(true);

    // UI State
    const [searchTerm, setSearchTerm] = useState("");
    const [selectedRegimeId, setSelectedRegimeId] = useState<string>("all");
    const [categoryFilter, setCategoryFilter] = useState("all");
    const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
    const [isAddModalOpen, setIsAddModalOpen] = useState(false);
    const [isSettingsOpen, setIsSettingsOpen] = useState(false);

    // Pagination State (Standard 0-based)
    const [page, setPage] = useState(0);
    const [pageSize, setPageSize] = useState(10);

    // Initial Load
    useEffect(() => {
        loadData();
    }, []);

    const loadData = async () => {
        setLoading(true);
        try {
            // 0. Fetch Regimes
            const loadedRegimes = await careerRegimeService.getAll();
            setRegimes(loadedRegimes);

            // 1. Fetch Entire Structure in one call
            const structure = await salaryService.getSummary();

            // Map the API structure to the flat SalaryRow format used by the table
            const allRows: SalaryRow[] = [];

            structure.categories.forEach(cat => {
                cat.grades.forEach(grade => {
                    allRows.push({
                        grade: {
                            id: grade.id,
                            categoryId: cat.id,
                            code: grade.code,
                            name: grade.name
                        },
                        categoryName: cat.name,
                        steps: grade.steps.map(step => ({
                            step: {
                                id: step.id,
                                gradeId: grade.id,
                                stepNumber: step.stepNumber
                            },
                            currentValue: step.currentValue,
                            gridEntry: {
                                id: "", // dummy, not used by display
                                stepId: step.id,
                                baseAmount: step.currentValue || 0,
                                subsidyAmount: step.subsidyAmount || 0,
                                grossAmount: step.grossAmount || 0,
                                validFrom: ""
                            }
                        }))
                    });
                });
            });

            // Update categories list for filters
            setCategories(structure.categories.map(c => ({
                id: c.id,
                code: c.code,
                name: c.name
            })));

            // Sort rows by Code
            allRows.sort((a, b) => a.grade.code.localeCompare(b.grade.code));
            setRows(allRows);

        } catch (error) {
            console.error(error);
            toast.error("Erro ao carregar estrutura salarial.");
        } finally {
            setLoading(false);
        }
    };

    // Derived State: Filtered Rows
    const filteredRows = useMemo(() => {
        return rows.filter(row => {
            const matchesSearch =
                row.grade.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                row.grade.code.toLowerCase().includes(searchTerm.toLowerCase());

            const matchesCategory = categoryFilter === "all" || row.grade.categoryId === categoryFilter;

            // Find category for this row to check Regime
            const cat = categories.find(c => c.id === row.grade.categoryId);
            const matchesRegime = selectedRegimeId === "all" || (cat?.regimeId === selectedRegimeId);

            return matchesSearch && matchesCategory && matchesRegime;
        });
    }, [rows, searchTerm, categoryFilter, selectedRegimeId, categories]);

    // Pagination Logic
    const totalPages = Math.ceil(filteredRows.length / pageSize);
    const paginatedRows = useMemo(() => {
        const start = page * pageSize;
        return filteredRows.slice(start, start + pageSize);
    }, [filteredRows, page, pageSize]);

    // Reset page on filter change
    useEffect(() => {
        setPage(0);
    }, [searchTerm, categoryFilter, selectedRegimeId]);

    // Actions
    const toggleRow = (gradeId: string) => {
        const newSet = new Set(expandedRows);
        if (newSet.has(gradeId)) {
            newSet.delete(gradeId);
        } else {
            newSet.add(gradeId);
        }
        setExpandedRows(newSet);
    };

    const handleSaveValue = async (stepId: string, newValue: number) => {
        try {
            await salaryService.createGridEntry({
                stepId,
                baseAmount: newValue,
                validFrom: new Date().toISOString().split('T')[0]
            });
            toast.success("Valor atualizado!");
            // Refresh data (smart reload preferred, but full reload safer for consistency)
            // Ideally we just update the local state to avoid UI flicker
            setRows(prev => prev.map(row => ({
                ...row,
                steps: row.steps.map(s => {
                    if (s.step.id === stepId) {
                        return { ...s, currentValue: newValue };
                    }
                    return s;
                })
            })));
        } catch (error) {
            toast.error("Erro ao salvar valor.");
        }
    };

    const handleDeleteGrade = async (gradeId: string) => {
        if (!confirm("Tem certeza? Isso apagará o cargo e históricos.")) return;
        try {
            await salaryService.deleteGrade(gradeId);
            setRows(prev => prev.filter(r => r.grade.id !== gradeId));
            toast.success("Cargo removido.");
        } catch (error) {
            toast.error("Falha ao remover.");
        }
    }

    const handleExportExcel = () => {
        if (filteredRows.length === 0) {
            toast.warning("Sem dados para exportar");
            return;
        }
        exportSalaryToExcel(filteredRows, "grelha_salarial_" + new Date().toISOString().slice(0, 10) + ".xlsx");
        toast.success("Exportando Excel...");
    };

    const handleExportPDF = () => {
        if (filteredRows.length === 0) {
            toast.warning("Sem dados para exportar");
            return;
        }
        exportSalaryToPDF(filteredRows, "grelha_salarial_" + new Date().toISOString().slice(0, 10) + ".pdf");
        toast.success("Exportando PDF...");
    };

    return (
        <div className="space-y-6">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h2 className="text-3xl font-bold tracking-tight text-slate-900">Grelha Salarial</h2>
                    <p className="text-slate-500">Gestão integrada de cargos, carreiras e tabelas remuneratórias.</p>
                </div>
                <div className="flex gap-2">
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="outline">
                                <FileDown className="mr-2 h-4 w-4" /> Exportar
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent>
                            <DropdownMenuLabel>Formatos</DropdownMenuLabel>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem onClick={handleExportExcel}>
                                <FileSpreadsheet className="mr-2 h-4 w-4" /> Excel (.xlsx)
                            </DropdownMenuItem>
                            <DropdownMenuItem onClick={handleExportPDF}>
                                <FileText className="mr-2 h-4 w-4" /> PDF (.pdf)
                            </DropdownMenuItem>
                        </DropdownMenuContent>
                    </DropdownMenu>

                    <Button onClick={() => setIsAddModalOpen(true)} className="bg-blue-600 hover:bg-blue-700">
                        <Plus className="mr-2 h-4 w-4" /> Novo Cargo
                    </Button>
                </div>
            </div>

            {/* Filters */}
            <Card>
                <CardContent className="p-4 flex flex-col md:flex-row gap-4 items-center">
                    <div className="relative flex-1 w-full">
                        <Search className="absolute left-2 top-2.5 h-4 w-4 text-slate-400" />
                        <Input
                            placeholder="Buscar por código ou nome do cargo..."
                            className="pl-8"
                            value={searchTerm}
                            onChange={e => setSearchTerm(e.target.value)}
                        />
                    </div>
                    <div className="w-full md:w-[250px]">
                        <Select value={selectedRegimeId} onValueChange={setSelectedRegimeId}>
                            <SelectTrigger>
                                <SelectValue placeholder="Filtrar Regime" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">Todos os Regimes</SelectItem>
                                {regimes.map(r => (
                                    <SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                    <div className="w-full md:w-[250px]">
                        <Select value={categoryFilter} onValueChange={setCategoryFilter}>
                            <SelectTrigger>
                                <SelectValue placeholder="Filtrar Categoria" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">Todas as Categorias</SelectItem>
                                {categories.map(c => (
                                    <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                    <Button variant="outline" size="icon" title="Gerenciar Estrutura" onClick={() => setIsSettingsOpen(true)}>
                        <Settings className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" onClick={loadData} title="Recarregar">
                        <Briefcase className="h-4 w-4" />
                    </Button>
                </CardContent>
            </Card>

            <SalarySettingsDialog
                open={isSettingsOpen}
                onOpenChange={setIsSettingsOpen}
                onSuccess={loadData}
            />

            {/* Old Filters Removed */}

            {/* Main Table */}
            <div className="border rounded-lg bg-white shadow-sm overflow-hidden">
                {loading ? (
                    <div className="p-10 text-center text-slate-500">Carregando estrutura salarial...</div>
                ) : filteredRows.length === 0 ? (
                    <div className="p-10 text-center text-slate-500">Nenhum cargo encontrado.</div>
                ) : (
                    <div className="overflow-x-auto">
                        <table className="w-full text-sm text-left">
                            <thead className="bg-slate-100 text-slate-700 font-semibold uppercase text-xs">
                                <tr>
                                    <th className="p-4 w-[100px]">Código</th>
                                    <th className="p-4 w-[25%]">Cargo / Função</th>
                                    <th className="p-4">Categoria</th>
                                    <th className="p-4 w-[160px]">Salário Base</th>
                                    <th className="p-4 w-[160px]">Subsídio</th>
                                    <th className="p-4 w-[160px]">Total Líquido</th>
                                    <th className="p-4 text-center w-[80px]">Steps</th>
                                    <th className="p-4 text-right w-[80px]">Ações</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {paginatedRows.map(row => {
                                    const expanded = expandedRows.has(row.grade.id);
                                    const step1 = row.steps.find(s => s.step.stepNumber === 1);

                                    return (
                                        <Fragment key={row.grade.id}>
                                            <tr key={row.grade.id} className="hover:bg-slate-50 transition-colors group">
                                                <td className="p-4 font-mono text-slate-600">{row.grade.code}</td>
                                                <td className="p-4 font-medium text-slate-900">{row.grade.name}</td>
                                                <td className="p-4">
                                                    <Badge variant="outline" className="font-normal text-slate-600">
                                                        {row.categoryName}
                                                    </Badge>
                                                </td>
                                                <td className="p-4">
                                                    {/* Quick Edit Step 1 */}
                                                    <div className="flex items-center gap-2">
                                                        <span className="text-slate-400 text-xs">XOF</span>
                                                        <Input
                                                            className="h-8 w-[140px] text-right font-medium"
                                                            type="number"
                                                            defaultValue={step1?.currentValue || ""}
                                                            onBlur={(e) => {
                                                                if (step1) {
                                                                    const val = parseFloat(e.target.value);
                                                                    if (!isNaN(val) && val !== step1.currentValue) {
                                                                        handleSaveValue(step1.step.id, val);
                                                                    }
                                                                }
                                                            }}
                                                        />
                                                    </div>
                                                </td>
                                                <td className="p-4">
                                                    <div className="flex items-center gap-2">
                                                        <span className="text-slate-400 text-xs">XOF</span>
                                                        <span className="font-medium text-slate-700">
                                                            {step1?.gridEntry?.subsidyAmount?.toLocaleString('fr-FR', { minimumFractionDigits: 0 }) || "-"}
                                                        </span>
                                                    </div>
                                                </td>
                                                <td className="p-4">
                                                    <div className="flex items-center gap-2">
                                                        <span className="text-slate-400 text-xs">XOF</span>
                                                        <span className="font-bold text-slate-900">
                                                            {step1?.gridEntry?.grossAmount?.toLocaleString('fr-FR', { minimumFractionDigits: 0 }) || "-"}
                                                        </span>
                                                    </div>
                                                </td>
                                                <td className="p-4 text-center">
                                                    <button
                                                        onClick={() => toggleRow(row.grade.id)}
                                                        className="inline-flex items-center justify-center h-6 w-12 rounded-full bg-slate-100 text-xs font-semibold hover:bg-slate-200 transition-colors"
                                                    >
                                                        {row.steps.length} {expanded ? <ChevronUp className="h-3 w-3 ml-1" /> : <ChevronDown className="h-3 w-3 ml-1" />}
                                                    </button>
                                                </td>
                                                <td className="p-4 text-right">
                                                    <div className="flex justify-end gap-1 opacity-100 md:opacity-0 group-hover:opacity-100 transition-opacity">
                                                        <Button size="icon" variant="ghost" className="h-8 w-8 text-red-500 hover:bg-red-50" onClick={() => handleDeleteGrade(row.grade.id)}>
                                                            <Trash2 className="h-4 w-4" />
                                                        </Button>
                                                    </div>
                                                </td>
                                            </tr>
                                            {/* Expanded Step Details */}
                                            {expanded && (
                                                <tr className="bg-slate-50/50">
                                                    <td colSpan={6} className="p-4 pb-6 shadow-inner">
                                                        <div className="pl-4 border-l-2 border-blue-500 ml-4">
                                                            <h4 className="text-xs font-bold uppercase text-slate-500 mb-3 flex items-center gap-2">
                                                                <Coins className="h-4 w-4" />
                                                                Tabela de Progressão Completa - {row.grade.name}
                                                            </h4>

                                                            <div className="flex flex-wrap gap-4">
                                                                {row.steps.map(stepDetail => (
                                                                    <div key={stepDetail.step.id} className="bg-white border rounded p-3 min-w-[150px] shadow-sm">
                                                                        <div className="flex justify-between items-center mb-2">
                                                                            <span className="text-xs font-semibold text-slate-700 bg-slate-100 px-2 py-0.5 rounded">
                                                                                Level {stepDetail.step.stepNumber}
                                                                            </span>
                                                                        </div>
                                                                        <div className="flex items-center gap-1">
                                                                            <span className="text-[10px] text-slate-400">XOF</span>
                                                                            <Input
                                                                                className="h-7 text-right text-sm"
                                                                                type="number"
                                                                                defaultValue={stepDetail.currentValue || ""}
                                                                                onBlur={(e) => {
                                                                                    const val = parseFloat(e.target.value);
                                                                                    if (!isNaN(val) && val !== stepDetail.currentValue) {
                                                                                        handleSaveValue(stepDetail.step.id, val);
                                                                                    }
                                                                                }}
                                                                            />
                                                                        </div>
                                                                        <div className="mt-2 text-[10px] text-slate-500 flex justify-between px-1">
                                                                            <span>Sub: {stepDetail.gridEntry?.subsidyAmount?.toLocaleString() || '-'}</span>
                                                                            <span className="font-semibold">Tot: {stepDetail.gridEntry?.grossAmount?.toLocaleString() || '-'}</span>
                                                                        </div>
                                                                    </div>
                                                                ))}

                                                                {/* "Add Step" Placeholder Button (Functionality could be added later) */}
                                                                <div className="flex items-center justify-center border border-dashed rounded p-3 min-w-[100px] text-slate-400 hover:text-blue-600 hover:border-blue-300 cursor-pointer bg-slate-50/50 hover:bg-blue-50/50 transition-colors"
                                                                    onClick={async () => {
                                                                        // Quick add step logic could go here
                                                                        try {
                                                                            await salaryService.createStep({ gradeId: row.grade.id, stepNumber: row.steps.length + 1 });
                                                                            loadData(); // lazy refresh
                                                                            toast.success("Step adicionado");
                                                                        } catch (e) { toast.error("Erro") }
                                                                    }}
                                                                >
                                                                    <Plus className="h-5 w-5" />
                                                                    <span className="text-xs ml-1 font-medium">Novo</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                </tr>
                                            )
                                            }

                                        </Fragment>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            {/* Pagination Controls (Standardized) */}
            {
                !loading && filteredRows.length > 0 && (
                    <div className="p-4 border-t border-slate-100 bg-white">
                        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                            <div className="flex items-center gap-2">
                                <span className="text-sm text-slate-500">Linhas por página:</span>
                                <Select
                                    value={String(pageSize)}
                                    onValueChange={(value) => {
                                        setPageSize(Number(value));
                                        setPage(0);
                                    }}
                                >
                                    <SelectTrigger className="w-16 h-8">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="10">10</SelectItem>
                                        <SelectItem value="20">20</SelectItem>
                                        <SelectItem value="50">50</SelectItem>
                                        <SelectItem value="100">100</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>

                            <div className="flex items-center gap-2">
                                <span className="text-sm text-slate-500">
                                    Página {page + 1} de {totalPages || 1}
                                </span>
                                <div className="flex items-center gap-1">
                                    <Button
                                        variant="outline"
                                        size="icon"
                                        className="h-8 w-8"
                                        onClick={() => setPage(0)}
                                        disabled={page === 0}
                                    >
                                        <span className="sr-only">Primeira</span>
                                        {/* ChevronsLeft */}
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m11 17-5-5 5-5" /><path d="m18 17-5-5 5-5" /></svg>
                                    </Button>
                                    <Button
                                        variant="outline"
                                        size="icon"
                                        className="h-8 w-8"
                                        onClick={() => setPage(page - 1)}
                                        disabled={page === 0}
                                    >
                                        <span className="sr-only">Anterior</span>
                                        {/* ChevronLeft */}
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6" /></svg>
                                    </Button>
                                    <Button
                                        variant="outline"
                                        size="icon"
                                        className="h-8 w-8"
                                        onClick={() => setPage(page + 1)}
                                        disabled={page >= totalPages - 1}
                                    >
                                        <span className="sr-only">Próxima</span>
                                        {/* ChevronRight */}
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6" /></svg>
                                    </Button>
                                    <Button
                                        variant="outline"
                                        size="icon"
                                        className="h-8 w-8"
                                        onClick={() => setPage(totalPages - 1)}
                                        disabled={page >= totalPages - 1}
                                    >
                                        <span className="sr-only">Última</span>
                                        {/* ChevronsRight */}
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m6 17 5-5-5-5" /><path d="m13 17 5-5-5-5" /></svg>
                                    </Button>
                                </div>
                            </div>
                        </div>
                    </div>
                )
            }
        </div >
    );
}

// --- Quick Add Modal Component ---

function QuickAddModal({
    open,
    onOpenChange,
    categories,
    onSuccess
}: {
    open: boolean;
    onOpenChange: (o: boolean) => void;
    categories: SalaryCategoryDTO[];
    onSuccess: () => void;
}) {
    const [code, setCode] = useState("");
    const [name, setName] = useState("");
    const [categoryId, setCategoryId] = useState("");
    const [baseSalary, setBaseSalary] = useState("0");
    const [isSubmitting, setIsSubmitting] = useState(false);

    // Autocomplete State
    const [positions, setPositions] = useState<PositionDTO[]>([]);
    const [openCombobox, setOpenCombobox] = useState(false);
    const [posSearch, setPosSearch] = useState("");

    useEffect(() => {
        if (open) {
            // Fetch large set to ensure coverage (simulating search/scroll)
            // Senior Fix: Ideally backend search, this is a robust client-side fallback
            positionService.getAllPositions(0, 1000).then(page => {
                setPositions(page.content || page as any);
            }).catch(console.error);
        }
    }, [open]);

    const handleSelectPosition = (pos: PositionDTO) => {
        setName(pos.title);
        setCode(pos.code); // Optional: auto-fill code too
        setOpenCombobox(false);
    }

    const handleSubmit = async () => {
        if (!code || !name || !categoryId) {
            toast.error("Preencha os campos obrigatórios");
            return;
        }

        setIsSubmitting(true);
        try {
            // 1. Create Grade
            const grade = await salaryService.createGrade({
                categoryId,
                code,
                name
            });

            // 2. Create Step 1
            const step = await salaryService.createStep({
                gradeId: grade.id,
                stepNumber: 1
            });

            // 3. Create Grid Entry (Salary)
            if (baseSalary && parseFloat(baseSalary) > 0) {
                await salaryService.createGridEntry({
                    stepId: step.id,
                    baseAmount: parseFloat(baseSalary),
                    validFrom: new Date().toISOString().split('T')[0]
                });
            }

            toast.success("Cargo criado com sucesso!");

            // Reset form
            setCode("");
            setName("");
            setBaseSalary("0");

            onSuccess();
        } catch (error) {
            console.error(error);
            toast.error("Erro ao criar cargo.");
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                    <DialogTitle>Novo Cargo / Função</DialogTitle>
                    <DialogDescription>
                        Adicione um novo cargo à grelha salarial. Um escalão inicial (Step 1) será criado automaticamente.
                    </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                    <div className="grid grid-cols-4 items-center gap-4">
                        <Label className="text-right">Código</Label>
                        <Input className="col-span-3" value={code} onChange={e => setCode(e.target.value)} placeholder="Ex: 5F02" />
                    </div>
                    <div className="grid grid-cols-4 items-center gap-4">
                        <Label className="text-right">Nome / Cargo</Label>
                        <div className="col-span-3">
                            <Popover open={openCombobox} onOpenChange={setOpenCombobox}>
                                <PopoverTrigger asChild>
                                    <Button
                                        variant="outline"
                                        role="combobox"
                                        aria-expanded={openCombobox}
                                        className="w-full justify-between"
                                    >
                                        {name ? name : "Selecione ou digite um cargo..."}
                                        <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                    </Button>
                                </PopoverTrigger>
                                <PopoverContent className="w-[300px] p-0">
                                    <Command>
                                        <CommandInput
                                            placeholder="Buscar cargo..."
                                            value={name}
                                            onValueChange={setName} // Allows typing new names
                                        />
                                        <CommandList>
                                            <CommandEmpty>Cargo não encontrado. Pressione Enter para usar o digitado.</CommandEmpty>
                                            <CommandGroup heading="Sugestões do Cadastro">
                                                {positions.map((pos) => (
                                                    <CommandItem
                                                        key={pos.id}
                                                        value={pos.title}
                                                        onSelect={() => handleSelectPosition(pos)}
                                                    >
                                                        <Check
                                                            className={cn(
                                                                "mr-2 h-4 w-4",
                                                                name === pos.title ? "opacity-100" : "opacity-0"
                                                            )}
                                                        />
                                                        {pos.title} ({pos.code})
                                                    </CommandItem>
                                                ))}
                                            </CommandGroup>
                                        </CommandList>
                                    </Command>
                                </PopoverContent>
                            </Popover>
                        </div>
                    </div>
                    <div className="grid grid-cols-4 items-center gap-4">
                        <Label className="text-right">Categoria</Label>
                        <div className="col-span-3">
                            <Select value={categoryId} onValueChange={setCategoryId}>
                                <SelectTrigger>
                                    <SelectValue placeholder="Selecione..." />
                                </SelectTrigger>
                                <SelectContent>
                                    {categories.map(c => (
                                        <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                    <div className="grid grid-cols-4 items-center gap-4">
                        <Label className="text-right">Salário Base</Label>
                        <div className="col-span-3 relative">
                            <span className="absolute left-3 top-2.5 text-slate-400 text-sm">XOF</span>
                            <Input
                                className="pl-12"
                                type="number"
                                value={baseSalary}
                                onChange={e => setBaseSalary(e.target.value)}
                                placeholder="0.00"
                            />
                        </div>
                    </div>
                </div>
                <DialogFooter>
                    <Button variant="outline" onClick={() => onOpenChange(false)}>Cancelar</Button>
                    <Button onClick={handleSubmit} disabled={isSubmitting}>
                        {isSubmitting ? "Salvando..." : "Criar Cargo"}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
