'use client'

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 Grid from '@mui/material/Grid2'
import Chip from '@mui/material/Chip'
import CircularProgress from '@mui/material/CircularProgress'
import Button from '@mui/material/Button'
import Stack from '@mui/material/Stack'
import { useLocale, useTranslations } from 'next-intl'

import { useGetTableStatus } from '@/@core/hooks/data/table'
import type { ITableStatus } from '@/types/data/table'

type Props = {
  open: boolean
  tableId?: string | null
  tableLabel?: string
  onClose: () => void
}

const TableStatusDrawer = ({ open, tableId, tableLabel, onClose }: Props) => {
  const locale = useLocale()
  const t = useTranslations('tables.status')
  const { data, isLoading, refetch, isFetching } = useGetTableStatus(tableId || '', {
    enabled: Boolean(open && tableId),
    refetchInterval: open && tableId ? 15000 : false
  })

  const status = data?.data as ITableStatus | undefined

  const parseTimestamp = (value?: number | null) => {
    if (!value) return t('unknown')
    const ms = value < 1_000_000_000_000 ? value * 1000 : value
    const date = new Date(ms)
    return Number.isNaN(date.getTime()) ? t('unknown') : date.toLocaleString(locale)
  }

  const estimatedMinutes = status?.estimated_free_time ? Math.round(status.estimated_free_time / 60) : null

  return (
    <Drawer
      anchor='right'
      open={open}
      onClose={onClose}
      sx={{ '& .MuiDrawer-paper': { width: { xs: 360, sm: 420 }, p: 4 } }}
    >
      <div className='flex items-start justify-between gap-2'>
        <div>
          <Typography variant='h6'>{t('title', { table: tableLabel || '' })}</Typography>
          <Typography variant='body2' color='text.secondary'>
            {t('subtitle')}
          </Typography>
        </div>

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

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

      {!tableId ? (
        <div className='flex flex-col gap-2 items-center justify-center h-full'>
          <Typography variant='body2' color='text.secondary'>
            {t('noTable')}
          </Typography>
        </div>
      ) : isLoading ? (
        <div className='flex flex-col items-center gap-2'>
          <CircularProgress />
          <Typography variant='body2' color='text.secondary'>
            {t('loading')}
          </Typography>
        </div>
      ) : status ? (
        <>
          <Stack spacing={2} mb={4}>
            <div className='flex items-center justify-between gap-2'>
              <Typography variant='body2' color='text.secondary'>
                {t('state')}
              </Typography>
              <Chip
                label={
                  status.is_occupied
                    ? locale === 'ar'
                      ? status.status_ar
                      : status.status_en
                    : t('available')
                }
                color={status.is_occupied ? 'warning' : 'success'}
              />
            </div>

            <div className='flex items-center justify-between gap-2'>
              <Typography variant='body2' color='text.secondary'>
                {t('currentOrder')}
              </Typography>
              <Typography fontWeight={600}>
                {status.current_order ? `#${status.current_order}` : t('noOrder')}
              </Typography>
            </div>

            <div className='flex items-center justify-between gap-2'>
              <Typography variant='body2' color='text.secondary'>
                {t('occupiedSince')}
              </Typography>
              <Typography fontWeight={600}>{parseTimestamp(status.occupied_since)}</Typography>
            </div>

            <div className='flex items-center justify-between gap-2'>
              <Typography variant='body2' color='text.secondary'>
                {t('eta')}
              </Typography>
              <Typography fontWeight={600}>
                {estimatedMinutes ? t('etaMinutes', { minutes: estimatedMinutes }) : t('etaUnknown')}
              </Typography>
            </div>

            <div className='flex items-center justify-between gap-2'>
              <Typography variant='body2' color='text.secondary'>
                {t('ordersCount')}
              </Typography>
              <Typography fontWeight={600}>
                {t('ordersSummary', {
                  total: status.table.total_orders ?? 0,
                  active: status.table.active_orders ?? 0
                })}
              </Typography>
            </div>
          </Stack>

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

          <Grid container spacing={3}>
            <Grid size={12}>
              <Typography variant='subtitle2' gutterBottom>
                {t('tableInfo')}
              </Typography>
            </Grid>
            <Grid size={6}>
              <Typography variant='body2' color='text.secondary'>
                {t('tableNumber')}
              </Typography>
              <Typography fontWeight={600}>{status.table.table_number}</Typography>
            </Grid>
            <Grid size={6}>
              <Typography variant='body2' color='text.secondary'>
                {t('capacity')}
              </Typography>
              <Typography fontWeight={600}>{status.table.capacity}</Typography>
            </Grid>
            <Grid size={6}>
              <Typography variant='body2' color='text.secondary'>
                {t('location')}
              </Typography>
              <Typography fontWeight={600}>{status.table.location || t('unknown')}</Typography>
            </Grid>
            <Grid size={6}>
              <Typography variant='body2' color='text.secondary'>
                {t('createdAt')}
              </Typography>
              <Typography fontWeight={600}>
                {status.table.created_at ? new Date(status.table.created_at).toLocaleString(locale) : t('unknown')}
              </Typography>
            </Grid>
          </Grid>
        </>
      ) : (
        <Typography variant='body2' color='error'>
          {t('error')}
        </Typography>
      )}

      {tableId && (
        <Button
          variant='outlined'
          fullWidth
          sx={{ mt: 4 }}
          onClick={() => refetch()}
          startIcon={isFetching ? <CircularProgress size={16} /> : <i className='tabler-refresh' />}
        >
          {isFetching ? t('refreshing') : t('refresh')}
        </Button>
      )}
    </Drawer>
  )
}

export default TableStatusDrawer
