import React, { useState, useEffect } from 'react';
import {
    Plus, Search, Edit2, Trash2, ShieldCheck,
    Calendar, Percent, Wallet, Info, X
} 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 TaxSettingsPage: React.FC = () => {
    const [rules, setRules] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingRule, setEditingRule] = useState<any>(null);

    useEffect(() => {
        loadRules();
    }, []);

    const loadRules = async () => {
        try {
            setLoading(true);
            const data = await rhService.getTaxRules();
            setRules(data);
        } catch (error) {
            toast.error('Erro ao carregar regras tributárias');
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (id: string) => {
        if (!window.confirm('Tem certeza que deseja excluir esta regra?')) return;
        try {
            await rhService.deleteTaxRule(id);
            toast.success('Regra excluída com sucesso');
            loadRules();
        } catch (error) {
            toast.error('Erro ao excluir regra');
        }
    };

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget);
        const data = {
            id: editingRule?.id,
            deductionType: { id: formData.get('deductionTypeId') },
            percentage: formData.get('percentage') ? parseFloat(formData.get('percentage') as string) / 100 : null,
            amountFixed: formData.get('amountFixed') ? parseFloat(formData.get('amountFixed') as string) : null,
            validFrom: formData.get('validFrom'),
            validTo: formData.get('validTo') || null,
            active: true
        };

        try {
            await rhService.saveTaxRule(data);
            toast.success(editingRule ? 'Regra atualizada' : 'Regra criada');
            setIsModalOpen(false);
            loadRules();
        } catch (error) {
            toast.error('Erro ao salvar regra');
        }
    };

    const filteredRules = rules.filter(r =>
        r.deductionType.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        r.deductionType.code.toLowerCase().includes(searchTerm.toLowerCase())
    );

    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">
                        <ShieldCheck className="w-8 h-8 text-primary" />
                        Configurações Tributárias
                    </h1>
                    <p className="text-slate-500 mt-1">Gestão de impostos e taxas globais aplicáveis à folha.</p>
                </div>

                <Button
                    onClick={() => { setEditingRule(null); setIsModalOpen(true); }}
                    className="shadow-lg flex items-center gap-2"
                >
                    <Plus className="w-5 h-5" />
                    Nova Regra Global
                </Button>
            </div>

            <Card>
                <CardHeader className="pb-3">
                    <div className="relative max-w-md">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground w-4 h-4" />
                        <Input
                            placeholder="Pesquisar por nome ou código..."
                            className="pl-10"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>
                </CardHeader>
                <CardContent>
                    <div className="rounded-md border">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Imposto</TableHead>
                                    <TableHead>Código</TableHead>
                                    <TableHead>Taxa / Valor</TableHead>
                                    <TableHead>Vigência</TableHead>
                                    <TableHead>Status</TableHead>
                                    <TableHead className="text-right">Ações</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {loading ? (
                                    <TableRow>
                                        <TableCell colSpan={6} className="h-24 text-center">
                                            Carregando configurações...
                                        </TableCell>
                                    </TableRow>
                                ) : filteredRules.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={6} className="h-24 text-center">
                                            Nenhuma regra encontrada.
                                        </TableCell>
                                    </TableRow>
                                ) : filteredRules.map((rule) => (
                                    <TableRow key={rule.id} className="group">
                                        <TableCell className="font-medium">{rule.deductionType.name}</TableCell>
                                        <TableCell>
                                            <Badge variant="outline" className="font-mono">{rule.deductionType.code}</Badge>
                                        </TableCell>
                                        <TableCell>
                                            {rule.percentage ? (
                                                <div className="flex items-center gap-1.5 text-primary font-semibold">
                                                    <Percent className="w-4 h-4" />
                                                    {(rule.percentage * 100).toFixed(2)}%
                                                </div>
                                            ) : (
                                                <div className="flex items-center gap-1.5 text-emerald-600 font-semibold">
                                                    <Wallet className="w-4 h-4" />
                                                    {rule.amountFixed?.toLocaleString('pt-PT')} XOF
                                                </div>
                                            )}
                                        </TableCell>
                                        <TableCell className="text-muted-foreground text-sm">
                                            <div className="flex items-center gap-2">
                                                <Calendar className="w-4 h-4 opacity-70" />
                                                {new Date(rule.validFrom).toLocaleDateString('pt-PT')}
                                                {rule.validTo && ` → ${new Date(rule.validTo).toLocaleDateString('pt-PT')}`}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <Badge variant={rule.active ? "default" : "secondary"}>
                                                {rule.active ? 'Ativo' : 'Inativo'}
                                            </Badge>
                                        </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={() => { setEditingRule(rule); setIsModalOpen(true); }}
                                                >
                                                    <Edit2 className="w-4 h-4 text-primary" />
                                                </Button>
                                                <Button
                                                    size="icon"
                                                    variant="ghost"
                                                    onClick={() => handleDelete(rule.id)}
                                                >
                                                    <Trash2 className="w-4 h-4 text-destructive" />
                                                </Button>
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                </CardContent>
            </Card>

            <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                <DialogContent className="sm:max-w-[500px]">
                    <DialogHeader>
                        <DialogTitle>{editingRule ? 'Editar Regra' : 'Nova Regra Tributária'}</DialogTitle>
                        <DialogDescription>
                            Defina os parâmetros do imposto governamental.
                        </DialogDescription>
                    </DialogHeader>

                    <form onSubmit={handleSubmit} className="space-y-4 py-4">
                        <div className="space-y-2">
                            <Label htmlFor="deductionTypeId">Tipo de Desconto (DeductionType ID)</Label>
                            <Input
                                id="deductionTypeId"
                                name="deductionTypeId"
                                defaultValue={editingRule?.deductionType?.id}
                                required
                                placeholder="Ex: UUID do Tipo de Desconto"
                            />
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="percentage">Taxa (%)</Label>
                                <Input
                                    id="percentage"
                                    name="percentage"
                                    type="number"
                                    step="0.01"
                                    defaultValue={editingRule?.percentage ? (editingRule.percentage * 100).toFixed(2) : ''}
                                    placeholder="Ex: 7.00"
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="amountFixed">Valor Fixo</Label>
                                <Input
                                    id="amountFixed"
                                    name="amountFixed"
                                    type="number"
                                    defaultValue={editingRule?.amountFixed || ''}
                                    placeholder="Ex: 1000"
                                />
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="validFrom">Válido de</Label>
                                <Input
                                    id="validFrom"
                                    name="validFrom"
                                    type="date"
                                    defaultValue={editingRule?.validFrom?.split('T')[0]}
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="validTo">Válido até</Label>
                                <Input
                                    id="validTo"
                                    name="validTo"
                                    type="date"
                                    defaultValue={editingRule?.validTo?.split('T')[0]}
                                />
                            </div>
                        </div>

                        <DialogFooter className="pt-4">
                            <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                                Cancelar
                            </Button>
                            <Button type="submit">
                                Salvar Regra
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </div>
    );
};
