'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { Modal, Select } from 'antd';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useResponsiveModalProps } from '@/hooks/useResponsiveModalProps';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { FormGroup } from '@/components/form';
import { queryKeys } from '@/lib/cache/queryKeys';

type ProjetoOption = { id: number; nome: string };

interface ProjetosPaginated {
    data: ProjetoOption[];
}

export type ModalHerdarEscopoProjetoProps = {
    open: boolean;
    projetoAtualId: string;
    confirmLoading?: boolean;
    onClose: () => void;
    onConfirm: (projetoOrigemId: number) => void;
};

export function ModalHerdarEscopoProjeto({
    open,
    projetoAtualId,
    confirmLoading = false,
    onClose,
    onConfirm,
}: ModalHerdarEscopoProjetoProps) {
    const modalLayout = useResponsiveModalProps();
    const [projetoId, setProjetoId] = useState<string>('');

    const { data: response, isLoading } = useQueryCache<ProjetosPaginated>({
        queryKey: queryKeys.projetos.selectHerdarEscopo(projetoAtualId),
        endpoint: API_ENDPOINTS.projetos.index,
        params: { per_page: 100, sort: 'nome' },
        enabled: open,
        staleTime: 5 * 60 * 1000,
    });

    const options = useMemo(
        () =>
            (response?.data ?? [])
                .filter((p) => String(p.id) !== String(projetoAtualId))
                .map((p) => ({
                    label: p.nome,
                    value: String(p.id),
                })),
        [response?.data, projetoAtualId],
    );

    useEffect(() => {
        if (!open) {
            setProjetoId('');
        }
    }, [open]);

    return (
        <Modal
            title="Herdar escopo de outro projeto"
            open={open}
            onCancel={onClose}
            onOk={() => {
                if (!projetoId) return;
                onConfirm(Number(projetoId));
            }}
            okText="Carregar escopo"
            okButtonProps={{ disabled: !projetoId, loading: confirmLoading }}
            cancelText="Cancelar"
            width={modalLayout.width ?? 520}
            centered={modalLayout.centered}
            styles={modalLayout.styles}
            destroyOnHidden
            data-testid="projeto-escopo-modal-herdar"
        >
            <p style={{ marginBottom: 16 }}>
                O texto de escopo do projeto escolhido será colocado no formulário. Revise e clique em
                Salvar para aplicar.
            </p>
            <FormGroup label="Projeto de origem" required>
                <Select
                    showSearch
                    placeholder="Selecione um projeto cadastrado"
                    loading={isLoading}
                    options={options}
                    value={projetoId || undefined}
                    onChange={(value) => setProjetoId(value)}
                    optionFilterProp="label"
                    style={{ width: '100%' }}
                    aria-label="Projeto de origem do escopo"
                    data-testid="projeto-escopo-herdar-select"
                />
            </FormGroup>
        </Modal>
    );
}
