'use client';

import React from 'react';
import { Form, Input } from 'antd';
import type { FormItemProps, InputProps } from 'antd';
import type { Rule } from 'antd/es/form';
import { CNPJ_FORMATTED_PATTERN, CNPJ_INVALID_MESSAGE, isValidCnpj } from '@/lib/utils/cnpj';

interface FormInputWithValidationProps extends Omit<FormItemProps, 'children'> {
    name: string | (string | number)[];
    inputProps?: InputProps;
    validationType?: 'email' | 'cpf' | 'cnpj' | 'phone' | 'cep' | 'url' | 'required';
    customValidation?: (value: unknown) => boolean | string;
}

export function FormInputWithValidation({
    name,
    inputProps,
    validationType,
    customValidation,
    ...formItemProps
}: FormInputWithValidationProps) {
    const getRules = (): Rule[] => {
        const rules: Rule[] = [];

        if (formItemProps.required) {
            rules.push({
                required: true,
                message: `${formItemProps.label || 'Campo'} é obrigatório`,
            });
        }

        switch (validationType) {
            case 'email':
                rules.push({ type: 'email' as const, message: 'E-mail inválido' });
                break;
            case 'cpf':
                rules.push({
                    pattern: /^\d{3}\.\d{3}\.\d{3}-\d{2}$/,
                    message: 'CPF inválido (formato: 000.000.000-00)',
                });
                break;
            case 'cnpj':
                rules.push({
                    pattern: CNPJ_FORMATTED_PATTERN,
                    message: CNPJ_INVALID_MESSAGE,
                });
                rules.push({
                    validator: (_: unknown, value: unknown) => {
                        if (value == null || value === '') {
                            return Promise.resolve();
                        }
                        if (typeof value === 'string' && isValidCnpj(value)) {
                            return Promise.resolve();
                        }
                        return Promise.reject(new Error(CNPJ_INVALID_MESSAGE));
                    },
                });
                break;
            case 'phone':
                rules.push({
                    pattern: /^\(\d{2}\)\s?\d{4,5}-?\d{4}$/,
                    message: 'Telefone inválido (formato: (00) 00000-0000)',
                });
                break;
            case 'cep':
                rules.push({
                    pattern: /^\d{5}-?\d{3}$/,
                    message: 'CEP inválido (formato: 00000-000)',
                });
                break;
            case 'url':
                rules.push({ type: 'url' as const, message: 'URL inválida' });
                break;
        }

        if (customValidation) {
            rules.push({
                validator: (_: unknown, value: unknown) => {
                    const result = customValidation(value);
                    if (result === true) {
                        return Promise.resolve();
                    }
                    return Promise.reject(
                        new Error(typeof result === 'string' ? result : 'Validação falhou')
                    );
                },
            });
        }

        return rules;
    };

    return (
        <Form.Item name={name} rules={getRules()} {...formItemProps}>
            <Input {...inputProps} />
        </Form.Item>
    );
}
