'use client';

import { useRef, useState } from 'react';
import { api } from '@/lib/api';
import { requireSelectedStore } from '@/lib/stores/store-context';
import type { MessageAttachmentUpload } from '@alqove/api-client';

interface Props {
  orderId: string;
  storeId?: string | null;
  onChange: (ids: string[]) => void;
  disabled?: boolean;
}

const MAX = 4;

export function AttachmentUploader({ orderId, storeId, onChange, disabled }: Props) {
  const [staged, setStaged] = useState<MessageAttachmentUpload[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  const handleFiles = async (fileList: FileList | null) => {
    if (!fileList) return;
    const files = Array.from(fileList);
    if (staged.length + files.length > MAX) {
      setError(`Limit ${MAX} attachments per message.`);
      return;
    }
    setError(null);
    setIsUploading(true);

    const uploaded: MessageAttachmentUpload[] = [];
    for (const file of files) {
      try {
        const endpoint = storeId !== undefined ? api.messages.forStore(requireSelectedStore(storeId)) : api.messages;
        const resp = await endpoint.uploadAttachment(orderId, file);
        uploaded.push(resp.data);
      } catch {
        setError('Upload failed. Try a smaller image (≤ 5 MB) in JPEG, PNG, or HEIC.');
      }
    }

    const next = [...staged, ...uploaded];
    setStaged(next);
    onChange(next.map((a) => a.id));
    setIsUploading(false);
    if (inputRef.current) inputRef.current.value = '';
  };

  const remove = (id: string) => {
    const next = staged.filter((a) => a.id !== id);
    setStaged(next);
    onChange(next.map((a) => a.id));
  };

  return (
    <div className="mt-2">
      {staged.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {staged.map((a) => (
            <div
              key={a.id}
              className="relative h-16 w-16 overflow-hidden rounded border border-slate-200"
            >
              <img src={a.url} alt="" className="h-full w-full object-cover" />
              <button
                type="button"
                onClick={() => remove(a.id)}
                aria-label={`Remove attachment ${a.id}`}
                className="absolute right-0 top-0 m-0.5 rounded-full bg-black/60 px-1 text-xs text-white hover:bg-black/80"
              >
                ✕
              </button>
            </div>
          ))}
        </div>
      )}

      <label className="mt-1 inline-block cursor-pointer text-xs text-forest-700 hover:underline">
        {isUploading ? 'Uploading…' : 'Attach photos'}
        <input
          ref={inputRef}
          type="file"
          accept="image/jpeg,image/png,image/heic"
          multiple
          aria-label="Attach images"
          className="hidden"
          disabled={disabled || isUploading}
          onChange={(e) => handleFiles(e.target.files)}
        />
      </label>
      {error && <p className="mt-1 text-xs text-red-600">{error}</p>}
    </div>
  );
}
