'use client'

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

// MUI Imports
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CircularProgress from '@mui/material/CircularProgress'

// Third-party Imports
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
import DateObject from 'react-date-object'

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

// Style Imports
import styles from '@core/styles/table.module.css'

const formatToShamsi = (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
  }
}

// Column Definitions
const columnHelper = createColumnHelper<Sensor>()

const SensorHubTable = () => {
  const t = useTranslations('sensorHub')

  const columns = useMemo(
    () => [
      columnHelper.accessor('name', {
        cell: info => info.getValue(),
        header: t('columns.name')
      }),
      columnHelper.accessor('last_updated', {
        cell: info => formatToShamsi(info.getValue()),
        header: t('columns.lastUpdate')
      }),
      columnHelper.accessor('uuid_sensor', {
        cell: info => info.getValue(),
        header: t('columns.uuid')
      })
    ],
    [t]
  )
  const [data, setData] = useState<Sensor[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchSensors = async () => {
      try {
        setLoading(true)
        setError(null)
        const sensors = await sensorHubService.listSensors()
        setData(sensors)
      } catch (err) {
        setError(err instanceof Error ? err.message : t('errorLoad'))
        setData([])
      } finally {
        setLoading(false)
      }
    }

    fetchSensors()
  }, [])

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    filterFns: {
      fuzzy: () => false
    }
  })

  if (loading) {
    return (
      <Card>
        <CardHeader title={t('title')} />
        <div className='flex items-center justify-center p-12'>
          <CircularProgress />
        </div>
      </Card>
    )
  }

  if (error) {
    return (
      <Card>
        <CardHeader title={t('title')} subheader={error} />
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader title={t('title')} />
      <div className='overflow-x-auto'>
        <table className={styles.table}>
          <thead>
            {table.getHeaderGroups().map(headerGroup => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map(header => (
                  <th key={header.id}>
                    {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody>
            {table.getRowModel().rows.map(row => (
              <tr key={row.id}>
                {row.getVisibleCells().map(cell => (
                  <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Card>
  )
}

export default SensorHubTable
