import { useEffect, useState } from 'react'
import useTaskStore from '../store/useTaskStore.js'

function TaskManager() {
  const { tasks, fetchTasks, addTask, deleteTask, updateTask } = useTaskStore()
  const [title, setTitle] = useState('')
  const [completed, setCompleted] = useState(false)
  const [id, setId] = useState('')
  const [ taskForm, setTaskForm ] = useState(false)

  useEffect(() => {
    fetchTasks()
  }, [])

  const [isUpdating, setIsUpdating] = useState(false)

  const handleUpdate = (taskId, taskTitle, taskCompleted) => {
    setIsUpdating(true)
    setTitle(taskTitle)
    setCompleted(!!taskCompleted)
    setId(taskId)
  }

  const handleSubmit = (e) => {
    e.preventDefault()

    if (isUpdating) {
      updateTask(id, title, completed)
    } else {
      addTask(title, completed)
    }

    setIsUpdating(false)
    setId('')
    setTitle('')
    setCompleted(false)
  }

  const toggleCompleted = (taskId, taskTitle, status) => {
    const nextCompleted = !status
    setCompleted(nextCompleted)
    updateTask(taskId, taskTitle, nextCompleted)

    setIsUpdating(false)
    setId('')
    setTitle('')
  }

  return (
    <div className='w-full flex flex-col items-center justify-center h-screen bg-slate-900 gap-3'>
      <h1  className={`text-2xl text-white hover:scale-102 transition duration-300 hover:text-gray-50`}>Task Manager</h1>
      <div className='w-full flex flex-col items-center gap-8'>
        <div className='w-1/3 bg-slate-900 rounded-lg p-4 flex flex-col items-center text-white shadow shadow-blue-600 gap-8'>
          <button onClick={() => setTaskForm(!taskForm)} className={`w-2/3 px-2 py-3 text-xl bg-blue-800 rounded-lg shadow-md shadow-blue-800 hover:scale-102 transition duration-300 ${taskForm ? "hidden": "visible"}`}>Create Task</button>
        <form onSubmit={handleSubmit} className={`w-full ${taskForm ? "visible": "hidden"} flex items-center justify-center content-center flex-col`}>
          <div className='p-4 flex flex-col gap-2 w-full'>
            <label className='text-white text-xl'>Title</label>
            <input
              type="text"
              name="title"
              placeholder="Title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className='w-full px-4 py-4 text-xl border-2 rounded-lg shadow-md shadow-blue-800 bg-slate-900'
            />
          </div>

          <div className='p-4 flex flex-col w-full gap-2'>
            <label className='text-white text-xl'>Completed</label>
          <select
            name="completed"
            value={String(completed)}
            onChange={(e) => setCompleted(e.target.value === 'true')}
            className='w-full px-4 py-4 text-xl border-2 rounded-lg shadow-md shadow-blue-800 bg-slate-900'
          >
            <option value={false}>Incomplete</option>
            <option value={true}>Complete</option>
          </select>
          </div>
          <div className='p-4 flex w-full gap-2'>
            <button type="button" onClick={() => setTaskForm(!taskForm)} className='w-full px-4 py-4 text-xl bg-red-800 rounded-lg shadow-md shadow-blue-800 hover:scale-102 transition duration-300'>Cancel</button>
            <button type="submit" className='w-full px-4 py-4 text-xl bg-blue-800 rounded-lg shadow-md shadow-blue-800 hover:scale-102 transition duration-300'>{!isUpdating ? 'Add Task' : 'Update Task'}</button>
          </div>
        </form>

        </div>
        <div className='w-3/4 rounded-lg px-8 py-12 flex flex-col items-center text-white shadow shadow-blue-600'>
          <table className='w-full table-fixed border-collapse text-center'>
          <thead className=''>
            <tr className='bg-slate-800'>
              <th className='px-8 py-6 text-left '>Title</th>
              <th className='px-8 py-6 text-left'>Completed</th>
              <th className='px-8 py-6 text-left '>Actions</th>
            </tr>
          </thead>
          <tbody className='w-full'>
            {tasks.length > 0 ? (
              tasks.map((task) => (
                <tr key={task._id} className='hover:bg-slate-700 p-4 bg-slate-900 hover:rounded-t-full'>
                  <td className='px-4 py-2 text-left'>{task.title}</td>
                  <td className='px-4 py-2 text-left'>
                    <input
                      type="checkbox"
                      name="completed"
                      checked={!!task.completed}
                      onChange={() => toggleCompleted(task._id, task.title, task.completed)}
                    />
                  </td>
                  <td className='px-4 py-2 text-left flex gap-4'>
                    <button className='w-full p-2 text-xl bg-red-800 rounded-lg shadow-sm shadow-blue-800 hover:scale-102 transition duration-300' onClick={() => deleteTask(task._id)}>Delete</button>
                    <button className='w-full p-2 text-xl bg-blue-800 rounded-lg shadow-sm shadow-blue-800 hover:scale-102 transition duration-300' onClick={() => handleUpdate(task._id, task.title, task.completed)}>
                      Update
                    </button>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={3}>No tasks found</td>
              </tr>
            )}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  )
}

export default TaskManager

