'use client';

import { ArrowLeft, BarChart3, Calendar, CheckCircle2, List as ListIcon, Rocket, Users } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useEffect, useMemo, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Alert, Button, Card, Col, Descriptions, Divider, Empty, List, Result, Row, Space, Spin, Tag, Tooltip, Typography } from 'antd';
import { message } from '@/lib/feedback/message';
import { useQueryCache } from '@/hooks/useQueryCache';
import { queryKeys } from '@/lib/cache/queryKeys';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { formatDate } from '@/lib/utils/export';
import PageWrapper from '@/components/layouts/PageWrapper';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import { OperativeRouteHint } from '@/components/layouts/OperativeRouteHint/OperativeRouteHint';
import { ObjetivoSprint } from '../components/scrum';
import type { Sprint, Tarefa } from '@/types/projeto';
import {
    ProjetoSprintPinBar,
    ProjetoSprintPinButton,
    ProjetosShortcutsHelp,
    PROJETOS_SPRINT_DETALHE_SHORTCUT_ITEMS,
    useProjetoOperacaoHotkeys,
    useProjetoSprintPin,
} from '@/features/projetos/projeto-sprint-pin';
import { ModalSprintPlanning } from './ModalSprintPlanning';
import { ModalSprintReview } from './ModalSprintReview';
import { ModalSprintRetrospective } from './ModalSprintRetrospective';
import { ModalSprintBurndown } from './ModalSprintBurndown';
import {
    projetoPlanejamentoSprintDetalhePath,
    projetoPlanejamentoSprintsPath,
    projetoSprintBacklogPath,
    projetoSprintBoardPath,
    projetoTarefaDetalhePath,
} from './sprintDetalhePaths';
import { getSprintDetalheStatusTagColor } from './sprintDetalheDisplay';

const { Title, Text } = Typography;
const PROJETOS_LIST_PATH = '/projetos';

export interface ProjetoSprintDetalheScreenProps {
    projetoId: string;
    sprintId: string;
}

