'use client';

/**
 * Cronograma master do programa (datas agregadas por superfície).
 *
 * @route /projetos/[id]/produto/cronograma
 */

import { ArrowLeft, Calendar, ChartGantt } from 'lucide-react';
import Link from 'next/link';
import React from 'react';
import { useParams } from 'next/navigation';
import { Alert, Button, Descriptions, Progress, Table, Tag, Typography } from 'antd';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';

type SuperficieCronograma = {
    projeto_id: number;
    nome: string;
    codigo_superficie?: string | null;
    data_inicio?: string | null;
    data_fim_prevista?: string | null;
    progresso_percentual?: number | null;
};

type CronogramaApiResponse = {
    data: {
        resumo: {
            data_inicio_min?: string | null;
            data_fim_prevista_max?: string | null;
            superficies_com_datas?: number;
        };
        superficies: SuperficieCronograma[];
    };
};

export function ProjetoProdutoCronogramaScreen() {
    const params = useParams();
    const projetoId = params?.id as string;

    const { data, isLoading, isError, refetch } = useQueryCache<CronogramaApiResponse>({
        queryKey: queryKeys.projetos.portfolioCronogramaLegacy(projetoId),
        endpoint: API_ENDPOINTS.projetos.portfolioCronograma(projetoId),
        enabled: Boolean(projetoId),
    });

    const resumo = data?.data?.resumo;
    const superficies = data?.data?.superficies ?? [];

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Cronograma master"
            titleSection="Cronograma master"
            headerAction={
                <Link href={`/projetos/${projetoId}/produto/cronograma/gantt`}>
                    <Button icon={<ChartGantt size={16} aria-hidden />}>Gantt agregado</Button>
                </Link>
            }
        >
            {isError ? (
                <Alert
                    type="error"
                    showIcon
                    message="Erro ao carregar cronograma"
                    action={<Button onClick={() => void refetch()}>Tentar novamente</Button>}
                />
            ) : (
                <>
                    <Descriptions bordered size="small" style={{ marginBottom: 24 }}>
                        <Descriptions.Item label="Início (mín.)">
                            {resumo?.data_inicio_min ?? '—'}
                        </Descriptions.Item>
                        <Descriptions.Item label="Fim previsto (máx.)">
                            {resumo?.data_fim_prevista_max ?? '—'}
                        </Descriptions.Item>
                        <Descriptions.Item label="Superfícies com datas">
                            {resumo?.superficies_com_datas ?? 0}
                        </Descriptions.Item>
                    </Descriptions>

                    <ContentCard title="Superfícies" icon={<Calendar size={18} aria-hidden />}>
                        <Table<SuperficieCronograma>
                            rowKey="projeto_id"
                            loading={isLoading}
                            pagination={false}
                            dataSource={superficies}
                            columns={[
                                {
                                    title: 'Superfície',
                                    dataIndex: 'codigo_superficie',
                                    render: (c: string | null) => (c ? <Tag>{c}</Tag> : '—'),
                                },
                                {
                                    title: 'Projeto',
                                    dataIndex: 'nome',
                                    render: (nome: string, row) => (
                                        <Link href={`/projetos/${row.projeto_id}`}>{nome}</Link>
                                    ),
                                },
                                {
                                    title: 'Início',
                                    dataIndex: 'data_inicio',
                                    render: (d: string | null) => d ?? '—',
                                },
                                {
                                    title: 'Fim previsto',
                                    dataIndex: 'data_fim_prevista',
                                    render: (d: string | null) => d ?? '—',
                                },
                                {
                                    title: 'Progresso',
                                    dataIndex: 'progresso_percentual',
                                    render: (p: number | null) =>
                                        p != null ? <Progress percent={Math.round(p)} size="small" /> : '—',
                                },
                            ]}
                        />
                    </ContentCard>
                </>
            )}
        </ProjetoLayout>
    );
}
