'use client';

import { useState } from 'react';
import { Paperclip, X, Loader2 } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { adminApiUploadFile } from '@/lib/api';
import { useToast } from '@/lib/toast';

export type Attachment = { filename: string; url: string; storedPath: string };

export default function AttachmentPicker({
  attachments, onChange,
}: { attachments: Attachment[]; onChange: (a: Attachment[]) => void }) {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [uploading, setUploading] = useState(false);

  async function handleFiles(files: FileList | null) {
    if (!files || !accessToken || !appSecretProof) return;
    setUploading(true);
    try {
      const uploaded: Attachment[] = [];
      for (const file of Array.from(files)) {
        const result = await adminApiUploadFile('/admin/attachments/upload', accessToken, appSecretProof, file, 'file');
        uploaded.push({ filename: result.filename || file.name, url: result.url, storedPath: result.storedPath || '' });
      }
      onChange([...attachments, ...uploaded]);
    } catch {
      show('error', 'One or more files could not be uploaded — allowed types: PDF, Word, Excel, PowerPoint, text/CSV, images, up to 10MB each.');
    } finally {
      setUploading(false);
    }
  }

  function remove(url: string) {
    onChange(attachments.filter((a) => a.url !== url));
  }

  return (
    <div>
      <label className="text-xs font-medium text-gray-600 flex items-center gap-1">
        <Paperclip size={12} /> Attachments
      </label>
      <div className="mt-1 flex flex-wrap gap-1.5">
        {attachments.map((a) => (
          <span key={a.url} className="inline-flex items-center gap-1 bg-brand-bg border border-brand-border rounded-full px-2 py-1 text-[11px] animate-scaleIn">
            {a.filename}
            <button type="button" onClick={() => remove(a.url)} className="text-gray-400 transition-colors hover:text-brand-red"><X size={11} /></button>
          </span>
        ))}
        <label className="inline-flex items-center gap-1 border border-dashed border-brand-border rounded-full px-2 py-1 text-[11px] cursor-pointer transition-colors hover:bg-brand-bg">
          {uploading ? <Loader2 size={11} className="animate-spin" /> : <Paperclip size={11} />}
          {uploading ? 'Uploading…' : 'Add file'}
          <input type="file" multiple className="hidden" disabled={uploading}
            accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv,.png,.jpg,.jpeg,.webp"
            onChange={(e) => { handleFiles(e.target.files); e.target.value = ''; }} />
        </label>
      </div>
    </div>
  );
}
