import React, { useState } from 'react'
import { CreatePost, GenerateAIImage } from '../api';
import { useNavigate } from 'react-router-dom'

const GenerateForm = ({post, setPost, postLoading, setPostLoading, imgLoading, setImgLoading}) => {
  const [error, setError] = useState("");
  const route = useNavigate()

  const generateImageFunction = async () => {
    setImgLoading(true);
    await GenerateAIImage({prompt: post.prompt}).then((res) => {
      setPost({...post, photo: `data: image/jpge;base64,${res?.data?.photo}`})
      setImgLoading(false)
    }).catch((error) => {
      setError(error?.response?.data?.message)
      setImgLoading(false)
      console.log(error)
    })
  }
  const creatPostFunction = async () => {
    setPostLoading(true)
    await CreatePost(post).then((res) => {
      setPostLoading(false);
      route('/');
      
    }).catch((error) => {
      setError(error?.response?.data?.message)
      setPostLoading(false)
    })
  }

  return (
    <div className='flex-1 flex flex-col gap-5 p-2 justify-center'>
        <div className='flex flex-col gap-1'>
            <p className='text-lg text-green-400 font-semibold'>Generate an image with your prompt</p>
        </div>
        <div className='flex flex-col gap-5 text-sm text-gray-200'>
            <p className='-mb-4 uppercase text-xs'>Author</p>
            <input placeholder='Enter your name' value={post.name} onChange={(e) => setPost({...post, name: e.target.value})} className='bg-transparent border rounded-sm p-2 outline-none'/>
            <p className='-mb-4 uppercase text-xs'>Prompt</p>
            <textarea placeholder='Enter your prompt' value={post.prompt} onChange={(e) => setPost({...post, prompt: e.target.value})} className='min-h-[100px] bg-transparent border rounded-sm p-2 outline-none resize-none'/>
          {
            error && <div className='text-red-500'>{error}</div>
          }
        </div>
        <div className='flex-1 flex gap-2 mt-5'>
            <button onClick={() => generateImageFunction()} onLoad={() => imgLoading()} disabled={post.prompt === ""} className='w-full h-[40px] flex items-center justify-center rounded-md p-1 bg-[#FFC100] disabled:bg-opacity-70'>Generate</button>
            <button onClick={() => creatPostFunction()} onLoad={() => postLoading()} disabled={post.name === "" || post.prompt === "" || post.photo === ""} className='w-full h-[40px] flex items-center justify-center rounded-md p-1 bg-[#FF8A08] disabled:bg-opacity-70'>Post</button>
        </div>
    </div>
  )
}

export default GenerateForm