'use client';

import { useState } from 'react';
import { Alert, Button, Form, Input, Select, Space, Typography } from 'antd';
import { message } from '@/lib/feedback/message';
import { confirmDialog } from '@/lib/feedback/confirmDialog';
import ContentCard from '@/components/layouts/ContentCard';
import { getLaravelApiErrorMessage } from '@/lib/api/laravelApiErrorMessage';
import { materializarProjetos } from '@/lib/api/fluxoComercialClient';

const { Text } = Typography;

export type NegocioMaterializarProjetosCardProps = {
    negocioId: number;
    /** Exige permissão de criar/atualizar projeto no pai. */
    canMaterializar: boolean;
    onSuccess?: () => void;
};

type FormValues = {
    nome: string;
    papel: 'superficie' | 'entrega' | 'discovery';
};

/**
 * F11/F12 — materializar projetos 1:N / discovery a partir do negócio pós-contratação.
 */
export function NegocioMaterializarProjetosCard({
    negocioId,
    canMaterializar,
    onSuccess,
}: NegocioMaterializarProjetosCardProps) {
    const [form] = Form.useForm<FormValues>();
    const [loading, setLoading] = useState(false);
    const [ultimoMsg, setUltimoMsg] = useState<string | null>(null);

    if (!canMaterializar) {
        return null;
    }

    const handleSubmit = (values: FormValues) => {
        confirmDialog({
            title: 'Materializar projeto a partir do negócio?',
            content:
                'Cria superfície(s) de projeto ligadas a este negócio (1:N pós-contratação / discovery). Use só após contrato ou handoff comercial.',
            okText: 'Materializar',
            cancelText: 'Cancelar',
            onOk: async () => {
                setLoading(true);
                try {
                    const res = await materializarProjetos(negocioId, {
                        superficies: [
                            {
                                nome: values.nome.trim(),
                                papel: values.papel,
                            },
                        ],
                    });
                    const msg = res.message ?? 'Projetos materializados.';
                    setUltimoMsg(msg);
                    message.success(msg);
                    form.resetFields(['nome']);
                    onSuccess?.();
                } catch (err: unknown) {
                    message.error(
                        getLaravelApiErrorMessage(
                            err,
                            'Não foi possível materializar os projetos. Verifique permissões e contrato.',
                        ),
                    );
                } finally {
                    setLoading(false);
                }
            },
        });
    };

    return (
        <ContentCard
            title="Materializar projetos (1:N)"
            data-testid="crm-negocio-materializar-projetos"
            style={{ marginBottom: 16 }}
        >
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                <Text type="secondary" style={{ fontSize: 13 }}>
                    Após contratação, crie superfícies adicionais (entrega ou discovery paga)
                    sem duplicar o planejamento pré-venda 1:1.
                </Text>
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleSubmit}
                    initialValues={{ papel: 'superficie' }}
                    requiredMark="optional"
                >
                    <Form.Item
                        name="nome"
                        label="Nome do projeto / superfície"
                        rules={[
                            { required: true, message: 'Informe o nome.' },
                            { max: 255, message: 'Máximo de 255 caracteres.' },
                        ]}
                    >
                        <Input
                            placeholder="Ex.: Discovery UX — lote 2"
                            data-testid="crm-negocio-materializar-nome"
                        />
                    </Form.Item>
                    <Form.Item name="papel" label="Papel" rules={[{ required: true }]}>
                        <Select
                            options={[
                                { value: 'superficie', label: 'Superfície' },
                                { value: 'entrega', label: 'Entrega' },
                                { value: 'discovery', label: 'Discovery' },
                            ]}
                            data-testid="crm-negocio-materializar-papel"
                        />
                    </Form.Item>
                    <Button
                        type="primary"
                        htmlType="submit"
                        loading={loading}
                        data-testid="crm-negocio-materializar-submit"
                    >
                        Materializar
                    </Button>
                </Form>
                {ultimoMsg ? (
                    <Alert
                        type="success"
                        showIcon
                        message={ultimoMsg}
                        data-testid="crm-negocio-materializar-sucesso"
                    />
                ) : null}
            </Space>
        </ContentCard>
    );
}
