'use client';

/**
 * Gestão de superfícies (subprojetos) do programa.
 *
 * @route /projetos/[id]/produto/superficies
 */

import Link from 'next/link';
import React, { useState } from 'react';
import { useParams } from 'next/navigation';
import { Button, Space, Tooltip } from 'antd';
import { FileUp, Plus } from 'lucide-react';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';
import {
    normalizarProjetoResponse,
    type ProjetoShowApiResponse,
} from '@/features/projetos/utils/normalizeProjetoShowResponse';
import { ProjetoSubprojetosPanel } from '@/features/projetos/projeto-subprojetos/ProjetoSubprojetosPanel';
import { useProjetoWriteGates } from '@/features/projetos/hooks/useProjetoWriteGates';
import { ProdutoImportCsvModal } from '@/features/projetos/produto-importacao-csv';

export function ProjetoProdutoSuperficiesScreen() {
    const params = useParams();
    const projetoId = params?.id as string;
    const [importOpen, setImportOpen] = useState(false);
    /** AuthZ import tipológico = `projetos.criar` (ProjetoPolicy::importarCsv). */
    const { canCriar, permsLoading, tooltipSemPermissao } = useProjetoWriteGates();

    const { data: projetoRaw, refetch } = useQueryCache<ProjetoShowApiResponse>({
        queryKey: queryKeys.projetos.detail(projetoId),
        endpoint: API_ENDPOINTS.projetos.show(projetoId),
        enabled: Boolean(projetoId),
        staleTime: 5 * 60 * 1000,
    });

    const projeto = normalizarProjetoResponse(projetoRaw);

    const importCta = permsLoading || canCriar ? (
        <Button
            icon={<FileUp size={16} aria-hidden />}
            onClick={() => setImportOpen(true)}
            loading={permsLoading}
            data-testid="produto-superficies-import-csv"
        >
            Importar CSV
        </Button>
    ) : (
        <Tooltip title={tooltipSemPermissao('importar programas e superfícies via CSV')}>
            <span>
                <Button
                    icon={<FileUp size={16} aria-hidden />}
                    disabled
                    data-testid="produto-superficies-import-csv-disabled"
                >
                    Importar CSV
                </Button>
            </span>
        </Tooltip>
    );

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Superfícies"
            titleSection="Subprojetos"
            headerAction={
                <Space wrap>
                    {importCta}
                    {permsLoading || canCriar ? (
                        <Link href={`/projetos/create?projeto_pai_id=${encodeURIComponent(projetoId)}`}>
                            <Button
                                type="primary"
                                icon={<Plus size={16} aria-hidden />}
                                loading={permsLoading}
                                data-testid="produto-superficies-adicionar"
                            >
                                Adicionar subprojeto
                            </Button>
                        </Link>
                    ) : (
                        <Tooltip title={tooltipSemPermissao('criar subprojetos')}>
                            <span>
                                <Button
                                    type="primary"
                                    icon={<Plus size={16} aria-hidden />}
                                    disabled
                                    data-testid="produto-superficies-adicionar-disabled"
                                >
                                    Adicionar subprojeto
                                </Button>
                            </span>
                        </Tooltip>
                    )}
                </Space>
            }
        >
            <ProjetoSubprojetosPanel projetoId={projetoId} programaNome={projeto?.nome} />
            <ProdutoImportCsvModal
                open={importOpen}
                onClose={() => setImportOpen(false)}
                onSuccess={() => {
                    void refetch();
                }}
            />
        </ProjetoLayout>
    );
}
