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

type Props = {
  items: PackageFormItem[];
  onChange: (items: PackageFormItem[]) => void;
  disabled?: boolean;
};

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

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

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

            {!isCollapsed ? (
              <>
                <label className="shop-packages-field">
                  <span className="shop-packages-label">套餐名称 *</span>
                  <input
                    className="shop-packages-input"
                    placeholder="如：套餐A"
                    value={item.name}
                    disabled={disabled}
                    onChange={(e) => updateAt(index, { name: e.target.value })}
                  />
                </label>

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

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

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

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

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