'use client';

import React from 'react';
import { Divider, Empty, Select, Typography } from 'antd';
import { Plus } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import type { SelectProps } from 'antd/es/select';
import styles from './SelectComParametros.module.scss';

interface SelectOption {
    label: string | React.ReactNode;
    value: string | number;
    disabled?: boolean;
}

export interface SelectComParametrosProps extends Omit<SelectProps, 'dropdownRender'> {
    /** Texto da linha fixa no topo do dropdown (ex.: "+ Novo cliente") */
    criarLabel: string;
    onCriarClick: () => void;
    options?: SelectOption[];
    placeholder?: string;
    allowClear?: boolean;
    showSearch?: boolean;
    mode?: 'multiple' | 'tags';
    dropdownRender?: (menu: React.ReactNode) => React.ReactNode;
    notFoundContent?: React.ReactNode;
    /** Falha ao carregar opções — esconde "+ criar" e desativa o select (alinhado a {@link FormSelect}). */
    fetchError?: boolean;
    fetchForbidden?: boolean;
    onRetryFetch?: () => void;
}

export function SelectComParametros({
    criarLabel,
    onCriarClick,
    options = [],
    placeholder = 'Selecione uma opção',
    allowClear = true,
    showSearch = false,
    mode,
    dropdownRender: userDropdownRender,
    notFoundContent,
    loading,
    fetchError = false,
    fetchForbidden = false,
    onRetryFetch,
    disabled: disabledProp,
    ...selectProps
}: SelectComParametrosProps) {
    const hideParametrosRow = fetchError || fetchForbidden;
    const resolvedNotFound =
        notFoundContent !== undefined
            ? notFoundContent
            : fetchError
              ? (
                    <div style={{ padding: '8px 12px' }}>
                        <Typography.Text type="danger">
                            {fetchForbidden
                                ? 'Sem permissão para consultar este catálogo.'
                                : 'Não foi possível carregar as opções.'}
                        </Typography.Text>
                        {!fetchForbidden && onRetryFetch ? (
                            <>
                                {' '}
                                <Typography.Link onClick={() => onRetryFetch()}>Tentar novamente</Typography.Link>
                            </>
                        ) : null}
                    </div>
                )
              : options.length === 0 && !loading
                ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="Nenhuma opção" />
                : undefined;

    const mergedDropdownRender = (menu: React.ReactNode) => {
        const body = userDropdownRender ? userDropdownRender(menu) : menu;

        if (hideParametrosRow) {
            return (
                <div onMouseDown={(e) => e.preventDefault()}>
                    {body}
                </div>
            );
        }

        return (
            <div onMouseDown={(e) => e.preventDefault()}>
                <div className={styles.parametrosContainer}>
                    <div
                        className={styles.parametrosRow}
                        role="button"
                        tabIndex={0}
                        onClick={() => onCriarClick()}
                        onKeyDown={(e) => {
                            if (e.key === 'Enter' || e.key === ' ') {
                                e.preventDefault();
                                onCriarClick();
                            }
                        }}
                    >
                        <Plus size={ICON_SIZE_MD} aria-hidden />
                        <span>{criarLabel}</span>
                    </div>
                    <Divider className={styles.divider} />
                </div>
                {body}
            </div>
        );
    };

    const selectDisabled = Boolean(disabledProp) || (!!fetchError && !loading);

    return (
        <Select
            placeholder={placeholder}
            allowClear={allowClear}
            showSearch={showSearch}
            mode={mode}
            loading={loading}
            disabled={selectDisabled}
            optionFilterProp={showSearch ? 'label' : undefined}
            notFoundContent={resolvedNotFound}
            dropdownRender={mergedDropdownRender}
            filterOption={
                showSearch
                    ? (input, option) =>
                          (option?.label ?? '')
                              .toString()
                              .toLowerCase()
                              .includes(input.toLowerCase())
                    : undefined
            }
            {...selectProps}
        >
            {options.map((option) => (
                <Select.Option
                    key={option.value}
                    value={option.value}
                    disabled={option.disabled}
                    label={typeof option.label === 'string' ? option.label : undefined}
                >
                    {option.label}
                </Select.Option>
            ))}
        </Select>
    );
}
