'use client';
import { useState, useEffect, useRef, ChangeEvent } from 'react';
import axios from 'axios';
import Canvas from './canvas';
import { BASE_URL } from './constants';


export default function Home() {
  const [images, setImages] = useState<string[]>([]);
  const [displayImage, setDisplayImage] = useState<string>('/loading.png');
  const [displayIndex, setDisplayIndex] = useState<number>(0);

  const getAllImages = async () => {
    const res = await axios.get(`v1/get_all_images`);
    setImages(res.data.images);
  }

  const setCurrentImage = async () => {
    if (images[displayIndex] === undefined) return;
    const res = await axios.get(`v1/get_image/${images[displayIndex]}`);
    const contentType = res.headers['content-type'];
    setDisplayImage(`data:${contentType};base64,${res.data}`);
  }

  const handleFileDelete = async (imageName: string) => {
    try {
      const res = await axios.delete(`v1/delete_image/${imageName}`);
      getAllImages();
      setDisplayIndex(0);
      setDisplayImage('/loading.png');
    } catch (err) {
      console.log(err);
      alert('Error deleting image');
    }
  }

  const handleFileUpload = async (e: ChangeEvent<HTMLInputElement>) => {
    const reader = new FileReader();
    reader.addEventListener("load", async () => {
      const newImageName = `img${images.length + 1}`;
      const res = await axios.put(`v1/upload_image/${newImageName}`,
        {
          image: reader.result,
        }
      );
      setImages([...images, newImageName]);
      setDisplayIndex(images.length);
    }, false);

    if (e.target.files) {
      for (let i = 0; i < e.target.files.length; i++) {
        reader.readAsDataURL(e.target.files[i]);
      }
    }
  }

  useEffect(() => {
    getAllImages();
  }, [])

  useEffect(() => {
    setCurrentImage();
  }, [images, displayIndex])

  return (
    <>
      <Canvas imageUrl={displayImage} imageName={images[displayIndex]} />
      <br />
      <br />
      <div className="float right">
        <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-2"
          onClick={() => {
            setDisplayIndex(displayIndex - 1 >= 0 ? displayIndex - 1 : images.length - 1);
          }}>Previous</button>&nbsp;
        <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-2"
          onClick={() => {
            setDisplayIndex(displayIndex + 1 < images.length ? displayIndex + 1 : 0);
          }}>Next</button>
      </div>
      <br />
      <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-2"
        onClick={() => handleFileDelete(images[displayIndex])}>Delete Image</button>&nbsp;
      <input type="file" id="image" accept="image/png, image/jpeg" onChange={handleFileUpload} />
    </>
  )
};
