'use client';

/**
 * Formulário tipológico DOC-TEC — campos de software via PUT `/projetos/{id}`.
 * Usado por arquitetura, modelo de dados, ambientes e controle documental.
 */

import { Save } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useEffect } from 'react';
import { useParams } from 'next/navigation';
import { Button, Form, Input, Spin, Tooltip } from 'antd';
import { message } from '@/lib/feedback/message';
import { notifyApiError } from '@/lib/feedback/notifyApiError';
import { FormTextarea, FormActions as FormActionsWrapper } from '@/components/form';
import { useMobilePageActionBarRegistration } from '@/components/layouts/PageShellOptions';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useMutationCache } from '@/hooks/useMutationCache';
import { useProjetoWriteGates } from '@/features/projetos/hooks/useProjetoWriteGates';
import { queryKeys } from '@/lib/cache/queryKeys';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import type { Projeto } from '@/types';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import { useProjetoBriefingFormGuard } from '@/features/projetos/hooks/useProjetoBriefingFormGuard';
import { resolveProjetoFromResponse } from '@/features/projetos/lib/resolveProjetoFromResponse';
import { ProjetoTipologicoSyncBanner } from '@/features/projetos/projeto-tipologico-empty-state';

const MAX_CHARS = 50000;

export type DocTecFormField = {
    name: string;
    label: string;
    placeholder?: string;
    rows?: number;
    maxLength?: number;
    /** `input` para campos curtos (versão, path); default textarea */
    kind?: 'textarea' | 'input';
};

export type ProjetoSoftwareDocTecFormScreenProps = {
    pageTitle: string;
    pageIcon: string;
    titleSection: string;
    /** Chave de draft do briefing guard */
    guardKey: string;
    fields: DocTecFormField[];
    emptyDomainDescription: string;
    emptyTitle: string;
    successMessage: string;
    /** Extrai valores iniciais a partir do projeto */
    pickInitialValues: (projeto: Projeto | undefined) => Record<string, string>;
    /** Monta payload PUT a partir dos valores do form */
    buildPayload: (values: Record<string, string>) => Record<string, string | null>;
    /** Critério de “vazio” para banner tipológico */
    isEmpty: (projeto: Projeto | undefined) => boolean;
    'data-testid'?: string;
};

