'use client'
import { useMemo } from 'react'
import { useT } from '@/contexts/LangContext'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import Box from '@mui/material/Box'
import type { Hearing } from './types'

function getCountdown(dateStr: string, timeStr: string): { label: string; urgent: boolean } {
  const [h, m] = timeStr.split(':').map(Number)
  const target = new Date(dateStr)
  target.setHours(h, m, 0, 0)
  const diff = target.getTime() - Date.now()
  if (diff <= 0) return { label: 'now', urgent: true }
  const hours = Math.floor(diff / 3600000)
  const mins = Math.floor((diff % 3600000) / 60000)
  if (hours < 1) return { label: `${mins}m`, urgent: true }
  if (hours < 3) return { label: `${hours}h ${mins}m`, urgent: true }
  if (hours < 24) return { label: `${hours}h ${mins}m`, urgent: false }
  const days = Math.ceil(diff / 86400000)
  return { label: `${days}d`, urgent: false }
}

const NextHearingCard = ({
  hearing,
  onAiBrief,
}: {
  hearing: Hearing | null
  onAiBrief?: (hearingId: string) => void
}) => {
  const t = useT()
  const countdown = useMemo(
    () => (hearing ? getCountdown(hearing.date, hearing.time) : null),
    [hearing],
  )

  if (!hearing) {
    return (
      <Card>
        <CardContent sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', py: 4 }}>
          <Typography color='text.secondary'>{t.dashboard.noHearings}</Typography>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card sx={{ position: 'relative', overflow: 'hidden' }}>
      {/* Accent bar */}
      <Box sx={{
        position: 'absolute', top: 0, left: 0, width: 3, height: '100%',
        bgcolor: countdown?.urgent ? 'error.main' : 'primary.main',
      }} />

      <CardContent sx={{ pl: 3 }}>
        {/* Top row: label + countdown chip */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
          <Typography variant='overline' color='text.secondary' sx={{ letterSpacing: 1 }}>
            {t.dashboard.nextHearing}
          </Typography>
          <Chip
            label={countdown?.label === 'now' ? t.common.now : countdown?.label}
            size='small'
            color={countdown?.urgent ? 'error' : 'primary'}
            icon={<i className='ri-time-line' />}
            sx={{ fontWeight: 700, fontSize: '0.72rem' }}
          />
        </Box>

        {/* Matter + client */}
        <Typography variant='subtitle1' sx={{ fontWeight: 700, lineHeight: 1.3, mb: 0.25 }}>
          {hearing.matter}
        </Typography>
        <Typography variant='body2' color='text.secondary' sx={{ mb: 1.5 }}>
          {hearing.client}
        </Typography>

        {/* Details inline */}
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2, mb: 1.5 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
            <i className='ri-time-line' style={{ fontSize: '0.85rem', color: '#9CA3AF' }} />
            <Typography variant='caption' color='text.secondary'>{hearing.time}</Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
            <i className='ri-map-pin-line' style={{ fontSize: '0.85rem', color: '#9CA3AF' }} />
            <Typography variant='caption' color='text.secondary'>
              {hearing.court}{hearing.room ? ` · Rm ${hearing.room}` : ''}
            </Typography>
          </Box>
          {hearing.judge && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
              <i className='ri-user-star-line' style={{ fontSize: '0.85rem', color: '#9CA3AF' }} />
              <Typography variant='caption' color='text.secondary'>{hearing.judge}</Typography>
            </Box>
          )}
          <Chip
            label={hearing.status === 'confirmed' ? t.common.confirmed : t.common.pending}
            size='small'
            color={hearing.status === 'confirmed' ? 'success' : 'warning'}
            sx={{ height: 18, fontSize: '0.65rem', fontWeight: 600 }}
          />
        </Box>

        {/* Actions */}
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button variant='contained' size='small' startIcon={<i className='ri-file-text-line' />}
            sx={{ fontSize: '0.75rem', py: 0.5 }}>
            {t.dashboard.viewMatter}
          </Button>
          <Button variant='outlined' size='small' startIcon={<i className='ri-sparkling-line' />}
            onClick={() => onAiBrief?.(hearing.id)} sx={{ fontSize: '0.75rem', py: 0.5 }}>
            {t.dashboard.aiBrief}
          </Button>
        </Box>
      </CardContent>
    </Card>
  )
}

export default NextHearingCard
