import { useState, useCallback } from 'react';
import { toBlob } from 'html-to-image';
import { useClient } from 'hooks/useClient';
import { useAuth } from 'hooks/useAuth';
import { useGlobal } from 'hooks/useGlobal';
import type { ErrorDetails } from 'hooks/useClient';
import { getConsoleBuffer } from '@/lib/console-buffer';
import { toast } from 'sonner';

export const useBugReport = () => {
  const [open, setOpen] = useState(false);
  const [screenshot, setScreenshot] = useState<Blob | null>(null);
  const [capturing, setCapturing] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const client = useClient();
  const { user } = useAuth();
  const [apiError] = useGlobal<ErrorDetails | null>('API_ERROR', null);

  const handleOpen = useCallback(async () => {
    setCapturing(true);
    try {
      const blob = await toBlob(document.body, { pixelRatio: 0.75 });
      setScreenshot(blob);
    } catch (err) {
      console.error('Screenshot capture failed:', err);
    } finally {
      setCapturing(false);
      setOpen(true);
    }
  }, []);

  const handleClose = useCallback(() => {
    setOpen(false);
    setScreenshot(null);
    setCapturing(false);
  }, []);

  const handleSubmit = useCallback(
    async (description: string) => {
      setSubmitting(true);
      try {
        const context = {
          url: window.location.href,
          userAgent: navigator.userAgent,
          viewport: { width: window.innerWidth, height: window.innerHeight },
          timestamp: new Date().toISOString(),
          consoleLogs: getConsoleBuffer(),
          apiError,
          user: user ? { id: user.id, email: user.email, name: user.name } : null,
        };

        const formData = new FormData();
        formData.append('description', description);
        formData.append('context', JSON.stringify(context));
        if (screenshot) {
          formData.append('screenshot', screenshot, 'screenshot.png');
        }

        await client.post('/bug-report', formData);
        toast.success('Bug report submitted');
        handleClose();
      } catch {
        toast.error('Failed to submit bug report');
      } finally {
        setSubmitting(false);
      }
    },
    [screenshot, client, user, apiError, handleClose],
  );

  return { open, capturing, submitting, screenshot, handleOpen, handleClose, handleSubmit };
};
