import Form, { FORM_SAMPLE_ITEMS } from './Form';

const FORM_COUNT = 5;
const FORM_SELECT_SAMPLE = FORM_SAMPLE_ITEMS.find((item) => item.type === 'select');

function cloneValue(value) {
  if (Array.isArray(value)) return value.map(cloneValue);
  if (value && typeof value === 'object') return { ...value };
  return value;
}

function buildFormItems(prefix) {
  const item = FORM_SELECT_SAMPLE || {
    id: 'region',
    label: '字段标题',
    type: 'select',
    placeholder: '请选择',
  };

  return [{
    ...item,
    id: `${prefix}-${item.id}`,
    fullWidth: true,
    value: cloneValue(item.value),
    defaultValue: cloneValue(item.defaultValue),
    options: cloneValue(item.options),
    selectOptions: cloneValue(item.selectOptions),
  }];
}

/** 自上而下：2×input、2×select、2×radio、2×checkbox、3×textarea（单 Form 内纵向） */
function buildMixedFormItems() {
  const inputTpl = FORM_SAMPLE_ITEMS.find((i) => i.type === 'input');
  const selectTpl = FORM_SAMPLE_ITEMS.find((i) => i.type === 'select');
  const radioTpl = FORM_SAMPLE_ITEMS.find((i) => i.type === 'radio');
  const checkboxTpl = FORM_SAMPLE_ITEMS.find((i) => i.type === 'checkbox');
  const textareaTpl = FORM_SAMPLE_ITEMS.find((i) => i.type === 'textarea');

  const pick = (tpl, overrides = {}) => {
    if (!tpl) return null;
    const { defaultValue: overrideDefault, id, ...rest } = overrides;
    const baseDefault = tpl.defaultValue;
    const resolvedDefault = overrideDefault !== undefined ? overrideDefault : baseDefault;
    return {
      ...tpl,
      ...rest,
      id,
      fullWidth: true,
      value: cloneValue(tpl.value),
      defaultValue: cloneValue(resolvedDefault),
      options: cloneValue(tpl.options),
      selectOptions: cloneValue(tpl.selectOptions),
    };
  };

  return [
    pick(inputTpl, { id: 'mixed-input-1' }),
    pick(inputTpl, { id: 'mixed-input-2' }),
    pick(selectTpl, { id: 'mixed-select-1' }),
    pick(selectTpl, { id: 'mixed-select-2' }),
    pick(radioTpl, { id: 'mixed-radio-1', defaultValue: 'a' }),
    pick(radioTpl, { id: 'mixed-radio-2', defaultValue: 'b' }),
    pick(checkboxTpl, { id: 'mixed-checkbox-1', defaultValue: ['a'] }),
    pick(checkboxTpl, { id: 'mixed-checkbox-2', defaultValue: ['b'] }),
    pick(textareaTpl, { id: 'mixed-textarea-1' }),
    pick(textareaTpl, { id: 'mixed-textarea-2' }),
    pick(textareaTpl, { id: 'mixed-textarea-3' }),
  ].filter(Boolean);
}

const MIXED_FORM_ITEMS = buildMixedFormItems();

/**
 * FormFieldStack — 纵向多段 Form 组合（无页级标题、无底栏、无独立卡片壳）
 *
 * - stackLayout=`select-stack`（默认）：5 个 Form，每段 1 条 select
 * - stackLayout=`mixed-fields`：1 个 Form，内含 2×input / 2×select / 2×radio / 2×checkbox / 3×textarea
 *
 * 根节点全宽，四周 p-6（24px）内边距，段与段之间 gap-6；背景与描边由宿主决定。
 */
export default function FormFieldStack({ className = '', stackLayout = 'select-stack' }) {
  if (stackLayout === 'mixed-fields') {
    return (
      <div
        className={[
          'tfds-form-field-stack box-border flex w-full min-w-0 flex-col gap-6 self-stretch p-6',
          className,
        ].filter(Boolean).join(' ')}
        data-tfds-component="FormFieldStack"
      >
        <Form
          key="mixed-form"
          className="w-full min-w-0 !items-stretch"
          items={MIXED_FORM_ITEMS}
        />
      </div>
    );
  }

  const forms = Array.from({ length: FORM_COUNT }, (_, index) => {
    const formKey = `form-section-${index + 1}`;
    const items = buildFormItems(formKey);
    return { formKey, items };
  });

  return (
    <div
      className={[
        'tfds-form-field-stack box-border flex w-full min-w-0 flex-col gap-6 self-stretch p-6',
        className,
      ].filter(Boolean).join(' ')}
      data-tfds-component="FormFieldStack"
    >
      {forms.map(({ formKey, items }) => (
        <Form
          key={formKey}
          className="w-full min-w-0 !items-stretch"
          items={items}
        />
      ))}
    </div>
  );
}
