'use client';
/**
 * ProductCard + ProductForm + ProductsSkeleton + ProductImageUpload — 产品档案子组件
 */
import { useRef, useState } from 'react';
import { api } from '@/lib/api';
import { Product, CreateProductRequest } from '@/types/index';

// --- ProductImageUpload ---
export function ProductImageUpload({
  product,
  onUploaded,
}: {
  product: Product;
  onUploaded: (updated: Product) => void;
}) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState('');

  async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 10 * 1024 * 1024) { setError('文件超过 10 MB'); return; }
    setError('');
    setUploading(true);
    try {
      const form = new FormData();
      form.append('file', file);
      const updated = await api.postForm<Product>(
        `/api/v1/products/${product.id}/upload-image`, form
      );
      onUploaded(updated);
    } catch {
      setError('上传失败，请重试');
    } finally {
      setUploading(false);
      if (inputRef.current) inputRef.current.value = '';
    }
  }

  return (
    <div className="mt-2">
      {product.image_path ? (
        <div className="flex items-center gap-2">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={`/uploads/${product.image_path.replace(/^.*\/uploads\//, '').replace(/^uploads\//, '')}`}
            alt={`${product.name}参考图`}
            className="h-12 w-12 object-cover rounded border border-border-default"
          />
          <button
            type="button"
            onClick={() => inputRef.current?.click()}
            className="text-xs text-brand-orange hover:underline"
          >
            换图
          </button>
        </div>
      ) : (
        <button
          type="button"
          onClick={() => inputRef.current?.click()}
          disabled={uploading}
          className="text-xs border border-dashed border-border-default rounded px-3 py-1
                     text-text-secondary hover:border-brand-orange hover:text-brand-orange
                     disabled:opacity-50 transition-colors"
        >
          {uploading ? '上传中…' : '+ 上传产品参考图'}
        </button>
      )}
      {error && <p className="text-xs text-red-500 mt-1">{error}</p>}
      <input
        ref={inputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        className="hidden"
        aria-label="选择产品参考图"
        onChange={handleFile}
      />
    </div>
  );
}

export function ProductCard({ product, onUpdated }: { product: Product; onUpdated: () => void }) {
  const [current, setCurrent] = useState<Product>(product);

  return (
    <div className="border border-border-default rounded-xl p-4 bg-surface-primary space-y-2">
      <div className="flex items-center justify-between">
        <h3 className="font-medium text-text-primary">{current.name}</h3>
        <span className="text-xs text-text-tertiary bg-surface-tertiary px-2 py-0.5 rounded-full">
          {current.category}
        </span>
      </div>
      <p className="text-xs text-text-secondary line-clamp-2">
        {current.selling_points.join(' · ')}
      </p>
      <div className="flex flex-wrap gap-1">
        {current.text_angles.slice(0, 3).map((a) => (
          <span key={a} className="text-xs bg-brand-cream px-2 py-0.5 rounded-full text-text-secondary">
            {a}
          </span>
        ))}
      </div>
      <ProductImageUpload
        product={current}
        onUploaded={(updated) => { setCurrent(updated); onUpdated(); }}
      />
    </div>
  );
}

export function ProductForm({ onSaved, onCancel }: { onSaved: () => void; onCancel: () => void }) {
  const [form, setForm] = useState<CreateProductRequest>({
    name: '', category: '', source: 'custom',
    selling_points: [], style_tone: '', text_angles: [],
    custom_prompt: null, banned_word_ids: [],
  });
  const [saving, setSaving] = useState(false);

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    if (!form.name) return;
    setSaving(true);
    try {
      await api.post('/api/v1/products', form);
      onSaved();
    } finally {
      setSaving(false);
    }
  }

  return (
    <form onSubmit={handleSave}
      className="border border-border-default rounded-xl p-6 bg-surface-primary space-y-4">
      <h3 className="font-medium text-text-primary">新增产品</h3>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label htmlFor="prod-name" className="block text-sm font-medium mb-1">产品名称</label>
          <input id="prod-name" value={form.name}
            onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
            className="w-full border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange"
            required aria-required="true"
          />
        </div>
        <div>
          <label htmlFor="prod-category" className="block text-sm font-medium mb-1">品类</label>
          <input id="prod-category" value={form.category}
            onChange={(e) => setForm((f) => ({ ...f, category: e.target.value }))}
            className="w-full border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange"
          />
        </div>
      </div>
      <div className="flex gap-3 justify-end">
        <button type="button" onClick={onCancel}
          className="px-4 py-2 text-sm text-text-secondary border border-border-default rounded-lg hover:bg-surface-tertiary">
          取消
        </button>
        <button type="submit" disabled={saving}
          className="px-4 py-2 text-sm bg-brand-orange text-white rounded-lg hover:bg-orange-600 disabled:opacity-50">
          {saving ? '保存中…' : '保存'}
        </button>
      </div>
    </form>
  );
}

export function ProductsSkeleton() {
  return (
    <div className="grid grid-cols-3 gap-4" aria-busy="true" aria-label="加载产品档案中">
      {[1, 2, 3].map((i) => (
        <div key={i} className="border border-border-default rounded-xl p-4 animate-pulse space-y-2">
          <div className="h-4 bg-surface-tertiary rounded w-1/2" />
          <div className="h-3 bg-surface-tertiary rounded w-full" />
          <div className="h-3 bg-surface-tertiary rounded w-3/4" />
        </div>
      ))}
    </div>
  );
}
