import { useState, useRef } from 'react';
import { Upload, Trash2, ImageIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { api } from '@/lib/api';
import type { Account, ReferenceItem } from '@/types';

interface Props {
  account: Account;
  onSave: (data: Partial<Account>) => void;
}

export function AccountReferencesTab({ account, onSave }: Props) {
  const refs = account.references || [];
  const [uploading, setUploading] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      await fetch(`/api/accounts/${account.id}/references/upload`, {
        method: 'POST',
        body: formData,
      });
      // Reload account to get updated references
      const updated = await api.getAccount(account.id);
      onSave({ references: updated.references });
    } catch (err) {
      alert('上传失败: ' + (err as Error).message);
    }
    setUploading(false);
    if (fileRef.current) fileRef.current.value = '';
  };

  const handleDelete = async (index: number) => {
    if (!confirm('确定删除这张参考图？')) return;
    try {
      await fetch(`/api/accounts/${account.id}/references/${index}`, { method: 'DELETE' });
      const updated = await api.getAccount(account.id);
      onSave({ references: updated.references });
    } catch (err) {
      alert('删除失败: ' + (err as Error).message);
    }
  };

  return (
    <div className="max-w-lg space-y-4">
      {/* Upload */}
      <div className="flex items-center gap-3">
        <input ref={fileRef} type="file" accept="image/*" onChange={handleUpload} className="hidden" />
        <Button variant="outline" size="sm" onClick={() => fileRef.current?.click()} disabled={uploading}>
          <Upload size={14} className="mr-1" />
          {uploading ? '上传中...' : '添加参考图'}
        </Button>
        <span className="text-xs text-zinc-400">{refs.length} 张参考图</span>
      </div>

      {/* Reference grid */}
      {refs.length > 0 ? (
        <div className="grid grid-cols-4 gap-2">
          {refs.map((ref, i) => (
            <div key={i} className="group relative aspect-square bg-zinc-100 rounded-lg overflow-hidden border border-zinc-200">
              {ref.file ? (
                <img src={`/api/accounts/${account.id}/references/${encodeURIComponent(ref.file.split('/').pop() || '')}`} alt="" className="w-full h-full object-cover" />
              ) : ref.url ? (
                <img src={ref.url} alt="" className="w-full h-full object-cover" />
              ) : (
                <div className="w-full h-full flex items-center justify-center">
                  <ImageIcon size={20} className="text-zinc-400" />
                </div>
              )}
              <button
                onClick={() => handleDelete(i)}
                className="absolute top-1 right-1 p-1 rounded bg-white/80 opacity-0 group-hover:opacity-100 transition-opacity shadow-sm"
              >
                <Trash2 size={11} className="text-red-500" />
              </button>
              <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/30 to-transparent p-1">
                <span className="text-[9px] text-white truncate block">{ref.file}</span>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-center py-8 text-zinc-400">
          <ImageIcon size={28} className="mx-auto mb-2 opacity-40" />
          <p className="text-xs">暂无参考图</p>
          <p className="text-[10px] mt-1">点击上方按钮上传参考图</p>
        </div>
      )}

      {/* Styles section */}
      {account.styles && Object.keys(account.styles).length > 0 && (
        <div className="mt-4">
          <h4 className="text-xs font-semibold text-zinc-600 mb-2">风格预设</h4>
          <div className="space-y-1">
            {Object.entries(account.styles).map(([name, style]) => (
              <div key={name} className="flex items-center justify-between px-3 py-2 bg-zinc-50 rounded-lg text-xs">
                <span className="font-medium text-zinc-700">{name}</span>
                <span className="text-zinc-400">{style.references?.length || 0} 张</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
