/**
 * @fileoverview Componente HistoriaUsuarioSelector - Seletor de História de Usuário
 *
 * @description
 * Componente de seleção de história de usuário para um projeto.
 * Permite filtrar por épico e exibe as histórias disponíveis.
 *
 * @module tarefas
 * @author Sistema de Gestão
 * @since 1.0.0
 */

'use client';

import React, { useEffect, useState } from 'react';
import { Select, Spin } from 'antd';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';
import { HistoriaUsuario } from '@/types/projeto';

const { Option } = Select;

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

export function HistoriaUsuarioSelector({
    value,
    onChange,
    projetoId,
    epicoId,
    style,
    placeholder = 'Selecione uma história de usuário',
    allowClear = true,
    disabled = false,
}: HistoriaUsuarioSelectorProps) {
    const [epicoFilter, setEpicoFilter] = useState<number | undefined>(
        epicoId !== null && epicoId !== undefined ? epicoId : undefined
    );

    const { data: historiasData, isLoading } = useQueryCache<{
        data: HistoriaUsuario[];
    }>({
        queryKey: queryKeys.historiasUsuario.byProjetoEpico(projetoId, epicoFilter),
        endpoint: API_ENDPOINTS.historiasUsuario.index(projetoId, {
            epico_id: epicoFilter,
        }),
        enabled: !!projetoId,
        staleTime: 2 * 60 * 1000,
    });

    const historias = historiasData?.data || [];

    useEffect(() => {
        if (epicoId !== null && epicoId !== undefined) {
            setEpicoFilter(epicoId);
        }
    }, [epicoId]);

    const handleChange = (newValue: number | null) => {
        onChange?.(newValue || null);
    };

    return (
        <Select
            value={value || null}
            onChange={handleChange}
            style={style}
            placeholder={placeholder}
            allowClear={allowClear}
            disabled={disabled}
            showSearch
            optionFilterProp="label"
            loading={isLoading}
            notFoundContent={isLoading ? <Spin size="small" /> : null}
            filterOption={(input, option) =>
                (typeof option?.label === 'string' ? option.label : '')
                    .toLowerCase()
                    .includes(input.toLowerCase())
            }
        >
            {historias.map((historia) => (
                <Option
                    key={historia.id}
                    value={historia.id}
                    label={`${historia.codigo} ${historia.titulo}`}
                >
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span style={{ color: '#722ed1', fontWeight: 500 }}>
                            {historia.codigo}
                        </span>
                        <span>{historia.titulo}</span>
                    </div>
                </Option>
            ))}
        </Select>
    );
}

