import { useState } from 'react';
import { toast } from 'sonner';
import { useClient } from 'hooks/useClient';
import type { Attachment } from './types';

type UseAttachmentsParams = {
  sessionId?: string | null;
};

export function useAttachments(params?: UseAttachmentsParams) {
  const client = useClient();
  const [attachments, setAttachments] = useState<Attachment[]>([]);

  const attachWebpage = async (url: string) => {
    const idx = attachments.length;
    setAttachments((prev) => [
      ...prev,
      { type: 'webpage', url, title: '', content: '', attachmentId: '', loading: true },
    ]);

    try {
      const res = await client.post<{ url: string; title: string; content: string; attachmentId: string }>('/scrape', {
        url,
        ...(params?.sessionId ? { sessionId: params.sessionId } : {}),
        provider: 'chat',
      });
      setAttachments((prev) =>
        prev.map((a, i) =>
          i === idx
            ? { ...a, title: res.title, content: res.content, attachmentId: res.attachmentId, loading: false }
            : a,
        ),
      );
    } catch {
      setAttachments((prev) => prev.filter((_, i) => i !== idx));
      toast.error('Failed to scrape webpage');
    }
  };

  const attachImage = async (file: File) => {
    const idx = attachments.length;
    setAttachments((prev) => [
      ...prev,
      { type: 'image', filename: file.name, dataUrl: '', attachmentId: '', loading: true },
    ]);

    try {
      const formData = new FormData();
      formData.append('file', file);
      if (params?.sessionId) formData.append('sessionId', params.sessionId);
      formData.append('provider', 'chat');

      const res = await client.post<{ filename: string; dataUrl: string; attachmentId: string }>('/upload', formData);
      setAttachments((prev) =>
        prev.map((a, i) =>
          i === idx ? { ...a, dataUrl: res.dataUrl, attachmentId: res.attachmentId, loading: false } : a,
        ),
      );
    } catch {
      setAttachments((prev) => prev.filter((_, i) => i !== idx));
      toast.error('Failed to upload image');
    }
  };

  const removeAttachment = (index: number) => {
    setAttachments((prev) => prev.filter((_, i) => i !== index));
  };

  const clearAttachments = () => {
    setAttachments([]);
  };

  const processAttachments = () => {
    let prefix = '';
    const ids: string[] = [];
    const images: { filename: string; dataUrl: string }[] = [];

    for (const a of attachments) {
      if (a.loading) continue;
      if (a.type === 'webpage' && a.content) {
        prefix = `[Attached webpage: ${a.url}]\n${a.content}\n\n${prefix}`;
      } else if (a.type === 'image' && a.dataUrl) {
        prefix = `[Attached image: ${a.filename}]\n\n${prefix}`;
        images.push({ filename: a.filename, dataUrl: a.dataUrl });
      }
      ids.push(a.attachmentId);
    }

    return { prefix, ids, images };
  };

  return {
    attachments,
    attachWebpage,
    attachImage,
    removeAttachment,
    clearAttachments,
    processAttachments,
  };
}

export type UseAttachmentsType = ReturnType<typeof useAttachments>;
