'use client';

/**
 * Seção genérica "Salvar filtros": botão + modal para persistir vista na API `/v1/filtros-salvos`.
 * Complementa {@link ListingFiltersTab} (listar/aplicar/remover).
 */

import React, { useEffect, useState } from 'react';
import { Save } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import { Button, Form, Input, Modal, Radio, Typography } from 'antd';
import { message } from '@/lib/feedback/message';
import { useMutationCache } from '@/hooks/useMutationCache';
import {
    mergeWaygestFormModalBodyStyles,
    useWaygestFormModalProps,
    waygestFormModalFooterClassName,
} from '@/hooks/useWaygestFormModalProps';
import { queryKeys } from '@/lib/cache/queryKeys';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import gridStyles from '@/features/pessoas/components/pessoaDetalheSublistaFormGrid.module.scss';
import { useLocale } from '@/contexts/LocaleContext';

const LISTING_SAVED_FILTER_FORM_ID = 'listing-saved-filter-form';

type SaveFormShape = {
    nome: string;
    is_shared: boolean;
};

export type ListingSavedFiltersSectionProps = {
    /** Chave do módulo em `/v1/filtros-salvos`. */
    moduleKey: string;
    enabled: boolean;
    /** Chave estável do rascunho atual (fecha modal ao mudar critérios). */
    snapshotKey: string;
    buildPayload: () => unknown;
    dataTestIdPrefix?: string;
    /** Sobrescreve `data-testid` do botão (listagens legadas). */
    openButtonTestId?: string;
    /** Sobrescreve `data-testid` do modal (listagens legadas). */
    modalTestId?: string;
    buttonLabel?: string;
    modalTitle?: string;
    saveDescription?: React.ReactNode;
};

export function ListingSavedFiltersSection({
    moduleKey,
    enabled,
    snapshotKey,
    buildPayload,
    dataTestIdPrefix,
    openButtonTestId,
    modalTestId,
    buttonLabel,
    modalTitle,
    saveDescription,
}: ListingSavedFiltersSectionProps) {
    const { t } = useLocale();
    const [saveForm] = Form.useForm<SaveFormShape>();
    const [saveModalOpen, setSaveModalOpen] = useState(false);
    const salvarVistaModalLayout = useWaygestFormModalProps();
    const savedListQueryKey = queryKeys.filtrosSalvos.list(moduleKey);

    const saveMutation = useMutationCache<
        unknown,
        SaveFormShape & { payload: unknown }
    >({
        endpoint: API_ENDPOINTS.filtrosSalvos.store,
        method: 'POST',
        buildBody: (v) => ({
            module_key: moduleKey,
            nome: v.nome.trim(),
            is_shared: v.is_shared,
            payload: v.payload,
        }),
        invalidateQueries: [savedListQueryKey],
        onSuccess: () => {
            message.success(t('listing.filters.save.success'));
            saveForm.resetFields();
            saveForm.setFieldsValue({ is_shared: false });
            setSaveModalOpen(false);
        },
        onError: (e: Error) => {
            message.error(e.message || t('listing.filters.save.error'));
        },
    });

    useEffect(() => {
        if (!enabled) return;
        saveForm.setFieldsValue({ nome: '', is_shared: false });
    }, [enabled, snapshotKey, saveForm]);

    useEffect(() => {
        if (!enabled) setSaveModalOpen(false);
    }, [enabled]);

    const handleSalvarFiltroAtual = async (values: SaveFormShape) => {
        await saveMutation.mutateAsync({
            ...values,
            payload: buildPayload(),
        });
    };

    const cancelarSalvar = () => {
        saveForm.resetFields();
        saveForm.setFieldsValue({ is_shared: false });
        setSaveModalOpen(false);
    };

    const testIdBase = dataTestIdPrefix ?? moduleKey.replace(/[^a-z0-9]+/gi, '-');
    const resolvedButtonLabel = buttonLabel ?? t('listing.filters.save.button');
    const resolvedModalTitle = modalTitle ?? t('listing.filters.save.modalTitle');
    const resolvedSaveDescription =
        saveDescription ?? t('listing.filters.save.description');

    return (
        <div>
            <Button
                type="default"
                icon={<Save size={ICON_SIZE_MD} aria-hidden />}
                data-testid={openButtonTestId ?? `${testIdBase}-salvar-filtros-abrir`}
                onClick={() => setSaveModalOpen(true)}
            >
                {resolvedButtonLabel}
            </Button>
            <Modal
                title={resolvedModalTitle}
                data-testid={modalTestId ?? `${testIdBase}-salvar-vista-modal`}
                open={saveModalOpen}
                onCancel={cancelarSalvar}
                destroyOnHidden
                maskClosable={!saveMutation.isPending}
                closable={!saveMutation.isPending}
                width={salvarVistaModalLayout.width ?? 480}
                centered={salvarVistaModalLayout.centered ?? true}
                className={salvarVistaModalLayout.className}
                styles={mergeWaygestFormModalBodyStyles(salvarVistaModalLayout)}
                zIndex={salvarVistaModalLayout.zIndex}
                keyboard
                focusTriggerAfterClose
                footer={
                    <div className={waygestFormModalFooterClassName}>
                        <Button onClick={cancelarSalvar} disabled={saveMutation.isPending}>
                            {t('common.cancel')}
                        </Button>
                        <Button
                            type="primary"
                            htmlType="submit"
                            form={LISTING_SAVED_FILTER_FORM_ID}
                            loading={saveMutation.isPending}
                        >
                            {t('common.save')}
                        </Button>
                    </div>
                }
            >
                {typeof resolvedSaveDescription === 'string' ? (
                    <Typography.Paragraph type="secondary" style={{ marginBottom: 16, fontSize: 13 }}>
                        {resolvedSaveDescription}
                    </Typography.Paragraph>
                ) : (
                    resolvedSaveDescription
                )}
                <Form
                    id={LISTING_SAVED_FILTER_FORM_ID}
                    form={saveForm}
                    layout="vertical"
                    initialValues={{ is_shared: false }}
                    onFinish={(values) => void handleSalvarFiltroAtual(values)}
                >
                    <div className={gridStyles.pessoaDetalheSublistaFormGrid}>
                        <Form.Item
                            name="nome"
                            label={t('listing.filters.form.name.label')}
                            rules={[{ required: true, message: t('listing.filters.form.name.required') }, { max: 255 }]}
                        >
                            <Input placeholder={t('listing.filters.form.name.placeholder')} maxLength={255} allowClear />
                        </Form.Item>
                        <Form.Item name="is_shared" label={t('listing.filters.form.visibility.label')}>
                            <Radio.Group>
                                <Radio value={false}>{t('listing.filters.form.visibility.private')}</Radio>
                                <Radio value={true}>{t('listing.filters.form.visibility.shared')}</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </div>
                </Form>
            </Modal>
        </div>
    );
}
