'use client';

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

interface Epico {
    id: number;
    codigo: string;
    nome: string;
    descricao?: string;
    cor?: string;
    status?: string;
    progresso: number;
    projeto_id: number;
    origem?: 'local' | 'programa';
    escopo_programa?: boolean;
}

interface EpicoSelectorProps {
    value?: number;
    onChange?: (value: number | undefined) => void;
    projetoId: number;
    style?: React.CSSProperties;
    placeholder?: string;
    allowClear?: boolean;
    disabled?: boolean;
}

export function EpicoSelector({
    value,
    onChange,
    projetoId,
    style,
    placeholder = 'Selecione um épico',
    allowClear = true,
    disabled = false,
}: EpicoSelectorProps) {
    // Épicos disponíveis (locais + programa quando subprojeto)
    const { data: epicosData, isLoading } = useQueryCache<{
        data: Epico[];
        meta?: { inclui_epicos_programa?: boolean };
    }>({
        queryKey: queryKeys.epicosCatalog.disponiveis(projetoId),
        endpoint: API_ENDPOINTS.epicos.disponiveis(projetoId),
        enabled: !!projetoId,
        staleTime: 5 * 60 * 1000,
    });

    const epicos = epicosData?.data ?? [];

    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())
            }
            notFoundContent={isLoading ? 'Carregando...' : 'Nenhum épico encontrado'}
        >
            {epicos.map((epico) => (
                <Select.Option
                    key={epico.id}
                    value={epico.id}
                    label={`${epico.codigo} ${epico.nome}`}
                >
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        {epico.cor && (
                            <div
                                style={{
                                    width: 12,
                                    height: 12,
                                    borderRadius: '50%',
                                    backgroundColor: epico.cor,
                                    flexShrink: 0,
                                }}
                            />
                        )}
                        <Tag color={epico.cor || 'default'}>{epico.codigo}</Tag>
                        <span>{epico.nome}</span>
                        {epico.origem === 'programa' ? (
                            <Tag color="blue" style={{ margin: 0 }}>
                                programa
                            </Tag>
                        ) : null}
                        {(() => {
                            const progressoPct = Number(epico.progresso);
                            if (!Number.isFinite(progressoPct)) return null;
                            return (
                                <span style={{ marginLeft: 'auto', color: '#999', fontSize: 12 }}>
                                    {progressoPct.toFixed(0)}%
                                </span>
                            );
                        })()}
                    </div>
                </Select.Option>
            ))}
        </Select>
    );
}

