'use client';

/**
 * @route /projetos/[id]/desenvolvimento/entregas/dashboard
 * Contrato: GET /v1/entregas/resumo (CTR-GAP-DEV-002/003).
 */

import { Box, Calendar, CheckCircle2, ChevronLeft, Clock, TriangleAlert, Truck } from 'lucide-react';
import { queryKeys } from '@/lib/cache/queryKeys';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useMemo } from 'react';
import { Button, Space } from 'antd';
import { useRouter, useParams } from 'next/navigation';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import MetricsGrid from '@/components/layouts/MetricsGrid';
import MetricCard from '@/components/layouts/MetricCard';
import { OperativeRouteHint } from '@/components/layouts/OperativeRouteHint/OperativeRouteHint';

/** Shape de `EntregaService::resumoMetricas` (flat). */
interface EntregasResumoMetricas {
    total: number;
    planejadas: number;
    em_preparacao: number;
    entregue: number;
    aceita: number;
    rejeitada: number;
    cancelada?: number;
}

export default function EntregasDashboardPage() {
    const router = useRouter();
    const params = useParams();
    const projetoId = typeof params?.id === 'string' ? params.id : Array.isArray(params?.id) ? params.id[0] : '';

    const { data: resumo, isLoading } = useQueryCache<EntregasResumoMetricas>({
        queryKey: [...queryKeys.entregas.dashboard(), projetoId || 'all'],
        endpoint: API_ENDPOINTS.entregas.resumo,
        params: projetoId ? { projeto_id: projetoId } : undefined,
        staleTime: 2 * 60 * 1000,
        gcTime: 10 * 60 * 1000,
    });

    const estatisticas = useMemo(
        () => ({
            total: resumo?.total ?? 0,
            planejada: resumo?.planejadas ?? 0,
            em_preparacao: resumo?.em_preparacao ?? 0,
            entregue: resumo?.entregue ?? 0,
            aceita: resumo?.aceita ?? 0,
            rejeitada: resumo?.rejeitada ?? 0,
        }),
        [resumo],
    );

    const taxaAprovacao = useMemo(() => {
        const decididas = estatisticas.aceita + estatisticas.rejeitada;
        if (decididas === 0) return undefined;
        return Math.round((estatisticas.aceita / decididas) * 100);
    }, [estatisticas.aceita, estatisticas.rejeitada]);

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Dashboard de entregas"
            showPageTitleIcon={false}
            titleSection="Dashboard de entregas"
            headerAction={
                <Button
                    onClick={() =>
                        router.push(
                            projetoId
                                ? `/projetos/${projetoId}/desenvolvimento/entregas`
                                : '/entregas',
                        )
                    }
                >
                    <ChevronLeft size={ICON_SIZE_MD} style={{ marginRight: 8 }} aria-hidden />
                    Voltar à lista
                </Button>
            }
        >
            {projetoId ? (
                <OperativeRouteHint
                    message="Decisão com contexto"
                    description="Compare a taxa de aprovação com o volume em preparação; se o risco for alto, volte à lista deste projeto e trate caso a caso."
                >
                    <Space wrap>
                        <Button
                            type="primary"
                            onClick={() =>
                                router.push(`/projetos/${projetoId}/desenvolvimento/entregas`)
                            }
                        >
                            Lista de entregas
                        </Button>
                        <Button onClick={() => router.push(`/projetos/${projetoId}/kanban`)}>
                            Kanban
                        </Button>
                    </Space>
                </OperativeRouteHint>
            ) : null}

            <MetricsGrid columns={3} style={{ marginBottom: 24 }}>
                <MetricCard
                    icon={<Box size={ICON_SIZE_MD} aria-hidden />}
                    label="Total de Entregas"
                    value={estatisticas.total.toString()}
                    variant="projetos"
                />
                <MetricCard
                    icon={<CheckCircle2 size={ICON_SIZE_MD} aria-hidden />}
                    label="Aceitas"
                    value={estatisticas.aceita.toString()}
                    variant="concluidos"
                />
                <MetricCard
                    icon={<Clock size={ICON_SIZE_MD} aria-hidden />}
                    label="Em Preparação"
                    value={estatisticas.em_preparacao.toString()}
                    variant="emAndamento"
                />
            </MetricsGrid>

            <MetricsGrid columns={3} style={{ marginBottom: 24 }}>
                <MetricCard
                    icon={<Calendar size={ICON_SIZE_MD} aria-hidden />}
                    label="Planejadas"
                    value={estatisticas.planejada.toString()}
                    variant="emAndamento"
                />
                <MetricCard
                    icon={<Truck size={ICON_SIZE_MD} />}
                    label="Entregues"
                    value={estatisticas.entregue.toString()}
                    variant="concluidos"
                />
                <MetricCard
                    icon={<TriangleAlert size={ICON_SIZE_MD} aria-hidden />}
                    label="Rejeitadas"
                    value={estatisticas.rejeitada.toString()}
                    variant="pausados"
                />
            </MetricsGrid>

            {taxaAprovacao !== undefined && (
                <ContentCard style={{ marginBottom: 24 }}>
                    <div style={{ textAlign: 'center' }}>
                        <div
                            style={{
                                fontSize: 48,
                                fontWeight: 600,
                                color:
                                    taxaAprovacao >= 80
                                        ? '#27ae60'
                                        : taxaAprovacao >= 60
                                          ? '#faad14'
                                          : '#e3402d',
                            }}
                        >
                            {taxaAprovacao}%
                        </div>
                        <div style={{ fontSize: 18, color: '#666', marginTop: 8 }}>
                            <CheckCircle2
                                size={ICON_SIZE_MD}
                                style={{ marginRight: 8 }}
                                aria-hidden
                            />
                            Taxa de Aprovação
                        </div>
                    </div>
                </ContentCard>
            )}

            {!resumo && !isLoading && (
                <ContentCard>
                    <div style={{ textAlign: 'center', color: '#666' }}>
                        Não foi possível carregar o resumo de entregas.
                    </div>
                </ContentCard>
            )}
        </ProjetoLayout>
    );
}
