import { useState } from 'react';
import type { PackageFormItem } from '../lib/storePackages';
import { STORE_PACKAGE_IMAGE_MAX_COUNT, STORE_PACKAGE_MAX_COUNT } from '@dukang/shared-types';
import { emptyPackage } from '../lib/storePackages';
import MultiOssUploadField from './MultiOssUploadField';

type Props = {
  items: PackageFormItem[];
  onChange: (items: PackageFormItem[]) => void;
  disabled?: boolean;
  /** 嵌入拓店流程时不重复外层卡片边距 */
  embedded?: boolean;
};

export default function StorePackagesForm({ items, onChange, disabled, embedded }: Props) {
  const [collapsed, setCollapsed] = useState<Record<number, boolean>>({});

  function updateAt(index: number, patch: Partial<PackageFormItem>) {
    const next = items.map((item, i) => (i === index ? { ...item, ...patch } : item));
    onChange(next);
  }

  function addItem() {
    if (items.length >= STORE_PACKAGE_MAX_COUNT) return;
    onChange([...items, emptyPackage(items.length)]);
  }

  function removeAt(index: number) {
    onChange(items.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i })));
    setCollapsed((prev) => {
      const next: Record<number, boolean> = {};
      Object.entries(prev).forEach(([k, v]) => {
        const i = Number(k);
        if (i < index) next[i] = v;
        else if (i > index) next[i - 1] = v;
      });
      return next;
    });
  }

  function toggleCollapse(index: number) {
    setCollapsed((prev) => ({ ...prev, [index]: !prev[index] }));
  }

  const list = items.length ? items : [emptyPackage(0)];

  return (
    <div className={`partner-packages-form${embedded ? ' partner-packages-form--embedded' : ''}`}>
      {list.map((item, index) => {
        const isCollapsed = !!collapsed[index];
        const displayName = item.name.trim() || `套餐 ${index + 1}`;
        return (
          <section
            key={index}
            className={`partner-form-card partner-packages-item${isCollapsed ? ' partner-packages-item--collapsed' : ''}`}
            style={embedded ? { marginLeft: 0, marginRight: 0 } : undefined}
          >
            <div className="partner-packages-item-head">
              <button
                type="button"
                className="partner-packages-toggle"
                onClick={() => toggleCollapse(index)}
                aria-expanded={!isCollapsed}
                aria-label={isCollapsed ? '展开套餐' : '收起套餐'}
              >
                <span className="material-symbols-outlined">
                  {isCollapsed ? 'expand_more' : 'expand_less'}
                </span>
                <span className="headline-md">{displayName}</span>
              </button>
              {!disabled && list.length > 1 ? (
                <button type="button" className="partner-packages-remove" onClick={() => removeAt(index)}>
                  删除
                </button>
              ) : null}
            </div>

            {!isCollapsed ? (
              <>
                <div className="partner-field">
                  <label>套餐名称 <span className="text-primary">*</span></label>
                  <div className="partner-field-input">
                    <span className="material-symbols-outlined">restaurant</span>
                    <input
                      placeholder="如：套餐A"
                      value={item.name}
                      disabled={disabled}
                      onChange={(e) => updateAt(index, { name: e.target.value })}
                    />
                  </div>
                </div>

                <div className="partner-field">
                  <label>价格（元） <span className="text-primary">*</span></label>
                  <div className="partner-field-input">
                    <span className="material-symbols-outlined">payments</span>
                    <input
                      type="number"
                      min={0}
                      step={0.01}
                      placeholder="198"
                      value={item.price}
                      disabled={disabled}
                      onChange={(e) => updateAt(index, { price: e.target.value })}
                    />
                  </div>
                </div>

                <div className="partner-field">
                  <label>菜品 <span className="text-primary">*</span></label>
                  <textarea
                    rows={3}
                    placeholder="红烧肉、红烧鱼、油焖茄子"
                    value={item.dishes}
                    disabled={disabled}
                    onChange={(e) => updateAt(index, { dishes: e.target.value })}
                  />
                </div>

                <div className="partner-field">
                  <label>使用时间</label>
                  <textarea
                    rows={2}
                    placeholder="节假日除外"
                    value={item.usableTime || ''}
                    disabled={disabled}
                    onChange={(e) => updateAt(index, { usableTime: e.target.value })}
                  />
                </div>

                <div className="partner-field">
                  <label>套餐图片（最多 {STORE_PACKAGE_IMAGE_MAX_COUNT} 张，支持批量）</label>
                  <MultiOssUploadField
                    bizType="STORE_PACKAGE"
                    maxCount={STORE_PACKAGE_IMAGE_MAX_COUNT}
                    disabled={disabled}
                    value={
                      Array.isArray(item.imageUrls) && item.imageUrls.length > 0
                        ? item.imageUrls.map((u) => String(u ?? '')).filter((u) => u.trim())
                        : item.imageUrl
                          ? [String(item.imageUrl)]
                          : []
                    }
                    onChange={(imageUrls) =>
                      updateAt(index, {
                        imageUrls,
                        imageUrl: imageUrls[0] ?? '',
                      })
                    }
                  />
                </div>

                <div className="partner-field">
                  <label>其他说明</label>
                  <textarea
                    rows={2}
                    placeholder="不可叠加"
                    value={item.otherNotes || ''}
                    disabled={disabled}
                    onChange={(e) => updateAt(index, { otherNotes: e.target.value })}
                  />
                </div>
              </>
            ) : null}
          </section>
        );
      })}

      {!disabled && list.length < STORE_PACKAGE_MAX_COUNT ? (
        <button type="button" className="partner-packages-add" onClick={addItem}>
          <span className="material-symbols-outlined">add_circle</span>
          添加套餐
        </button>
      ) : null}
    </div>
  );
}
