import { useState } from 'react';

interface AttachmentDropzoneProps {
  attachments: Array<{ name: string; contentBase64: string }>;
  onFilesChange: (files: Array<{ name: string; contentBase64: string }>) => void;
}

async function toBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      const result = String(reader.result ?? '');
      resolve(result.includes(',') ? result.split(',')[1]! : result);
    };
    reader.onerror = () => reject(reader.error ?? new Error('file read error'));
    reader.readAsDataURL(file);
  });
}

export function AttachmentDropzone({ attachments, onFilesChange }: AttachmentDropzoneProps) {
  const [dragOver, setDragOver] = useState(false);

  const handleFiles = async (files: FileList | null) => {
    if (!files || files.length === 0) return;
    const converted = await Promise.all(
      Array.from(files).map(async f => ({ name: f.name, contentBase64: await toBase64(f) }))
    );
    onFilesChange([...attachments, ...converted]);
  };

  return (
    <div
      className={`border-2 border-dashed rounded-xl p-4 transition-colors ${
        dragOver ? 'border-accent bg-accent-soft' : 'border-slate-200 bg-white'
      }`}
      onDragOver={e => { e.preventDefault(); setDragOver(true); }}
      onDragLeave={() => setDragOver(false)}
      onDrop={e => { e.preventDefault(); setDragOver(false); void handleFiles(e.dataTransfer.files); }}
    >
      <div className="font-bold text-[13px] text-slate-700">添付ファイル</div>
      <div className="mt-1 text-xs text-slate-400">ドラッグ&ドロップまたはファイル選択</div>
      <input
        type="file"
        multiple
        className="mt-2 text-xs"
        onChange={e => void handleFiles(e.target.files)}
      />
      {attachments.length > 0 && (
        <div className="mt-2 flex flex-wrap gap-1.5">
          {attachments.map(a => (
            <span key={a.name} className="px-2.5 py-1 bg-slate-100 rounded-full text-2xs text-slate-600">
              {a.name}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}