export function ProjetoSoftwareDocTecFormScreen({
    pageTitle,
    pageIcon,
    titleSection,
    guardKey,
    fields,
    emptyDomainDescription,
    emptyTitle,
    successMessage,
    pickInitialValues,
    buildPayload,
    isEmpty,
    'data-testid': dataTestId = 'projeto-doc-tec-form',
}: ProjetoSoftwareDocTecFormScreenProps) {
    const params = useParams();
    const id = params?.id as string;
    const isMobileLayout = useIsMobile();
    const { canEditar, tooltipSemPermissao } = useProjetoWriteGates();
    const [form] = Form.useForm();
    useMobilePageActionBarRegistration(isMobileLayout);
    const {
        draftBanner,
        savedHint,
        handleFormValuesChange,
        afterSaveSuccess,
        handleCancelEdits,
    } = useProjetoBriefingFormGuard(form, id, guardKey, { enabled: canEditar });

    const { data: projetoResponse, isLoading } = useQueryCache<
        Projeto | { projeto?: Projeto; metricas?: unknown }
    >({
        queryKey: queryKeys.projetos.detail(id),
        endpoint: API_ENDPOINTS.projetos.show(id),
        enabled: !!id,
        staleTime: 1 * 60 * 1000,
        gcTime: 5 * 60 * 1000,
    });

    const projeto = resolveProjetoFromResponse(projetoResponse);

    const updateMutation = useMutationCache({
        endpoint: API_ENDPOINTS.projetos.update(id),
        method: 'PUT',
        invalidateQueries: [queryKeys.projetos.detail(id), queryKeys.projetos.lists()],
        onSuccess: () => {
            message.success(successMessage);
            afterSaveSuccess();
        },
        onError: (error: unknown) => {
            notifyApiError(error, `Erro ao salvar ${titleSection.toLowerCase()}.`, guardKey);
        },
    });

    const projetoId = projeto?.id;
    const initialValues = pickInitialValues(projeto);
    const initialSerialized = JSON.stringify(initialValues);
    const fieldNamesKey = fields.map((f) => f.name).join(',');

    useEffect(() => {
        if (projetoId == null) return;
        const names = fieldNamesKey.split(',').filter(Boolean);
        if (form.isFieldsTouched(names)) return;
        form.setFieldsValue(JSON.parse(initialSerialized) as Record<string, string>);
    }, [projetoId, initialSerialized, form, fieldNamesKey]);

    const handleSubmit = (values: Record<string, string>) => {
        updateMutation.mutate(buildPayload(values));
    };

    const tooltipSemEdicao = !canEditar
        ? tooltipSemPermissao(`editar ${titleSection.toLowerCase()}`)
        : undefined;

    if (isLoading && !projeto) {
        return (
            <ProjetoLayout
                projetoId={id}
                pageTitle={pageTitle}
                pageIcon={pageIcon}
                titleSection={titleSection}
            >
                <div style={{ textAlign: 'center', padding: 50 }}>
                    <Spin size="large" />
                </div>
            </ProjetoLayout>
        );
    }

    return (
        <ProjetoLayout
            projetoId={id}
            pageTitle={pageTitle}
            pageIcon={pageIcon}
            titleSection={titleSection}
            breadcrumbItems={[
                { title: 'PROJETO' },
                { title: projeto?.nome || 'Projeto' },
                { title: titleSection },
            ]}
        >
            {draftBanner}
            {savedHint}

            {isEmpty(projeto) ? (
                <ProjetoTipologicoSyncBanner
                    projetoId={id}
                    title={emptyTitle}
                    domainDescription={emptyDomainDescription}
                    data-testid={`${dataTestId}-sync-banner`}
                />
            ) : null}

            <Form
                form={form}
                layout="vertical"
                initialValues={initialValues}
                onFinish={handleSubmit}
                onValuesChange={handleFormValuesChange}
                data-testid={dataTestId}
            >
                <ContentCard>
                    {fields.map((field) => {
                        const max = field.maxLength ?? MAX_CHARS;
                        if (field.kind === 'input') {
                            return (
                                <Form.Item
                                    key={field.name}
                                    name={field.name}
                                    label={field.label}
                                    rules={[{ max, message: `Máximo ${max.toLocaleString('pt-BR')} caracteres.` }]}
                                >
                                    <Input
                                        placeholder={field.placeholder}
                                        allowClear
                                        disabled={!canEditar}
                                        maxLength={max}
                                    />
                                </Form.Item>
                            );
                        }
                        return (
                            <FormTextarea
                                key={field.name}
                                name={field.name}
                                label={field.label}
                                rules={[{ max, message: `Máximo ${max.toLocaleString('pt-BR')} caracteres.` }]}
                                placeholder={field.placeholder}
                                rows={field.rows ?? 12}
                                maxLength={max}
                                showCount
                                disabled={!canEditar}
                            />
                        );
                    })}
                </ContentCard>

                {!isMobileLayout ? (
                    <FormActionsWrapper>
                        <Button
                            type="default"
                            onClick={() => handleCancelEdits(pickInitialValues(projeto))}
                            disabled={updateMutation.isPending || !form.isFieldsTouched()}
                        >
                            Cancelar
                        </Button>
                        <Tooltip title={tooltipSemEdicao}>
                            <span>
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    loading={updateMutation.isPending}
                                    disabled={!canEditar}
                                    icon={<Save size={ICON_SIZE_MD} aria-hidden />}
                                    data-testid={`${dataTestId}-save`}
                                >
                                    Salvar
                                </Button>
                            </span>
                        </Tooltip>
                    </FormActionsWrapper>
                ) : (
                    <FormActionsWrapper>
                        <Tooltip title={tooltipSemEdicao}>
                            <span>
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    loading={updateMutation.isPending}
                                    disabled={!canEditar}
                                    icon={<Save size={ICON_SIZE_MD} aria-hidden />}
                                    block
                                    data-testid={`${dataTestId}-save-mobile`}
                                >
                                    Salvar
                                </Button>
                            </span>
                        </Tooltip>
                    </FormActionsWrapper>
                )}
            </Form>
        </ProjetoLayout>
    );
}
