'use client'

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

// MUI Imports
import Grid from '@mui/material/Grid2'
import Button from '@mui/material/Button'
import CircularProgress from '@mui/material/CircularProgress'

// Third-party Imports
import DateObject from 'react-date-object'

// Type Imports
import type { CustomInputHorizontalData } from '@core/components/custom-inputs/types'

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

// Component Imports
import CustomInputHorizontal from '@core/components/custom-inputs/Horizontal'

type OptionSensorHubProps = {
  onConfirm?: (sensor: Sensor) => void
}

const formatLastUpdated = (dateStr: string | null | undefined): string => {
  if (!dateStr) return '—'
  try {
    const d = new DateObject(new Date(dateStr)).convert('persian' as any).setLocale('fa' as any)

    return d.format('YYYY/MM/DD')
  } catch {
    return dateStr
  }
}

const sensorToOption = (sensor: Sensor, isFirst: boolean): CustomInputHorizontalData => ({
  title: sensor.name,
  meta: formatLastUpdated(sensor.last_updated),
  content: sensor.uuid_sensor,
  value: sensor.uuid_sensor,
  isSelected: isFirst
})

const OptionSensorHub = ({ onConfirm }: OptionSensorHubProps) => {
  const [sensors, setSensors] = useState<Sensor[]>([])
  const [data, setData] = useState<CustomInputHorizontalData[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedOption, setSelectedOption] = useState<string>('')

  useEffect(() => {
    const fetchSensors = async () => {
      try {
        setLoading(true)
        const sensorsList = await sensorHubService.listSensors()
        setSensors(sensorsList)
        const options = sensorsList.map((s, i) => sensorToOption(s, i === 0))
        setData(options)
        if (options.length > 0) {
          const selected = options.find(o => o.isSelected) ?? options[0]

          setSelectedOption(selected.value)
        }
      } catch {
        setSensors([])
        setData([])
      } finally {
        setLoading(false)
      }
    }

    fetchSensors()
  }, [])

  const handleOptionChange = (prop: string | ChangeEvent<HTMLInputElement>) => {
    if (typeof prop === 'string') {
      setSelectedOption(prop)
    } else {
      setSelectedOption((prop.target as HTMLInputElement).value)
    }
  }

  if (loading) {
    return (
      <div className='flex items-center justify-center py-12'>
        <CircularProgress />
      </div>
    )
  }

  if (data.length === 0) {
    return null
  }

  const handleConfirm = () => {
    const selected = sensors.find(s => s.uuid_sensor === selectedOption)
    if (selected && onConfirm) {
      onConfirm(selected)
    }
  }

  return (
    <form onSubmit={e => e.preventDefault()}>
      <Grid container>
        {data.map(item => (
          <CustomInputHorizontal
            type='radio'
            key={item.value}
            data={item}
            gridProps={{
              size: { xs: 12 },
              className:
                '[&:first-of-type>*]:rounded-be-none [&:last-of-type>*]:rounded-bs-none [&:nth-of-type(2)>*]:rounded-none'
            }}
            selected={selectedOption}
            name='sensor-hub-option'
            handleChange={handleOptionChange}
          />
        ))}
      </Grid>
      {onConfirm && (
        <div className='flex justify-end mts-4'>
          <Button
            variant='contained'
            sx={{mt:4}}
            color='primary'
            onClick={handleConfirm}
            startIcon={<i className='tabler-check text-xl' />}
          >
            تایید
          </Button>
        </div>
      )}
    </form>
  )
}

export default OptionSensorHub
