// React Imports
import { useState, useEffect } from 'react'

// MUI Imports
import Button from '@mui/material/Button'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'

// Third-party Imports
import { useForm, Controller } from 'react-hook-form'

// Type Imports
import type { TodoType, TodoStatusType, TodoPriorityType } from '@/types/apps/todoTypes'

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import AppReactDatepicker from '@/libs/styles/AppReactDatepicker'

// API Imports
import { todoService } from '@/libs/api'

type Props = {
  open: boolean
  handleClose: () => void
  todoData?: TodoType[]
  setData: (data: TodoType[]) => void
  editTodo?: TodoType | null
  setEditTodo: (todo: TodoType | null) => void
}

type FormValidateType = {
  title: string
  description: string
  status: TodoStatusType
  priority: TodoPriorityType
  dueDate: Date | null
}

const AddEditTodoDrawer = (props: Props) => {
  // Props
  const { open, handleClose, todoData, setData, editTodo, setEditTodo } = props

  // States
  const [dueDate, setDueDate] = useState<Date | null>(null)

  // Hooks
  const {
    control,
    reset: resetForm,
    handleSubmit,
    formState: { errors },
    setValue
  } = useForm<FormValidateType>({
    defaultValues: {
      title: '',
      description: '',
      status: 'pending',
      priority: 'medium',
      dueDate: null
    }
  })

  // Reset form when editTodo changes
  useEffect(() => {
    if (editTodo) {
      setValue('title', editTodo.title)
      setValue('description', editTodo.description)
      setValue('status', editTodo.status)
      setValue('priority', editTodo.priority)
      setDueDate(editTodo.dueDate ? new Date(editTodo.dueDate) : null)
      setValue('dueDate', editTodo.dueDate ? new Date(editTodo.dueDate) : null)
    } else {
      resetForm({
        title: '',
        description: '',
        status: 'pending',
        priority: 'medium',
        dueDate: null
      })
      setDueDate(null)
    }
  }, [editTodo, setValue, resetForm])

  const onSubmit = async (data: FormValidateType) => {
    try {
      const dueDateString = data.dueDate ? data.dueDate.toISOString() : undefined

      if (editTodo) {
        // Update existing todo using API
        const updatedTodo = await todoService.updateTodo(editTodo.id, {
          title: data.title,
          description: data.description,
          status: data.status,
          priority: data.priority,
          dueDate: dueDateString
        })
        const updatedTodos = todoData?.map(todo =>
          todo.id === editTodo.id ? updatedTodo : todo
        )
        setData(updatedTodos || [])
      } else {
        // Add new todo using API
        const newTodo = await todoService.createTodo({
          title: data.title,
          description: data.description,
          status: data.status,
          priority: data.priority,
          dueDate: dueDateString,
          routine: 0 // NONE
        })
        
        // Update state with the todo returned from API
        setData([...(todoData ?? []), newTodo])
      }

      handleClose()
      setEditTodo(null)
      setDueDate(null)
      resetForm({
        title: '',
        description: '',
        status: 'pending',
        priority: 'medium',
        dueDate: null
      })
    } catch (error) {
      console.error('Error saving todo:', error)
      // TODO: Show error message to user (e.g., using a toast notification)
    }
  }

  const handleReset = () => {
    handleClose()
    setEditTodo(null)
    setDueDate(null)
    resetForm({
      title: '',
      description: '',
      status: 'pending',
      priority: 'medium',
      dueDate: null
    })
  }

  return (
    <Drawer
      open={open}
      anchor='right'
      variant='temporary'
      onClose={handleReset}
      ModalProps={{ keepMounted: true }}
      sx={{ '& .MuiDrawer-paper': { width: { xs: 300, sm: 400 } } }}
    >
      <div className='flex items-center justify-between plb-5 pli-6'>
        <Typography variant='h5'>{editTodo ? 'Edit Todo' : 'Add New Todo'}</Typography>
        <IconButton size='small' onClick={handleReset}>
          <i className='tabler-x text-2xl text-textPrimary' />
        </IconButton>
      </div>
      <Divider />
      <div>
        <form onSubmit={handleSubmit(data => onSubmit(data))} className='flex flex-col gap-6 p-6'>
          <Controller
            name='title'
            control={control}
            rules={{ required: true }}
            render={({ field }) => (
              <CustomTextField
                {...field}
                fullWidth
                label='Title'
                placeholder='Enter todo title'
                {...(errors.title && { error: true, helperText: 'This field is required.' })}
              />
            )}
          />
          <Controller
            name='description'
            control={control}
            render={({ field }) => (
              <CustomTextField
                {...field}
                fullWidth
                multiline
                rows={4}
                label='Description'
                placeholder='Enter todo description (optional)'
              />
            )}
          />
          <Controller
            name='status'
            control={control}
            rules={{ required: true }}
            render={({ field }) => (
              <CustomTextField
                select
                fullWidth
                id='select-status'
                label='Select Status'
                {...field}
                {...(errors.status && { error: true, helperText: 'This field is required.' })}
              >
                <MenuItem value='pending'>Pending</MenuItem>
                <MenuItem value='in-progress'>In Progress</MenuItem>
                <MenuItem value='completed'>Completed</MenuItem>
              </CustomTextField>
            )}
          />
          <Controller
            name='priority'
            control={control}
            rules={{ required: true }}
            render={({ field }) => (
              <CustomTextField
                select
                fullWidth
                id='select-priority'
                label='Select Priority'
                {...field}
                {...(errors.priority && { error: true, helperText: 'This field is required.' })}
              >
                <MenuItem value='high'>High</MenuItem>
                <MenuItem value='medium'>Medium</MenuItem>
                <MenuItem value='low'>Low</MenuItem>
              </CustomTextField>
            )}
          />
          <AppReactDatepicker
            selected={dueDate}
            id='due-date'
            onChange={(date: Date | null) => {
              setDueDate(date)
              setValue('dueDate', date)
            }}
            placeholderText='Select due date (optional)'
            dateFormat='yyyy-MM-dd'
            customInput={<CustomTextField label='Due Date' fullWidth />}
          />
          <div className='flex items-center gap-4'>
            <Button variant='contained' type='submit'>
              {editTodo ? 'Update' : 'Submit'}
            </Button>
            <Button variant='tonal' color='error' type='reset' onClick={() => handleReset()}>
              Cancel
            </Button>
          </div>
        </form>
      </div>
    </Drawer>
  )
}

export default AddEditTodoDrawer


