import React, { useState } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Filter, X, Search, UserSearch } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';

interface AgentFilters {
    query?: string;
    status?: string;
    ministry?: string;
    orgUnit?: string;
    position?: string;
    functionalSituation?: string;
    appointmentType?: string;
}

interface AgentFilterPanelProps {
    initialFilters: AgentFilters;
    onApply: (filters: AgentFilters) => void;
    onClear: () => void;
    ministries: Array<{ id: string; name: string }>;
    orgUnits: Array<{ id: string; name: string }>;
    positions: Array<{ id: string; name: string }>;
}

export const AgentFilterPanel: React.FC<AgentFilterPanelProps> = ({
    initialFilters,
    onApply,
    onClear,
    ministries,
    orgUnits,
    positions
}) => {
    const [localFilters, setLocalFilters] = useState<AgentFilters>(initialFilters);
    const activeFilterCount = Object.values(localFilters).filter(v => v !== undefined && v !== '').length;

    const handleClear = () => {
        setLocalFilters({});
        onClear();
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            onApply(localFilters);
        }
    };

    return (
        <div className="gov-card mb-6 overflow-hidden animate-fade-in no-print">
            <div className="bg-muted/50 border-b border-border px-4 py-3 flex items-center justify-between">
                <div className="flex items-center gap-2">
                    <Filter className="h-4 w-4 text-primary" />
                    <span className="text-sm font-semibold text-foreground">Filtros de Pesquisa</span>
                    {activeFilterCount > 0 && (
                        <span className="ml-2 bg-primary/10 text-primary text-[10px] font-bold px-2 py-0.5 rounded-full uppercase">
                            {activeFilterCount} Ativos
                        </span>
                    )}
                </div>
                <Button variant="ghost" size="sm" onClick={handleClear} className="h-8 text-muted-foreground hover:text-destructive">
                    <X className="h-4 w-4 mr-1" />
                    Limpar
                </Button>
            </div>
            <div className="p-4 bg-card">
                <div className="space-y-6">
                    {/* Linha 1: Busca Geral */}
                    <div className="relative">
                        <label className="text-xs font-semibold text-muted-foreground mb-1 block">Pesquisa Geral</label>
                        <div className="relative group">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground group-focus-within:text-primary transition-colors" />
                            <Input
                                placeholder="Pesquisar por Nome Completo, NIF ou Matrícula..."
                                className="pl-10 h-10 bg-muted/20 border-border focus:bg-background transition-all"
                                value={localFilters.query || ''}
                                onChange={(e) => setLocalFilters({ ...localFilters, query: e.target.value })}
                                onKeyDown={handleKeyDown}
                            />
                        </div>
                    </div>

                    <div className="h-px bg-border/50" />

                    {/* Linha 2: Filtros Estruturais */}
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-muted-foreground block">Estado</label>
                            <Select
                                value={localFilters.status || '__ALL__'}
                                onValueChange={(v) => setLocalFilters({ ...localFilters, status: v === '__ALL__' ? undefined : v })}
                            >
                                <SelectTrigger className="h-9 border-border bg-background">
                                    <SelectValue placeholder="Qualquer Estado" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="__ALL__">Qualquer Estado</SelectItem>
                                    <SelectItem value="ACTIVE">Activo</SelectItem>
                                    <SelectItem value="INACTIVE">Inactivo</SelectItem>
                                    <SelectItem value="SUSPENDED">Suspenso</SelectItem>
                                    <SelectItem value="TERMINATED">Desligado</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-muted-foreground block">Ministério</label>
                            <Select
                                value={localFilters.ministry || '__ALL__'}
                                onValueChange={(v) => setLocalFilters({ ...localFilters, ministry: v === '__ALL__' ? undefined : v })}
                            >
                                <SelectTrigger className="h-9 border-border bg-background">
                                    <SelectValue placeholder="Todos os Ministérios" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="__ALL__">Todos os Ministérios</SelectItem>
                                    {ministries.sort((a, b) => a.name.localeCompare(b.name)).map(min => (
                                        <SelectItem key={min.id} value={min.id}>{min.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-muted-foreground block">Unidade Orgânica</label>
                            <Select
                                value={localFilters.orgUnit || '__ALL__'}
                                onValueChange={(v) => setLocalFilters({ ...localFilters, orgUnit: v === '__ALL__' ? undefined : v })}
                            >
                                <SelectTrigger className="h-9 border-border bg-background">
                                    <SelectValue placeholder="Todas as Unidades" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="__ALL__">Todas as Unidades</SelectItem>
                                    {orgUnits.sort((a, b) => a.name.localeCompare(b.name)).map(unit => (
                                        <SelectItem key={unit.id} value={unit.id}>{unit.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-muted-foreground block">Cargo / Função</label>
                            <Select
                                value={localFilters.position || '__ALL__'}
                                onValueChange={(v) => setLocalFilters({ ...localFilters, position: v === '__ALL__' ? undefined : v })}
                            >
                                <SelectTrigger className="h-9 border-border bg-background">
                                    <SelectValue placeholder="Todos os Cargos" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="__ALL__">Todos os Cargos</SelectItem>
                                    {positions.sort((a, b) => a.name.localeCompare(b.name)).map(pos => (
                                        <SelectItem key={pos.id} value={pos.id}>{pos.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-muted-foreground block">Situação Funcional</label>
                            <Select
                                value={localFilters.functionalSituation || '__ALL__'}
                                onValueChange={(v) => setLocalFilters({ ...localFilters, functionalSituation: v === '__ALL__' ? undefined : v })}
                            >
                                <SelectTrigger className="h-9 border-border bg-background">
                                    <SelectValue placeholder="Qualquer Situação" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="__ALL__">Qualquer Situação</SelectItem>
                                    <SelectItem value="ATIVIDADE_NO_QUADRO">Atividade no Quadro</SelectItem>
                                    <SelectItem value="ATIVIDADE_FORA_DO_QUADRO">Atividade Fora do Quadro</SelectItem>
                                    <SelectItem value="SUBSTITUICAO">Substituição</SelectItem>
                                    <SelectItem value="TRANSFERENCIA">Transferência</SelectItem>
                                    <SelectItem value="COMISSAO_SERVICO">Comissão de Serviço</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold text-muted-foreground block">Natureza do Vínculo</label>
                            <Select
                                value={localFilters.appointmentType || '__ALL__'}
                                onValueChange={(v) => setLocalFilters({ ...localFilters, appointmentType: v === '__ALL__' ? undefined : v })}
                            >
                                <SelectTrigger className="h-9 border-border bg-background">
                                    <SelectValue placeholder="Todos os Vínculos" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="__ALL__">Todos os Vínculos</SelectItem>
                                    <SelectItem value="PROVISORIA">Provisória</SelectItem>
                                    <SelectItem value="DEFINITIVA">Definitiva</SelectItem>
                                    <SelectItem value="CONTRATO_PROVIMENTO">Direito de Provimento</SelectItem>
                                    <SelectItem value="CONTRATO_TERMO">Contrato a Termo</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                </div>

                <div className="flex justify-end gap-3 mt-6 pt-6 border-t border-border">
                    <Button
                        onClick={() => onApply(localFilters)}
                        className="px-6 h-10 font-semibold"
                    >
                        <UserSearch className="h-4 w-4 mr-2" />
                        Filtrar Agentes
                    </Button>
                </div>
            </div>
        </div>
    );
};
