import React, { useState, useEffect } from 'react';
import {
    Plus, Search, Edit2, Trash2, Layers,
    TrendingUp, ArrowDownRight, Info, Calendar
} from 'lucide-react';
import { rhService } from '@/services/rhService';
import { toast } from 'sonner';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";

export const TaxBracketsPage: React.FC = () => {
    const [taxTypes, setTaxTypes] = useState<any[]>([]);
    const [brackets, setBrackets] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [isConfigModalOpen, setIsConfigModalOpen] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingBracket, setEditingBracket] = useState<any>(null);
    const [filterType, setFilterType] = useState<string>('IRPS');

    useEffect(() => {
        loadTaxTypes();
        loadBrackets();
    }, []);

    const loadTaxTypes = async () => {
        try {
            const response = await rhService.getDeductionTypes();
            setTaxTypes(response);
        } catch (e) {
            // Fallback for visual safety if backend is down
            setTaxTypes([
                { code: 'IRPS', name: 'IRPS Progressivo', active: true },
                { code: 'ID', name: 'Imposto Democracia', active: true }
            ]);
        }
    };

    const loadBrackets = async () => {
        try {
            setLoading(true);
            const data = await rhService.getTaxBrackets();
            setBrackets(data.sort((a: any, b: any) => a.lowerLimit - b.lowerLimit));
        } catch (error) {
            toast.error('Erro ao carregar escalões');
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (id: string) => {
        if (!window.confirm('Tem certeza que deseja excluir este escalão?')) return;
        try {
            await rhService.deleteTaxBracket(id);
            toast.success('Escalão excluído com sucesso');
            loadBrackets();
        } catch (error) {
            toast.error('Erro ao excluir escalão');
        }
    };

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget);
        const data = {
            id: editingBracket?.id,
            deductionType: { id: formData.get('deductionTypeId') },
            lowerLimit: parseFloat(formData.get('lowerLimit') as string),
            upperLimit: formData.get('upperLimit') ? parseFloat(formData.get('upperLimit') as string) : null,
            ratePercentage: formData.get('ratePercentage') ? parseFloat(formData.get('ratePercentage') as string) / 100 : null,
            excessDeduction: formData.get('excessDeduction') ? parseFloat(formData.get('excessDeduction') as string) : null,
            fixedAmount: formData.get('fixedAmount') ? parseFloat(formData.get('fixedAmount') as string) : null,
            validFrom: formData.get('validFrom'),
            validTo: formData.get('validTo') || null
        };

        try {
            await rhService.saveTaxBracket(data);
            toast.success(editingBracket ? 'Escalão atualizado' : 'Escalão criado');
            setIsModalOpen(false);
            loadBrackets();
        } catch (error) {
            toast.error('Erro ao salvar escalão');
        }
    };

    const handleSaveType = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget);
        const data = {
            code: formData.get('code'),
            name: formData.get('name'),
            mandatory: formData.get('mandatory') === 'on',
            active: true
        };
        try {
            await rhService.saveDeductionType(data);
            toast.success('Tipo de Imposto criado com sucesso');
            setIsConfigModalOpen(false);
            loadTaxTypes();
        } catch (error) {
            toast.error('Erro ao criar tipo de imposto');
        }
    };

    const handleToggleType = async (id: string) => {
        try {
            await rhService.toggleDeductionTypeStatus(id);
            toast.success('Status atualizado');
            loadTaxTypes();
        } catch (error) {
            toast.error('Erro ao atualizar status');
        }
    };


    return (
        <div className="p-6 space-y-6 animate-in fade-in duration-500">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                    <h1 className="text-3xl font-bold text-slate-900 tracking-tight flex items-center gap-3">
                        <Layers className="w-8 h-8 text-primary" />
                        Escalões & Impostos
                    </h1>
                    <p className="text-slate-500 mt-1">Gestão da Tabela de Retenção e Tipos de Imposto.</p>
                </div>

                <div className="flex gap-2">
                    <Button variant="outline" onClick={() => setIsConfigModalOpen(true)}>
                        <Layers className="w-4 h-4 mr-2" />
                        Gerir Tipos de Imposto
                    </Button>
                    <Button
                        onClick={() => { setEditingBracket(null); setIsModalOpen(true); }}
                        className="shadow-lg flex items-center gap-2"
                    >
                        <Plus className="w-5 h-5" />
                        Novo Escalão
                    </Button>
                </div>
            </div>

            <Card>
                {/* ... Content ... */}
                <CardHeader>
                    {/* ... */}
                </CardHeader>
                <CardContent>
                    <div className="flex items-center gap-2 mb-4 overflow-x-auto pb-2">
                        <Button
                            variant={filterType === 'ALL' ? 'default' : 'outline'}
                            onClick={() => setFilterType('ALL')}
                            size="sm"
                        >
                            Todos
                        </Button>
                        {taxTypes.map((type) => (
                            <div key={type.code} className="relative group">
                                <Button
                                    variant={filterType === type.code ? 'default' : 'outline'}
                                    onClick={() => setFilterType(type.code)}
                                    size="sm"
                                    className={`${!type.active ? 'opacity-50 line-through' : ''}`}
                                >
                                    {type.name}
                                </Button>
                            </div>
                        ))}
                    </div>

                    <div className="rounded-md border">
                        <Table>
                            {/* Table Header and Body defined previously, kept as is */}
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Intervalo de Rendimento (XOF)</TableHead>
                                    <TableHead className="text-center">Taxa / Valor Fixo</TableHead>
                                    <TableHead className="text-right">Parcela a Abater (XOF)</TableHead>
                                    <TableHead className="text-right">Ações</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {loading ? (
                                    <TableRow>
                                        <TableCell colSpan={4} className="h-24 text-center">
                                            Carregando tabela progressiva...
                                        </TableCell>
                                    </TableRow>
                                ) : brackets.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={4} className="h-24 text-center">
                                            Nenhum escalão cadastrado.
                                        </TableCell>
                                    </TableRow>
                                ) : brackets
                                    .filter(b => filterType === 'ALL' || b.deductionType?.code === filterType)
                                    .map((bracket) => (
                                        <TableRow key={bracket.id} className="group">
                                            <TableCell>
                                                <div className="flex items-center gap-3">
                                                    <div className="w-10 h-10 rounded-full bg-slate-50 flex items-center justify-center text-slate-400 border border-slate-100">
                                                        <TrendingUp className="w-5 h-5 text-primary" />
                                                    </div>
                                                    <div>
                                                        <div className="font-semibold text-slate-900">
                                                            {bracket.lowerLimit.toLocaleString('pt-PT')}
                                                            {bracket.upperLimit ? ` a ${bracket.upperLimit.toLocaleString('pt-PT')}` : ' em diante'}
                                                        </div>
                                                        <div className="text-xs text-muted-foreground flex items-center gap-1">
                                                            <Info className="w-3 h-3" />
                                                            Código: {bracket.deductionType.code}
                                                        </div>
                                                    </div>
                                                </div>
                                            </TableCell>
                                            <TableCell className="text-center">
                                                {bracket.fixedAmount && bracket.fixedAmount > 0 ? (
                                                    <Badge variant="secondary" className="font-bold text-emerald-700 bg-emerald-50 border-emerald-200">
                                                        {bracket.fixedAmount.toLocaleString('pt-PT')} XOF
                                                    </Badge>
                                                ) : (bracket.ratePercentage !== null && bracket.ratePercentage !== undefined) ? (
                                                    <Badge className="font-bold">
                                                        {(bracket.ratePercentage * 100).toFixed(0)}%
                                                    </Badge>
                                                ) : (
                                                    <span className="text-gray-400 font-mono text-xs">--</span>
                                                )}
                                            </TableCell>
                                            <TableCell className="text-right">
                                                {bracket.excessDeduction > 0 && (
                                                    <div className="flex flex-col items-end">
                                                        <span className="text-destructive font-mono font-bold">
                                                            - {bracket.excessDeduction.toLocaleString('pt-PT')}
                                                        </span>
                                                        <span className="text-[10px] text-muted-foreground uppercase">Dedução Automática</span>
                                                    </div>
                                                )}
                                            </TableCell>
                                            <TableCell className="text-right">
                                                <div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                                    <Button
                                                        size="icon"
                                                        variant="ghost"
                                                        onClick={() => { setEditingBracket(bracket); setIsModalOpen(true); }}
                                                    >
                                                        <Edit2 className="w-4 h-4 text-primary" />
                                                    </Button>
                                                    <Button
                                                        size="icon"
                                                        variant="ghost"
                                                        onClick={() => handleDelete(bracket.id)}
                                                    >
                                                        <Trash2 className="w-4 h-4 text-destructive" />
                                                    </Button>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                            </TableBody>
                        </Table>
                    </div>
                </CardContent>
            </Card>

            {/* Bracket Modal */}
            <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                <DialogContent className="sm:max-w-[500px]">
                    <DialogHeader>
                        <DialogTitle>{editingBracket ? 'Editar Escalão' : 'Novo Escalão de Imposto'}</DialogTitle>
                        <DialogDescription>
                            Ajuste os valores para o cálculo (Progressivo ou Fixo).
                        </DialogDescription>
                    </DialogHeader>

                    <form onSubmit={handleSubmit} className="space-y-4 py-4">
                        <div className="space-y-2">
                            <Label htmlFor="deductionTypeId">Tipo de Desconto (DeductionType UID)</Label>
                            {/* Improved Select instead of raw Input ID */}
                            <select
                                id="deductionTypeId"
                                name="deductionTypeId"
                                defaultValue={editingBracket?.deductionType?.id}
                                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                                required
                            >
                                <option value="">Selecione o Imposto...</option>
                                {taxTypes.map(t => (
                                    <option key={t.id} value={t.id}>{t.name} ({t.code})</option>
                                ))}
                            </select>
                        </div>
                        {/* Fields kept same as before */}
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="lowerLimit" className="flex items-center gap-2">
                                    <ArrowDownRight className="w-4 h-4 text-emerald-500" />
                                    Limite Inferior
                                </Label>
                                <Input
                                    id="lowerLimit"
                                    name="lowerLimit"
                                    type="number"
                                    defaultValue={editingBracket?.lowerLimit}
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="upperLimit" className="flex items-center gap-2">
                                    <TrendingUp className="w-4 h-4 text-destructive" />
                                    Limite Superior
                                </Label>
                                <Input
                                    id="upperLimit"
                                    name="upperLimit"
                                    type="number"
                                    defaultValue={editingBracket?.upperLimit || ''}
                                    placeholder="Vazio para infinito"
                                />
                            </div>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="ratePercentage">Taxa (%) - Opcional</Label>
                                <Input
                                    id="ratePercentage"
                                    name="ratePercentage"
                                    type="number"
                                    step="0.01"
                                    defaultValue={editingBracket?.ratePercentage ? (editingBracket.ratePercentage * 100).toFixed(2) : ''}
                                    placeholder="Ex: 15.00"
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="fixedAmount">Valor Fixo (Novo)</Label>
                                <Input
                                    id="fixedAmount"
                                    name="fixedAmount"
                                    type="number"
                                    defaultValue={editingBracket?.fixedAmount}
                                    placeholder="Ex: 1000"
                                />
                            </div>
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="excessDeduction">Parcela a Abater (Para Progressivo)</Label>
                            <Input
                                id="excessDeduction"
                                name="excessDeduction"
                                type="number"
                                defaultValue={editingBracket?.excessDeduction}
                                placeholder="0"
                            />
                        </div>
                        <div className="grid grid-cols-2 gap-4 pt-4 border-t">
                            <div className="space-y-2">
                                <Label htmlFor="validFrom">Início Vigência</Label>
                                <Input
                                    id="validFrom"
                                    name="validFrom"
                                    type="date"
                                    defaultValue={editingBracket?.validFrom?.split('T')[0]}
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="validTo">Fim Vigência</Label>
                                <Input
                                    id="validTo"
                                    name="validTo"
                                    type="date"
                                    defaultValue={editingBracket?.validTo?.split('T')[0]}
                                />
                            </div>
                        </div>
                        <DialogFooter className="pt-4">
                            <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                                Cancelar
                            </Button>
                            <Button type="submit">
                                Salvar Escalão
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Type Management Modal */}
            <Dialog open={isConfigModalOpen} onOpenChange={setIsConfigModalOpen}>
                <DialogContent className="sm:max-w-[600px]">
                    <DialogHeader>
                        <DialogTitle>Gestão de Tipos de Imposto</DialogTitle>
                        <DialogDescription>
                            Crie novos impostos ou ative/desative os existentes.
                        </DialogDescription>
                    </DialogHeader>

                    <div className="space-y-6">
                        <div className="rounded-md border">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Código</TableHead>
                                        <TableHead>Nome</TableHead>
                                        <TableHead>Status</TableHead>
                                        <TableHead className="text-right">Ação</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {taxTypes.map((type) => (
                                        <TableRow key={type.id}>
                                            <TableCell className="font-mono">{type.code}</TableCell>
                                            <TableCell>{type.name}</TableCell>
                                            <TableCell>
                                                <Badge variant={type.active ? 'default' : 'secondary'}>
                                                    {type.active ? 'Ativo' : 'Inativo'}
                                                </Badge>
                                            </TableCell>
                                            <TableCell className="text-right">
                                                <Button size="sm" variant="ghost" onClick={() => handleToggleType(type.id)}>
                                                    {type.active ? 'Desativar' : 'Ativar'}
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </div>

                        <div className="border-t pt-4">
                            <h4 className="font-semibold mb-3">Novo Imposto</h4>
                            <form onSubmit={handleSaveType} className="grid gap-4">
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label htmlFor="code">Código (Ex: TAXA_LIXO)</Label>
                                        <Input id="code" name="code" placeholder="CODE_123" required className="uppercase" />
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="name">Nome (Ex: Taxa de Lixo)</Label>
                                        <Input id="name" name="name" placeholder="Nome do Imposto" required />
                                    </div>
                                </div>
                                <div className="flex items-center gap-2">
                                    <input type="checkbox" id="mandatory" name="mandatory" className="rounded border-gray-300" />
                                    <Label htmlFor="mandatory">Obrigatório para Todos (Mandatory)</Label>
                                </div>
                                <Button type="submit" className="w-full">
                                    <Plus className="w-4 h-4 mr-2" />
                                    Criar Novo Tipo
                                </Button>
                            </form>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
};
