'use client';

import { queryKeys } from '@/lib/cache/queryKeys';
import React from 'react';
import { Select, Tag, Space } from 'antd';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';

interface TipoTarefa {
    id: number;
    nome: string;
    chave: string;
    icone?: string;
    descricao?: string;
    nivel_hierarquia: 'epico' | 'historia' | 'tarefa' | 'subtarefa';
    ativo: boolean;
}

interface TipoTarefaSelectorProps {
    value?: number;
    onChange?: (value: number | undefined) => void;
    projetoId?: number;
    nivelHierarquia?: 'epico' | 'historia' | 'tarefa' | 'subtarefa';
    style?: React.CSSProperties;
    placeholder?: string;
    allowClear?: boolean;
    disabled?: boolean;
}

export function TipoTarefaSelector({
    value,
    onChange,
    projetoId,
    nivelHierarquia,
    style,
    placeholder = 'Selecione o tipo de tarefa',
    allowClear = true,
    disabled = false,
}: TipoTarefaSelectorProps) {
    // Buscar tipos de tarefa
    const endpoint = projetoId
        ? API_ENDPOINTS.tiposTarefa.tiposPorProjeto(projetoId)
        : API_ENDPOINTS.tiposTarefa.index;

    const { data: tiposData, isLoading } = useQueryCache<{ data: TipoTarefa[] }>({
        queryKey: queryKeys.tiposTarefaCatalog.byScope(projetoId ? `projeto-${projetoId}` : 'all'),
        endpoint,
        params: nivelHierarquia ? { nivel: nivelHierarquia } : undefined,
        staleTime: 5 * 60 * 1000, // 5 minutos
    });

    const tipos = tiposData?.data || [];

    // Filtrar por nível de hierarquia se especificado
    const tiposFiltrados = nivelHierarquia
        ? tipos.filter((tipo) => tipo.nivel_hierarquia === nivelHierarquia)
        : tipos;

    const getNivelColor = (nivel: string) => {
        switch (nivel) {
            case 'epico':
                return 'purple';
            case 'historia':
                return 'blue';
            case 'tarefa':
                return 'green';
            case 'subtarefa':
                return 'default';
            default:
                return 'default';
        }
    };

    return (
        <Select
            value={value}
            onChange={onChange}
            style={{ width: '100%', ...style }}
            placeholder={placeholder}
            loading={isLoading}
            allowClear={allowClear}
            disabled={disabled}
            showSearch
            optionFilterProp="label"
            filterOption={(input, option) =>
                (typeof option?.label === 'string' ? option.label : '')
                    .toLowerCase()
                    .includes(input.toLowerCase())
            }
        >
            {tiposFiltrados
                .filter((tipo) => tipo.ativo)
                .map((tipo) => (
                    <Select.Option
                        key={tipo.id}
                        value={tipo.id}
                        label={`${tipo.chave} ${tipo.nome}`}
                    >
                        <Space>
                            <Tag color={getNivelColor(tipo.nivel_hierarquia)}>
                                {tipo.chave}
                            </Tag>
                            {tipo.nome}
                        </Space>
                    </Select.Option>
                ))}
        </Select>
    );
}

