import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { CareerRegimeDTO, SalaryCategoryDTO } from "@/types/salary";
import { careerRegimeService } from "@/services/careerRegimeService";
import { salaryService } from "@/services/salaryService";
import { Pencil, Trash2, Plus, Save, X } from "lucide-react";

interface SalarySettingsDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onSuccess: () => void;
}

export function SalarySettingsDialog({ open, onOpenChange, onSuccess }: SalarySettingsDialogProps) {
    const [activeTab, setActiveTab] = useState("categories");
    const [regimes, setRegimes] = useState<CareerRegimeDTO[]>([]);
    const [categories, setCategories] = useState<SalaryCategoryDTO[]>([]);
    const [loading, setLoading] = useState(false);

    // Edit States
    const [editingRegime, setEditingRegime] = useState<Partial<CareerRegimeDTO> | null>(null);
    const [editingCategory, setEditingCategory] = useState<Partial<SalaryCategoryDTO> | null>(null);

    useEffect(() => {
        if (open) {
            loadData();
        }
    }, [open]);

    const loadData = async () => {
        setLoading(true);
        try {
            const [r, c] = await Promise.all([
                careerRegimeService.getAll(),
                salaryService.getAllCategories()
            ]);
            setRegimes(r);
            setCategories(c);
        } catch (error) {
            toast.error("Erro ao carregar configurações");
        } finally {
            setLoading(false);
        }
    };

    // --- Regime Handlers ---
    const handleSaveRegime = async () => {
        if (!editingRegime?.name || !editingRegime?.code) {
            toast.error("Nome e Código são obrigatórios");
            return;
        }
        try {
            if (editingRegime.id) {
                await careerRegimeService.update(editingRegime.id, editingRegime);
                toast.success("Regime atualizado");
            } else {
                await careerRegimeService.create(editingRegime);
                toast.success("Regime criado");
            }
            setEditingRegime(null);
            loadData();
            onSuccess(); // Trigger parent refresh too
        } catch (error) {
            toast.error("Erro ao salvar regime");
        }
    };

    const handleDeleteRegime = async (id: string) => {
        if (!confirm("Tem certeza? Isso pode afetar categorias vinculadas.")) return;
        try {
            await careerRegimeService.delete(id);
            toast.success("Regime removido");
            loadData();
            onSuccess();
        } catch (error) {
            toast.error("Erro ao remover regime");
        }
    };

    // --- Category Handlers ---
    const handleSaveCategory = async () => {
        if (!editingCategory?.name || !editingCategory?.code || !editingCategory?.regimeId) {
            toast.error("Nome, Código e Regime são obrigatórios");
            return;
        }
        try {
            // Map regimeName locally 
            const selectedRegime = regimes.find(r => r.id === editingCategory.regimeId);
            const payload = { ...editingCategory, regimeName: selectedRegime?.name };

            if (editingCategory.id) {
                await salaryService.updateCategory(editingCategory.id, payload);
                toast.success("Categoria atualizada");
            } else {
                await salaryService.createCategory(payload);
                toast.success("Categoria criada");
            }
            setEditingCategory(null);
            loadData();
            onSuccess();
        } catch (error) {
            toast.error("Erro ao salvar categoria");
        }
    };

    const handleDeleteCategory = async (id: string) => {
        if (!confirm("Tem certeza? Isso apagará cargos vinculados.")) return;
        try {
            await salaryService.deleteCategory(id);
            toast.success("Categoria removida");
            loadData();
            onSuccess();
        } catch (error) {
            toast.error("Erro ao remover categoria");
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-4xl h-[80vh] flex flex-col">
                <DialogHeader>
                    <DialogTitle>Configurações da Estrutura Salarial</DialogTitle>
                    <DialogDescription>
                        Gerencie os Regimes de Carreira e as Categorias Salariais.
                    </DialogDescription>
                </DialogHeader>

                <Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col overflow-hidden">
                    <TabsList>
                        <TabsTrigger value="regimes">Regimes de Carreira</TabsTrigger>
                        <TabsTrigger value="categories">Categorias Salariais</TabsTrigger>
                    </TabsList>

                    <TabsContent value="regimes" className="flex-1 overflow-auto border rounded-md mt-2 p-2">
                        <div className="flex justify-between mb-4">
                            <h3 className="text-lg font-semibold">Regimes Cadastrados</h3>
                            <Button size="sm" onClick={() => setEditingRegime({ code: '', name: '', description: '' })}>
                                <Plus className="h-4 w-4 mr-2" /> Novo Regime
                            </Button>
                        </div>

                        {editingRegime && (
                            <div className="bg-slate-50 p-4 rounded mb-4 border">
                                <h4 className="font-medium mb-3">{editingRegime.id ? 'Editar Regime' : 'Novo Regime'}</h4>
                                <div className="grid grid-cols-3 gap-4">
                                    <div>
                                        <Label>Código</Label>
                                        <Input
                                            value={editingRegime.code}
                                            onChange={e => setEditingRegime({ ...editingRegime, code: e.target.value })}
                                            placeholder="Ex: HEALTH"
                                        />
                                    </div>
                                    <div>
                                        <Label>Nome</Label>
                                        <Input
                                            value={editingRegime.name}
                                            onChange={e => setEditingRegime({ ...editingRegime, name: e.target.value })}
                                            placeholder="Ex: Saúde Pública"
                                        />
                                    </div>
                                    <div>
                                        <Label>Descrição</Label>
                                        <Input
                                            value={editingRegime.description || ''}
                                            onChange={e => setEditingRegime({ ...editingRegime, description: e.target.value })}
                                        />
                                    </div>
                                </div>
                                <div className="flex justify-end gap-2 mt-3">
                                    <Button variant="ghost" size="sm" onClick={() => setEditingRegime(null)}>Cancelar</Button>
                                    <Button size="sm" onClick={handleSaveRegime}>Salvar</Button>
                                </div>
                            </div>
                        )}

                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Código</TableHead>
                                    <TableHead>Nome</TableHead>
                                    <TableHead>Descrição</TableHead>
                                    <TableHead className="text-right">Ações</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {regimes.map(r => (
                                    <TableRow key={r.id}>
                                        <TableCell className="font-mono">{r.code}</TableCell>
                                        <TableCell>{r.name}</TableCell>
                                        <TableCell>{r.description}</TableCell>
                                        <TableCell className="text-right">
                                            <Button variant="ghost" size="icon" onClick={() => setEditingRegime(r)}>
                                                <Pencil className="h-4 w-4" />
                                            </Button>
                                            <Button variant="ghost" size="icon" className="text-red-500" onClick={() => handleDeleteRegime(r.id)}>
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TabsContent>

                    <TabsContent value="categories" className="flex-1 overflow-auto border rounded-md mt-2 p-2">
                        <div className="flex justify-between mb-4">
                            <h3 className="text-lg font-semibold">Categorias Salariais</h3>
                            <Button size="sm" onClick={() => setEditingCategory({ code: '', name: '', regimeId: '' })}>
                                <Plus className="h-4 w-4 mr-2" /> Nova Categoria
                            </Button>
                        </div>

                        {editingCategory && (
                            <div className="bg-slate-50 p-4 rounded mb-4 border">
                                <h4 className="font-medium mb-3">{editingCategory.id ? 'Editar Categoria' : 'Nova Categoria'}</h4>
                                <div className="grid grid-cols-3 gap-4">
                                    <div>
                                        <Label>Código</Label>
                                        <Input
                                            value={editingCategory.code}
                                            onChange={e => setEditingCategory({ ...editingCategory, code: e.target.value })}
                                            placeholder="Ex: CAT-01"
                                        />
                                    </div>
                                    <div>
                                        <Label>Nome</Label>
                                        <Input
                                            value={editingCategory.name}
                                            onChange={e => setEditingCategory({ ...editingCategory, name: e.target.value })}
                                            placeholder="Ex: Tabelas Gerais"
                                        />
                                    </div>
                                    <div>
                                        <Label>Regime de Carreira</Label>
                                        <Select
                                            value={editingCategory.regimeId}
                                            onValueChange={val => setEditingCategory({ ...editingCategory, regimeId: val })}
                                        >
                                            <SelectTrigger>
                                                <SelectValue placeholder="Selecione..." />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {regimes.map(r => (
                                                    <SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </div>
                                <div className="flex justify-end gap-2 mt-3">
                                    <Button variant="ghost" size="sm" onClick={() => setEditingCategory(null)}>Cancelar</Button>
                                    <Button size="sm" onClick={handleSaveCategory}>Salvar</Button>
                                </div>
                            </div>
                        )}

                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Código</TableHead>
                                    <TableHead>Nome</TableHead>
                                    <TableHead>Regime</TableHead>
                                    <TableHead className="text-right">Ações</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {categories.map(c => (
                                    <TableRow key={c.id}>
                                        <TableCell className="font-mono">{c.code}</TableCell>
                                        <TableCell>{c.name}</TableCell>
                                        <TableCell>
                                            <span className="inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80">
                                                {c.regimeName || '-'}
                                            </span>
                                        </TableCell>
                                        <TableCell className="text-right">
                                            <Button variant="ghost" size="icon" onClick={() => setEditingCategory(c)}>
                                                <Pencil className="h-4 w-4" />
                                            </Button>
                                            <Button variant="ghost" size="icon" className="text-red-500" onClick={() => handleDeleteCategory(c.id)}>
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TabsContent>
                </Tabs>
                <DialogFooter>
                    <Button variant="outline" onClick={() => onOpenChange(false)}>Fechar</Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
