'use client';
/**
 * NewTaskForm — 开任务表单（屏2主体）
 * 选产品 + 今天主题 + 数量 + 双轨入口
 */
import { Product, CreateTaskRequest } from '@/types/index';
import { CountStepper } from './CountStepper';

interface NewTaskFormProps {
  products: Product[];
  selectedProduct: Product | null;
  onSelectProduct: (p: Product | null) => void;
  form: Omit<CreateTaskRequest, 'product_id'>;
  onFormChange: (patch: Partial<Omit<CreateTaskRequest, 'product_id'>>) => void;
  submitting: boolean;
  error: string;
  onSubmitAi: (e: React.FormEvent) => void;
  onSubmitImport: (e: React.FormEvent) => void;
}

export function NewTaskForm({
  products, selectedProduct, onSelectProduct,
  form, onFormChange, submitting, error,
  onSubmitAi, onSubmitImport,
}: NewTaskFormProps) {
  function adjustCount(field: 'text_count' | 'image_count', delta: number) {
    const max = field === 'image_count' ? 8 : 20;
    onFormChange({ [field]: Math.max(1, Math.min(max, form[field] + delta)) });
  }

  // 产品参考图状态：image_path 绝对路径(/app/uploads/...)取末段映射成 /uploads/... 供前端访问
  const rawPath = selectedProduct?.image_path || '';
  const hasProductImage = !!rawPath;
  const imgSrc = rawPath
    ? '/uploads/' + rawPath.replace(/^.*\/uploads\//, '').replace(/^uploads\//, '')
    : '';
  // 禁降级：产品入镜但无图 → 主轨按钮禁用
  const blockedByNoImage = form.need_product_image && !hasProductImage;

  return (
    <form className="space-y-6 max-w-xl" noValidate>
      {/* 选产品 */}
      <div>
        <label htmlFor="product-select" className="block text-sm font-medium text-text-primary mb-2">
          选产品
        </label>
        <select id="product-select"
          value={selectedProduct?.id ?? ''}
          onChange={(e) => onSelectProduct(products.find((p) => p.id === Number(e.target.value)) ?? null)}
          className="w-full border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange"
          aria-required="true"
        >
          {products.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
        </select>
      </div>

      {/* 产品入镜开关 + 参考图状态 */}
      <div className="bg-surface-secondary rounded-lg p-4 space-y-3">
        <label className="flex items-center gap-2 cursor-pointer">
          <input type="checkbox" checked={form.need_product_image}
            onChange={(e) => onFormChange({ need_product_image: e.target.checked })}
            className="w-4 h-4 accent-brand-orange"
            aria-label="本次产品是否入镜" />
          <span className="text-sm font-medium text-text-primary">产品入镜（带真品图生图，过抽检）</span>
        </label>
        {form.need_product_image && (
          hasProductImage ? (
            <div className="flex items-center gap-2 text-xs text-status-success">
              <img src={imgSrc} alt="产品参考图" className="w-12 h-12 rounded object-cover border border-border-default" />
              <span>✓ 已上传参考图，生图将带产品入镜</span>
            </div>
          ) : (
            <div className="text-xs text-status-error bg-red-50 rounded px-3 py-2" role="alert">
              ⚠ 该产品未上传参考图。请先到「配置-产品库」上传，或取消勾选「产品入镜」改用纯文生图。
            </div>
          )
        )}
      </div>

      {/* 今天主题（关键字段） */}
      <div>
        <label htmlFor="theme-input" className="block text-sm font-medium text-text-primary mb-2">
          今天主题
        </label>
        <input id="theme-input" type="text"
          value={form.theme}
          onChange={(e) => onFormChange({ theme: e.target.value })}
          placeholder="如：黄皮提亮·早八伪素颜"
          maxLength={100}
          className="w-full border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange"
          aria-required="true"
        />
        <p className="text-xs text-text-tertiary mt-1">{form.theme.length}/100</p>
      </div>

      {/* 数量设定（不写死） */}
      <div className="flex gap-6">
        <CountStepper label="生几条文案" value={form.text_count}
          onInc={() => adjustCount('text_count', 1)} onDec={() => adjustCount('text_count', -1)} />
        <CountStepper label="生几批图" value={form.image_count}
          onInc={() => adjustCount('image_count', 1)} onDec={() => adjustCount('image_count', -1)} />
      </div>

      {error && (
        <div role="alert" className="text-status-error text-sm bg-red-50 px-3 py-2 rounded-lg">
          {error}
        </div>
      )}

      {/* 双轨入口 */}
      <div className="flex gap-3">
        <button type="submit" disabled={submitting || blockedByNoImage} onClick={onSubmitAi}
          aria-label="轨A：批量生成文案"
          title={blockedByNoImage ? '该产品未上传参考图，请先上传或关闭产品入镜' : ''}
          className="flex-1 bg-brand-orange text-white rounded-lg py-2.5 text-sm font-medium hover:bg-orange-600 disabled:opacity-50">
          {submitting ? '生成中…' : '开始批量生文 →'}
        </button>
        <button type="button" disabled={submitting} onClick={onSubmitImport}
          aria-label="轨B：导入外部文案"
          className="px-4 py-2.5 text-sm text-text-secondary border border-border-default rounded-lg hover:bg-surface-tertiary disabled:opacity-50">
          导入外部文案
        </button>
      </div>
    </form>
  );
}
