'use client'

// React Imports
import { useState } from 'react'
import type { Theme } from '@mui/material/styles'
import { useTranslations } from 'next-intl'

// Hook Imports
import { useSensorHub } from '@/hooks/useSensorHub'

// API Imports
import type { Sensor } from '@/libs/api/services/sensorHubService'
import Dialog from '@mui/material/Dialog'
import DialogContent from '@mui/material/DialogContent'
import DialogTitle from '@mui/material/DialogTitle'
import Drawer from '@mui/material/Drawer'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import useMediaQuery from '@mui/material/useMediaQuery'
import Fade from '@mui/material/Fade'

// Component Imports
import OptionSensorHub from './OptionSensorHub'
import FormSensorHub from './FormSensorHub'

type TableModalSheetProps = {
  open: boolean
  onClose: () => void
}

const backdropBlurSx = { backdropFilter: 'blur(4px)' }
const transitionTimeout = { enter: 300, exit: 200 }

const DialogContentWithTransition = ({
  showAddForm,
  onShowAddForm,
  onBack,
  onConfirm,
  selectSensor,
  selectSensorDescription,
  addSensor
}: {
  showAddForm: boolean
  onShowAddForm: () => void
  onBack: () => void
  onConfirm: (sensor: Sensor) => void
  selectSensor: string
  selectSensorDescription: string
  addSensor: string
}) => (
  <Fade key={showAddForm ? 'form' : 'options'} in timeout={transitionTimeout}>
    <div>
      {showAddForm ? (
        <FormSensorHub onBack={onBack} />
      ) : (
        <div className='flex flex-col gap-4'>
          <div className='grid grid-cols-[1fr_auto] items-center gap-4'>
            <div className='flex flex-col gap-0.5'>
              <Typography variant='h6' fontWeight={600}>
                {selectSensor}
              </Typography>
              <Typography variant='body2' color='text.secondary' sx={{ lineHeight: 1.5 }}>
                {selectSensorDescription}
              </Typography>
            </div>
            <Button
              variant='contained'
              color='primary'
              startIcon={<i className='tabler-plus text-xl' />}
              onClick={onShowAddForm}
            >
              {addSensor}
            </Button>
          </div>
          <OptionSensorHub onConfirm={onConfirm} />
        </div>
      )}
    </div>
  </Fade>
)

const DrawerContentWithTransition = ({
  showAddForm,
  onShowAddForm,
  onBack,
  onConfirm,
  selectSensor,
  selectSensorDescription,
  addSensor
}: {
  showAddForm: boolean
  onShowAddForm: () => void
  onBack: () => void
  onConfirm: (sensor: Sensor) => void
  selectSensor: string
  selectSensorDescription: string
  addSensor: string
}) => (
  <Fade key={showAddForm ? 'form' : 'options'} in timeout={transitionTimeout}>
    <div>
      {showAddForm ? (
        <FormSensorHub onBack={onBack} />
      ) : (
        <div className='flex flex-col gap-4'>
          <div className='grid grid-cols-[1fr_auto] items-center gap-4'>
            <div className='flex flex-col gap-0.5'>
              <Typography variant='h6' fontWeight={600}>
                {selectSensor}
              </Typography>
              <Typography variant='body2' color='text.secondary' sx={{ lineHeight: 1.5 }}>
                {selectSensorDescription}
              </Typography>
            </div>
            <Button
              variant='contained'
              color='primary'
              startIcon={<i className='tabler-plus text-xl' />}
              onClick={onShowAddForm}
            >
              {addSensor}
            </Button>
          </div>
          <OptionSensorHub onConfirm={onConfirm} />
        </div>
      )}
    </div>
  </Fade>
)

const TableModalSheet = ({ open, onClose }: TableModalSheetProps) => {
  const t = useTranslations('sensorHub')
  const [showAddForm, setShowAddForm] = useState(false)
  const isMobile = useMediaQuery((theme: Theme) => theme.breakpoints.down('sm'))
  const { setSensorHub } = useSensorHub()

  const contentProps = {
    selectSensor: t('selectSensor'),
    selectSensorDescription: t('selectSensorDescription'),
    addSensor: t('addSensor')
  }

  const handleBack = () => setShowAddForm(false)

  const handleConfirm = (sensor: Sensor) => {
    setSensorHub({ id: sensor.uuid_sensor, ...sensor })
    onClose()
  }

  if (isMobile) {
    return (
      <Drawer
        anchor='bottom'
        variant='temporary'
        open={open}
        onClose={onClose}
        ModalProps={{ keepMounted: true }}
        slotProps={{
          backdrop: {
            sx: backdropBlurSx
          }
        }}
        PaperProps={{
          sx: {
            maxHeight: '80vh',
            borderTopLeftRadius: 'var(--mui-shape-borderRadius)',
            borderTopRightRadius: 'var(--mui-shape-borderRadius)'
          }
        }}
      >
        <div className='flex items-center justify-between plb-4 pli-6 border-bs'>
          <Typography variant='h5'>{t('sensorData')}</Typography>
          <IconButton size='small' onClick={onClose} aria-label={t('ariaClose')}>
            <i className='tabler-x text-2xl' />
          </IconButton>
        </div>
        <div className='overflow-y-auto pli-6 plb-6' style={{ maxHeight: 'calc(80vh - 72px)' }}>
          <DrawerContentWithTransition
            showAddForm={showAddForm}
            onShowAddForm={() => setShowAddForm(true)}
            onBack={handleBack}
            onConfirm={handleConfirm}
            {...contentProps}
          />
        </div>
      </Drawer>
    )
  }

  return (
    <Dialog
      fullWidth
      maxWidth='lg'
      open={open}
      onClose={onClose}
      slotProps={{
        backdrop: {
          sx: backdropBlurSx
        }
      }}
    >

      <DialogContent>
        <DialogContentWithTransition
          showAddForm={showAddForm}
          onShowAddForm={() => setShowAddForm(true)}
          onBack={handleBack}
          onConfirm={handleConfirm}
          {...contentProps}
        />
      </DialogContent>
    </Dialog>
  )
}

export default TableModalSheet