export function ProjetoSprintDetalheScreen({
    projetoId,
    sprintId,
}: ProjetoSprintDetalheScreenProps) {
    const router = useRouter();
    const searchParams = useSearchParams();
    const [shortcutsHelpOpen, setShortcutsHelpOpen] = useState(false);
    const [planningModalOpen, setPlanningModalOpen] = useState(false);
    const [reviewModalOpen, setReviewModalOpen] = useState(false);
    const [retrospectiveModalOpen, setRetrospectiveModalOpen] = useState(false);
    const [burndownModalOpen, setBurndownModalOpen] = useState(false);
    const { togglePin } = useProjetoSprintPin(projetoId);
    const projetoIdSafe = projetoId.trim();
    const sprintIdSafe = sprintId.trim();
    const idsValid = Boolean(projetoIdSafe) && Boolean(sprintIdSafe);
    const sprintsListPath = projetoPlanejamentoSprintsPath(projetoIdSafe);

    useEffect(() => {
        const openModal = searchParams?.get('openModal');
        if (
            openModal !== 'planning' &&
            openModal !== 'review' &&
            openModal !== 'retrospective'
        ) {
            return;
        }
        if (openModal === 'planning') {
            setPlanningModalOpen(true);
        } else if (openModal === 'review') {
            setReviewModalOpen(true);
        } else {
            setRetrospectiveModalOpen(true);
        }
        router.replace(projetoPlanejamentoSprintDetalhePath(projetoIdSafe, sprintIdSafe), {
            scroll: false,
        });
    }, [searchParams, projetoIdSafe, sprintIdSafe, router]);

    const sprintBreadcrumb = [
        { title: 'PROJETO', path: `/projetos/${projetoIdSafe}` },
        { title: 'Sprints', path: sprintsListPath },
        { title: 'Detalhe' },
    ];

    const {
        data: sprint,
        isLoading,
        isError,
        isFetched,
        error: queryError,
        refetch,
    } = useQueryCache<Sprint>({
        queryKey: queryKeys.desenvolvimento.sprints.detail(sprintIdSafe),
        endpoint: API_ENDPOINTS.desenvolvimento.sprints.show(sprintIdSafe),
        enabled: idsValid,
        staleTime: 1 * 60 * 1000,
        gcTime: 5 * 60 * 1000,
    });

    const errStatus = (queryError as { response?: { status?: number } } | null)?.response?.status;
    const queryErr =
        queryError instanceof Error ? queryError : queryError ? new Error(String(queryError)) : null;

    const { data: tarefasData, isLoading: loadingTarefas } = useQueryCache<{ data: Tarefa[] }>({
        queryKey: queryKeys.desenvolvimento.tarefas.list({ sprint_id: sprintIdSafe }),
        endpoint: API_ENDPOINTS.desenvolvimento.tarefas.index,
        params: { sprint_id: sprintIdSafe },
        enabled: idsValid,
        staleTime: 1 * 60 * 1000,
    });

    const tarefas = useMemo(() => tarefasData?.data ?? [], [tarefasData?.data]);

    const tarefasConcluidas = useMemo(
        () =>
            tarefas.filter(
                (t) => t.status === 'done' || t.status === 'concluida'
            ).length,
        [tarefas]
    );
    const tarefasCriticasAbertas = useMemo(
        () =>
            tarefas.filter(
                (t) =>
                    t.prioridade === 'critica' &&
                    t.status !== 'done' &&
                    t.status !== 'concluida' &&
                    t.status !== 'cancelled'
            ).length,
        [tarefas]
    );

    useProjetoOperacaoHotkeys({
        enabled: idsValid && Boolean(sprint) && !shortcutsHelpOpen,
        onOpenHelp: () => setShortcutsHelpOpen(true),
        onTogglePin: () => {
            if (!sprint) return;
            const next = togglePin({ id: sprint.id, nome: sprint.nome });
            message.success(
                next
                    ? `Sprint "${next.sprintNome}" fixada — acesse pelo atalho no topo.`
                    : 'Sprint desafixada.',
            );
        },
    });

    const eventosScrum = useMemo(
        () => [
            {
                key: 'board',
                title: 'Board da Sprint',
                icon: <BarChart3 />,
                path: projetoSprintBoardPath(projetoIdSafe, sprintIdSafe) as string | null,
                onOpen: null as (() => void) | null,
                description: 'Visualize e gerencie as tarefas no board Scrum',
            },
            {
                key: 'planning',
                title: 'Sprint Planning',
                icon: <Calendar />,
                path: null,
                onOpen: () => setPlanningModalOpen(true),
                description: 'Registre o planejamento da sprint',
            },
            {
                key: 'review',
                title: 'Sprint Review',
                icon: <CheckCircle2 />,
                path: null,
                onOpen: () => setReviewModalOpen(true),
                description: 'Registre a revisão da sprint',
            },
            {
                key: 'retrospective',
                title: 'Sprint Retrospective',
                icon: <Users />,
                path: null,
                onOpen: () => setRetrospectiveModalOpen(true),
                description: 'Registre a retrospectiva da sprint',
            },
        ],
        [projetoIdSafe, sprintIdSafe]
    );

    if (!idsValid) {
        return (
            <PageWrapper
                breadcrumbItems={[
                    { title: 'Projetos', path: PROJETOS_LIST_PATH },
                    { title: 'Sprint' },
                ]}
            >
                <Alert
                    message="Identificador inválido"
                    description="Projeto ou sprint em falta na rota."
                    type="error"
                    showIcon
                    action={
                        <Button type="primary" size="small" onClick={() => router.push(PROJETOS_LIST_PATH)}>
                            Voltar à lista de projetos
                        </Button>
                    }
                />
            </PageWrapper>
        );
    }

    if (isLoading && !sprint) {
        return (
            <ProjetoLayout
                projetoId={projetoIdSafe}
                pageTitle="Carregando…"
                pageIcon="spinner"
                titleSection="Sprint"
                breadcrumbItems={sprintBreadcrumb}
            >
                {null}
            </ProjetoLayout>
        );
    }

    if (isError) {
        const is404 = errStatus === 404;
        return (
            <ProjetoLayout
                projetoId={projetoIdSafe}
                pageTitle={is404 ? 'Não encontrado' : 'Erro'}
                pageIcon={is404 ? 'search' : 'exclamation-triangle'}
                titleSection="Sprint"
                breadcrumbItems={sprintBreadcrumb}
            >
                <ContentCard>
                    <Result
                        status={is404 ? '404' : 'error'}
                        title={is404 ? 'Sprint não encontrada' : 'Não foi possível carregar a sprint'}
                        subTitle={
                            queryErr?.message ??
                            (is404
                                ? 'A sprint não existe ou não tem permissão para a ver.'
                                : 'Tente novamente dentro de instantes.')
                        }
                        extra={
                            <Space wrap>
                                {!is404 ? (
                                    <Button type="primary" onClick={() => void refetch()}>
                                        Tentar novamente
                                    </Button>
                                ) : null}
                                <Button onClick={() => router.push(sprintsListPath)}>Voltar às sprints</Button>
                            </Space>
                        }
                    />
                </ContentCard>
            </ProjetoLayout>
        );
    }

    if (isFetched && !sprint) {
        return (
            <ProjetoLayout
                projetoId={projetoIdSafe}
                pageTitle="Não encontrado"
                pageIcon="search"
                titleSection="Sprint"
                breadcrumbItems={sprintBreadcrumb}
            >
                <ContentCard>
                    <Result
                        status="404"
                        title="Sprint não encontrada"
                        subTitle="A resposta veio vazia."
                        extra={
                            <Button type="primary" onClick={() => router.push(sprintsListPath)}>
                                Voltar às sprints
                            </Button>
                        }
                    />
                </ContentCard>
            </ProjetoLayout>
        );
    }

    const sp = sprint!;

    return (
        <ProjetoLayout
            projetoId={projetoIdSafe}
            pageTitle={sp.nome || `Sprint ${sprintIdSafe}`}
            pageIcon="rocket"
            titleSection="Sprint"
            breadcrumbItems={[
                { title: 'PROJETO', path: `/projetos/${projetoIdSafe}` },
                { title: 'Sprints', path: sprintsListPath },
                { title: sp.nome || 'Detalhe' },
            ]}
            headerAction={
                <Space wrap size={8} align="center">
                    <ProjetosShortcutsHelp
                        items={PROJETOS_SPRINT_DETALHE_SHORTCUT_ITEMS}
                        open={shortcutsHelpOpen}
                        onOpenChange={setShortcutsHelpOpen}
                        title="Atalhos — sprint"
                    />
                    <ProjetoSprintPinButton
                        projetoId={projetoIdSafe}
                        sprintId={sp.id}
                        sprintNome={sp.nome}
                        type="default"
                    />
                    <Tooltip title="Voltar à lista de sprints">
                        <span style={{ display: 'inline-block' }}>
                            <Button icon={<ArrowLeft />} onClick={() => router.push(sprintsListPath)}>
                                Voltar
                            </Button>
                        </span>
                    </Tooltip>
                </Space>
            }
        >
            <ProjetoSprintPinBar projetoId={projetoIdSafe} />
            <OperativeRouteHint
                type={tarefasCriticasAbertas > 0 ? 'warning' : 'info'}
                message="Decisão operacional"
                description={
                    tarefas.length > 0
                        ? `${tarefasConcluidas}/${tarefas.length} tarefas concluídas nesta sprint.${
                              tarefasCriticasAbertas > 0
                                  ? ` ${tarefasCriticasAbertas} com prioridade crítica ainda em aberto — priorize no board e na daily.`
                                  : ' Acompanhe riscos no board e ajuste capacidade se o burndown divergir.'
                          }`
                        : 'Sem tarefas associadas a esta sprint — confirme o backlog e o planejamento antes da execução.'
                }
            />
            <Row gutter={16} style={{ marginBottom: 16 }}>
                <Col xs={24} sm={8}>
                    <Card size="small">
                        <Text type="secondary">Progresso (tarefas)</Text>
                        <Title level={3} style={{ margin: '8px 0 0' }}>
                            {tarefas.length > 0
                                ? `${Math.round((tarefasConcluidas / tarefas.length) * 100)}%`
                                : '—'}
                        </Title>
                    </Card>
                </Col>
                <Col xs={24} sm={8}>
                    <Card size="small">
                        <Text type="secondary">Críticas em aberto</Text>
                        <Title
                            level={3}
                            style={{
                                margin: '8px 0 0',
                                color: tarefasCriticasAbertas > 0 ? '#d46b08' : undefined,
                            }}
                        >
                            {tarefasCriticasAbertas}
                        </Title>
                    </Card>
                </Col>
                <Col xs={24} sm={8}>
                    <Card size="small">
                        <Text type="secondary">Status da sprint</Text>
                        <Title level={4} style={{ margin: '8px 0 0' }}>
                            <Tag color={getSprintDetalheStatusTagColor(sp.status)}>{sp.status}</Tag>
                        </Title>
                    </Card>
                </Col>
            </Row>
            <Row gutter={[24, 24]}>
                <Col xs={24} lg={16}>
                    <ContentCard style={{ marginBottom: 24 }}>
                        <ObjetivoSprint sprint={sp} onUpdate={refetch} />
                    </ContentCard>

                    <ContentCard style={{ marginBottom: 24 }}>
                        <Title level={5}>Informações da Sprint</Title>
                        <Divider />
                        <Descriptions column={1} bordered>
                            <Descriptions.Item label="Status">
                                <Tag color={getSprintDetalheStatusTagColor(sp.status)}>
                                    {sp.status?.toUpperCase()}
                                </Tag>
                            </Descriptions.Item>
                            <Descriptions.Item label="Data de Início">
                                {sp.data_inicio ? formatDate(sp.data_inicio) : '-'}
                            </Descriptions.Item>
                            <Descriptions.Item label="Data de Fim">
                                {sp.data_fim ? formatDate(sp.data_fim) : '-'}
                            </Descriptions.Item>
                            <Descriptions.Item label="Capacidade Planejada">
                                {sp.capacidade_planejada || sp.velocidade_planejada || '-'}
                            </Descriptions.Item>
                            <Descriptions.Item label="Capacidade Realizada">
                                {sp.capacidade_realizada || sp.velocidade_real || '-'}
                            </Descriptions.Item>
                            {sp.descricao && (
                                <Descriptions.Item label="Descrição">{sp.descricao}</Descriptions.Item>
                            )}
                        </Descriptions>
                    </ContentCard>

                    <ContentCard>
                        <Title level={5}>Tarefas da Sprint</Title>
                        <Divider />
                        {loadingTarefas ? (
                            <Spin />
                        ) : tarefas.length > 0 ? (
                            <List
                                dataSource={tarefas}
                                renderItem={(tarefa) => (
                                    <List.Item
                                        actions={[
                                            <Button
                                                key="view"
                                                type="link"
                                                onClick={() =>
                                                    router.push(projetoTarefaDetalhePath(tarefa.id))
                                                }
                                            >
                                                Ver Detalhes
                                            </Button>,
                                        ]}
                                    >
                                        <List.Item.Meta
                                            title={
                                                <Space>
                                                    {tarefa.chave_tarefa && (
                                                        <Text code>{tarefa.chave_tarefa}</Text>
                                                    )}
                                                    <Text>{tarefa.titulo}</Text>
                                                </Space>
                                            }
                                            description={
                                                <Space>
                                                    <Tag
                                                        color={getSprintDetalheStatusTagColor(
                                                            tarefa.status
                                                        )}
                                                    >
                                                        {tarefa.status}
                                                    </Tag>
                                                    {tarefa.responsavel && (
                                                        <Text type="secondary">
                                                            {tarefa.responsavel.nome}
                                                        </Text>
                                                    )}
                                                </Space>
                                            }
                                        />
                                    </List.Item>
                                )}
                            />
                        ) : (
                            <Empty description="Nenhuma tarefa nesta sprint" />
                        )}
                    </ContentCard>
                </Col>

                <Col xs={24} lg={8}>
                    <ContentCard>
                        <Title level={5}>
                            <Rocket /> Eventos Scrum
                        </Title>
                        <Divider />
                        <Space direction="vertical" style={{ width: '100%' }}>
                            {eventosScrum.map((evento) => (
                                <Card
                                    key={evento.key}
                                    hoverable
                                    onClick={() => {
                                        if (evento.onOpen) {
                                            evento.onOpen();
                                            return;
                                        }
                                        if (evento.path) {
                                            router.push(evento.path);
                                        }
                                    }}
                                    style={{ cursor: 'pointer' }}
                                    data-testid={
                                        evento.key === 'planning'
                                            ? 'sprint-detalhe-evento-planning'
                                            : evento.key === 'review'
                                              ? 'sprint-detalhe-evento-review'
                                              : evento.key === 'retrospective'
                                                ? 'sprint-detalhe-evento-retrospective'
                                                : undefined
                                    }
                                >
                                    <Space>
                                        {evento.icon}
                                        <div>
                                            <Text strong>{evento.title}</Text>
                                            <br />
                                            <Text type="secondary" style={{ fontSize: 12 }}>
                                                {evento.description}
                                            </Text>
                                        </div>
                                    </Space>
                                </Card>
                            ))}
                        </Space>
                    </ContentCard>

                    <ContentCard style={{ marginTop: 24 }}>
                        <Title level={5}>Links Rápidos</Title>
                        <Divider />
                        <Space direction="vertical" style={{ width: '100%' }}>
                            <Button
                                block
                                icon={<BarChart3 />}
                                onClick={() => setBurndownModalOpen(true)}
                                data-testid="sprint-detalhe-link-burndown"
                            >
                                Burndown Chart
                            </Button>
                            <Button
                                block
                                icon={<ListIcon size={ICON_SIZE_MD} aria-hidden />}
                                onClick={() =>
                                    router.push(projetoSprintBacklogPath(projetoIdSafe, sprintIdSafe))
                                }
                            >
                                Backlog da Sprint
                            </Button>
                        </Space>
                    </ContentCard>
                </Col>
            </Row>

            <ModalSprintPlanning
                open={planningModalOpen}
                onClose={() => setPlanningModalOpen(false)}
                sprintId={sprintIdSafe}
                sprint={sp}
                onSuccess={() => void refetch()}
            />
            <ModalSprintReview
                open={reviewModalOpen}
                onClose={() => setReviewModalOpen(false)}
                sprintId={sprintIdSafe}
                sprint={sp}
                onSuccess={() => void refetch()}
            />
            <ModalSprintRetrospective
                open={retrospectiveModalOpen}
                onClose={() => setRetrospectiveModalOpen(false)}
                sprintId={sprintIdSafe}
                sprint={sp}
                onSuccess={() => void refetch()}
            />
            <ModalSprintBurndown
                open={burndownModalOpen}
                onClose={() => setBurndownModalOpen(false)}
                sprintId={sprintIdSafe}
                sprintNome={sp.nome}
            />
        </ProjetoLayout>
    );
}
