'use client';

/**
 * Gantt agregado read-only (barras programa + superfícies + sprints ativas).
 *
 * @route /projetos/[id]/produto/cronograma/gantt
 */

import { ArrowLeft, ChartGantt } from 'lucide-react';
import Link from 'next/link';
import React, { useMemo } from 'react';
import { useParams } from 'next/navigation';
import { Alert, Button, Progress, Table, Tag, Typography } from 'antd';
import dayjs from 'dayjs';
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 BarraGantt = {
    id: number;
    tipo: 'programa' | 'superficie' | 'sprint';
    rotulo: string;
    grupo: string;
    data_inicio?: string | null;
    data_fim?: string | null;
    progresso_percentual?: number | null;
    projeto_id?: number | null;
};

type CronogramaApiResponse = {
    data: {
        resumo: { data_inicio_min?: string | null; data_fim_prevista_max?: string | null };
        barras_gantt: BarraGantt[];
        meta?: { read_only?: boolean };
    };
};

const TIPO_COLOR: Record<string, string> = {
    programa: 'purple',
    superficie: 'blue',
    sprint: 'green',
};

export function ProjetoProdutoCronogramaGanttScreen() {
    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 barras = data?.data?.barras_gantt ?? [];
    const resumo = data?.data?.resumo;

    const timelineInicio = resumo?.data_inicio_min;
    const timelineFim = resumo?.data_fim_prevista_max;

    const columns = useMemo(
        () => [
            {
                title: 'Tipo',
                dataIndex: 'tipo',
                width: 110,
                render: (tipo: string) => <Tag color={TIPO_COLOR[tipo] ?? 'default'}>{tipo}</Tag>,
            },
            {
                title: 'Item',
                dataIndex: 'rotulo',
                render: (rotulo: string, row: BarraGantt) =>
                    row.projeto_id ? (
                        <Link href={`/projetos/${row.projeto_id}`}>{rotulo}</Link>
                    ) : (
                        rotulo
                    ),
            },
            {
                title: 'Grupo',
                dataIndex: 'grupo',
                width: 100,
            },
            {
                title: 'Período',
                key: 'periodo',
                width: 220,
                render: (_: unknown, row: BarraGantt) =>
                    row.data_inicio ? `${row.data_inicio} → ${row.data_fim ?? '?'}` : '—',
            },
            {
                title: 'Linha temporal (MVP)',
                key: 'barra',
                render: (_: unknown, row: BarraGantt) => {
                    if (!row.data_inicio || !timelineInicio || !timelineFim) {
                        return <Typography.Text type="secondary">—</Typography.Text>;
                    }
                    const start = dayjs(timelineInicio);
                    const end = dayjs(timelineFim);
                    const totalDays = Math.max(end.diff(start, 'day'), 1);
                    const offset = Math.max(dayjs(row.data_inicio).diff(start, 'day'), 0);
                    const duration = row.data_fim
                        ? Math.max(dayjs(row.data_fim).diff(dayjs(row.data_inicio), 'day'), 1)
                        : 1;
                    const leftPct = Math.min((offset / totalDays) * 100, 100);
                    const widthPct = Math.min((duration / totalDays) * 100, 100 - leftPct);

                    return (
                        <div style={{ position: 'relative', height: 24, background: '#f5f5f5', borderRadius: 4 }}>
                            <div
                                style={{
                                    position: 'absolute',
                                    left: `${leftPct}%`,
                                    width: `${Math.max(widthPct, 2)}%`,
                                    top: 4,
                                    bottom: 4,
                                    background: TIPO_COLOR[row.tipo] === 'purple' ? '#722ed1' : '#1677ff',
                                    borderRadius: 4,
                                    opacity: 0.85,
                                }}
                            />
                        </div>
                    );
                },
            },
            {
                title: 'Progresso',
                dataIndex: 'progresso_percentual',
                width: 120,
                render: (p: number | null | undefined) =>
                    p != null ? <Progress percent={Math.round(p)} size="small" /> : '—',
            },
        ],
        [timelineInicio, timelineFim],
    );

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Gantt agregado"
            titleSection="Gantt agregado"
            headerAction={
                <Link href={`/projetos/${projetoId}/produto/cronograma`}>
                    <Button icon={<ArrowLeft size={16} aria-hidden />}>Cronograma</Button>
                </Link>
            }
        >
            {data?.data?.meta?.read_only ? (
                <Alert
                    type="info"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message="Visualização read-only"
                    description="MVP: barras agregadas por programa, superfície e sprint ativa — sem edição de tarefas."
                />
            ) : null}

            {isError ? (
                <Alert
                    type="error"
                    showIcon
                    message="Erro ao carregar Gantt"
                    action={<Button onClick={() => void refetch()}>Tentar novamente</Button>}
                />
            ) : (
                <ContentCard title="Barras agregadas" icon={<ChartGantt size={18} aria-hidden />}>
                    <Table<BarraGantt>
                        rowKey={(row: any) => `${row.tipo}-${row.id}`}
                        loading={isLoading}
                        columns={columns}
                        dataSource={barras}
                        pagination={false}
                    />
                </ContentCard>
            )}
        </ProjetoLayout>
    );
}
