'use client';

import React, { useState } from 'react';
import useImageUpload from '../../lib/hooks/useImageUpload';
import { cn, fetcher } from '@/lib/utils';
import { ChatEntity, MessageBase } from '@/lib/types';
import { useRouter } from 'next/navigation';
import Loading from '../ui/Loading';

export interface ImageSelectorProps {}

type Example = {
  url: string;
  initMessages: MessageBase[];
};

const ImageSelector: React.FC<ImageSelectorProps> = () => {
  const router = useRouter();
  const [isUploading, setUploading] = useState(false);
  const { getRootProps, getInputProps, isDragActive } = useImageUpload(
    undefined,
    async files => {
      const formData = new FormData();
      if (files.length !== 1) {
        throw new Error('Only one image can be uploaded at a time');
      }
      setUploading(true);
      const reader = new FileReader();
      reader.readAsDataURL(files[0]);
      reader.onload = async () => {
        const resp = await fetcher<ChatEntity>('/api/upload', {
          method: 'POST',
          body: JSON.stringify({
            base64: reader.result as string,
            fileType: files[0].type,
          }),
        });
        setUploading(false);
        if (resp) {
          router.push(`/chat/${resp.id}`);
        }
      };
    },
  );
  return (
    <div
      {...getRootProps()}
      className={cn(
        'dropzone border-2 border-dashed border-gray-400 w-full h-64 flex items-center justify-center rounded-lg mt-4 cursor-pointer',
        isDragActive && 'bg-gray-500/50 border-solid',
      )}
    >
      <input {...getInputProps()} />
      <div className="text-gray-400 text-lg">
        {isUploading ? (
          <Loading />
        ) : (
          'Drag or drop image here, or click to select images'
        )}
      </div>
    </div>
  );
};

export default ImageSelector;
