'use client'

import { useEffect } from 'react'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'
import Grid from '@mui/material/Grid2'
import { Controller, useForm } from 'react-hook-form'
import { useTranslations } from 'next-intl'
import { toast } from 'react-toastify'

import CustomTextField from '@core/components/mui/TextField'
import type { ICreateTable, ITable, IUpdateTable } from '@/types/data/table'
import { useCreateTable, useUpdateTable } from '@/@core/hooks/data/table'
import Button from '@/@core/components/mui/Button'

type Props = {
  mode: 'create' | 'edit'
  open: boolean
  initialTable?: ITable | null
  onClose: () => void
  onSuccess?: () => void
}

const defaultValues: ICreateTable = {
  table_number: '',
  capacity: 4,
  location: '',
  is_active: true
}

const TableFormDrawer = ({ mode, open, onClose, onSuccess, initialTable }: Props) => {
  const t = useTranslations('tables.form')
  const createTable = useCreateTable()
  const updateTable = useUpdateTable()

  const { control, handleSubmit, reset } = useForm<ICreateTable>({ defaultValues })

  useEffect(() => {
    if (!open) {
      return
    }

    if (mode === 'edit' && initialTable) {
      reset({
        table_number: initialTable.table_number || '',
        capacity: initialTable.capacity || 0,
        location: initialTable.location || '',
        is_active: Boolean(initialTable.is_active)
      })
    } else {
      reset(defaultValues)
    }
  }, [open, mode, initialTable, reset])

  const loading = createTable.isPending || updateTable.isPending
  const drawerTitle = mode === 'create' ? t('createTitle') : t('editTitle')
  const ctaLabel = mode === 'create' ? t('createAction') : t('saveAction')

  const onSubmit = async (values: ICreateTable) => {
    const payload: ICreateTable | IUpdateTable = {
      table_number: values.table_number.trim(),
      capacity: Number(values.capacity) || 0,
      location: values.location.trim(),
      is_active: Boolean(values.is_active)
    }

    try {
      if (mode === 'create') {
        await createTable.mutateAsync(payload)
      } else if (initialTable) {
        await updateTable.mutateAsync({ tableId: initialTable.id, payload })
      }

      onSuccess?.()
      onClose()
    } catch (error) {
      console.error('Failed to submit table form', error)
      toast.error(t('error'))
    }
  }

  return (
    <Drawer
      anchor='right'
      open={open}
      onClose={() => {
        if (!loading) {
          onClose()
        }
      }}
      sx={{ '& .MuiDrawer-paper': { width: { xs: 340, sm: 420 }, p: 4 } }}
    >
      <div className='flex items-center justify-between'>
        <div>
          <Typography variant='h6'>{drawerTitle}</Typography>
          <Typography variant='body2' color='text.secondary'>
            {mode === 'create' ? t('createSubtitle') : t('editSubtitle')}
          </Typography>
        </div>

        <IconButton onClick={onClose}>
          <i className='tabler-x text-textSecondary' />
        </IconButton>
      </div>

      <Divider sx={{ my: 4 }} />

      <form onSubmit={handleSubmit(onSubmit)} className='flex flex-col gap-4'>
        <Controller
          name='table_number'
          control={control}
          rules={{ required: true }}
          render={({ field }) => <CustomTextField {...field} label={t('tableNumber')} placeholder='T-01' fullWidth />}
        />

        <Grid container spacing={3}>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='capacity'
              control={control}
              rules={{ required: true, min: 1 }}
              render={({ field }) => (
                <CustomTextField {...field} label={t('capacity')} type='number' inputProps={{ min: 1 }} fullWidth />
              )}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='location'
              control={control}
              render={({ field }) => (
                <CustomTextField {...field} label={t('location')} placeholder='Main hall' fullWidth />
              )}
            />
          </Grid>
        </Grid>

        <Controller
          name='is_active'
          control={control}
          render={({ field }) => (
            <FormControlLabel
              control={
                <Switch
                  {...field}
                  checked={field.value}
                  onChange={(_, checked) => field.onChange(checked)}
                  color='primary'
                />
              }
              label={field.value ? t('active') : t('inactive')}
            />
          )}
        />

        <div className='flex items-center justify-end gap-3 pt-2'>
          <Button variant='tonal' color='secondary' onClick={onClose} disabled={loading}>
            {t('cancel')}
          </Button>
          <Button variant='contained' type='submit' disabled={loading} isLoading={loading}>
            {loading ? t('saving') : ctaLabel}
          </Button>
        </div>
      </form>
    </Drawer>
  )
}

export default TableFormDrawer
