'use client';

import { Plus } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useMemo } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Card, Empty, Spin, Tag, Space } from 'antd';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import { ButtonHeaderIcon } from '@/components/ui';
import { OperativeRouteHint } from '@/components/layouts/OperativeRouteHint/OperativeRouteHint';
import type { HistoriaUsuario } from '@/types/projeto';

/**
 * Página de listagem de Histórias de Usuário do projeto.
 * @route /projetos/[id]/historias-usuario
 */
export default function HistoriasUsuarioPage() {
    const params = useParams();
    const router = useRouter();
    const projetoId = params?.id as string;

    const { data: projeto } = useQueryCache<{ id: number; nome: string }>({
        queryKey: queryKeys.projetos.legacyShow(projetoId),
        endpoint: API_ENDPOINTS.projetos.show(projetoId),
        enabled: !!projetoId,
        staleTime: 5 * 60 * 1000});

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

    const historias = historiasData?.data ?? [];
    const projetoNome = projeto?.nome ?? 'Projeto';

    const historiasComRiscoCount = useMemo(
        () =>
            historias.filter((h) => {
                const semAceite = !h.criterios_aceitacao?.length;
                const urgente = h.prioridade === 'urgente' || h.prioridade === 'alta';
                return semAceite || urgente;
            }).length,
        [historias]
    );

    const breadcrumbItems = [
        { title: 'PROJETO' },
        { title: projetoNome, path: `/projetos/${projetoId}` },
        { title: 'Histórias de usuário' },
    ];

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Histórias de usuário"
            pageIcon="book"
            titleSection="Histórias de usuário"
            breadcrumbItems={breadcrumbItems}
            headerAction={
                <ButtonHeaderIcon
                    icon={<Plus size={ICON_SIZE_MD} aria-hidden />}
                    title="Nova história"
                    onClick={() => router.push(`/projetos/${projetoId}/historias-usuario/create`)}
                    variant="primary"
                />
            }
        >
            <OperativeRouteHint
                type={historiasComRiscoCount > 0 ? 'warning' : 'info'}
                message="Priorização e prontidão para sprint"
                description={
                    historiasComRiscoCount > 0
                        ? `${historiasComRiscoCount} história(s) com critérios de aceite em falta ou prioridade alta — abra o detalhe para refinar antes do planning.`
                        : 'Ordene mentalmente por valor e prioridade; confirme critérios de aceite e dependências antes de puxar para a sprint.'
                }
            />

            <ContentCard>
                {isLoading ? (
                    <div style={{ textAlign: 'center', padding: 48 }}>
                        <Spin size="large" />
                    </div>
                ) : historias.length === 0 ? (
                    <Empty
                        description="Nenhuma história de usuário encontrada"
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                    >
                        <a
                            href="#"
                            onClick={(e) => {
                                e.preventDefault();
                                router.push(`/projetos/${projetoId}/historias-usuario/create`);
                            }}
                        >
                            Criar primeira história
                        </a>
                    </Empty>
                ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                        {historias.map((h) => (
                            <Card
                                key={h.id}
                                size="small"
                                hoverable
                                style={{
                                    borderColor:
                                        !h.criterios_aceitacao?.length ||
                                        h.prioridade === 'urgente' ||
                                        h.prioridade === 'alta'
                                            ? '#faad14'
                                            : undefined}}
                                onClick={() =>
                                    router.push(`/projetos/${projetoId}/historias-usuario/${h.id}`)
                                }
                            >
                                <Space wrap size="small" style={{ marginBottom: 4 }}>
                                    {h.prioridade && (
                                        <Tag
                                            color={
                                                h.prioridade === 'urgente' || h.prioridade === 'alta'
                                                    ? 'error'
                                                    : 'default'
                                            }
                                        >
                                            {h.prioridade}
                                        </Tag>
                                    )}
                                    {!h.criterios_aceitacao?.length && (
                                        <Tag color="warning">Sem critérios de aceite</Tag>
                                    )}
                                </Space>
                                <strong>{h.titulo ?? `História #${h.id}`}</strong>
                                {h.descricao && (
                                    <p style={{ margin: '8px 0 0', color: '#666', fontSize: 13 }}>
                                        {h.descricao.slice(0, 120)}
                                        {h.descricao.length > 120 ? '...' : ''}
                                    </p>
                                )}
                            </Card>
                        ))}
                    </div>
                )}
            </ContentCard>
        </ProjetoLayout>
    );
}
