'use client'

// React Imports
import { useState } from 'react'
import { useTranslations } from 'next-intl'

// MUI Imports
import Grid from '@mui/material/Grid2'
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Fade from '@mui/material/Fade'

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

// API Imports
import type { Sensor } from '@/libs/api/services/sensorHubService'

// Component Imports
import SensorHubTable from '@views/sensorHub/SensorHubTable'
import OptionSensorHub from '@views/sensorHub/OptionSensorHub'
import FormSensorHub from '@views/sensorHub/FormSensorHub'

const transitionTimeout = { enter: 300, exit: 200 }

const SensorHubTabContent = () => {
  const t = useTranslations('sensorHub')
  const [showAddForm, setShowAddForm] = useState(false)
  const { setSensorHub } = useSensorHub()

  const handleBack = () => setShowAddForm(false)

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

  return (
    <Grid container spacing={6}>

      <Grid size={{ xs: 12 }}>
        <Card>
          <CardContent>
            <Fade key={showAddForm ? 'form' : 'options'} in timeout={transitionTimeout}>
              <div>
                {showAddForm ? (
                  <FormSensorHub onBack={handleBack} />
                ) : (
                  <div className='flex flex-col gap-4'>
                    <div className='grid grid-cols-1 sm:grid-cols-[1fr_auto] items-center gap-4'>
                      <div className='flex flex-col gap-0.5'>
                        <Typography variant='h6' fontWeight={600}>
                          {t('selectSensor')}
                        </Typography>
                        <Typography variant='body2' color='text.secondary' sx={{ lineHeight: 1.5 }}>
                          {t('selectSensorDescription')}
                        </Typography>
                      </div>
                      <Button
                        variant='contained'
                        color='primary'
                        startIcon={<i className='tabler-plus text-xl' />}
                        onClick={() => setShowAddForm(true)}
                      >
                        {t('addSensor')}
                      </Button>
                    </div>
                    <OptionSensorHub onConfirm={handleConfirm} />
                  </div>
                )}
              </div>
            </Fade>
          </CardContent>
        </Card>
      </Grid>
    </Grid>
  )
}

export default SensorHubTabContent
