'use client'
import { useRef, useState, useEffect, useCallback } from 'react'
import { useT } from '@/contexts/LangContext'
import dynamic from 'next/dynamic'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import Button from '@mui/material/Button'
import Box from '@mui/material/Box'
import Chip from '@mui/material/Chip'
import Typography from '@mui/material/Typography'
import CircularProgress from '@mui/material/CircularProgress'
import type { Hearing, Matter, Appointment } from './types'

const LegalCalendarGrid = dynamic(() => import('./LegalCalendarGrid'), {
  ssr: false,
  loading: () => (
    <Box sx={{ minHeight: 300, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <CircularProgress size={24} />
    </Box>
  ),
})

const LEGEND_COLORS = ['#0D9394', '#FF4C51', '#16B1FF']

function fmtDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' })
}

const TYPE_COLOR: Record<string, string> = {
  hearing:  '#0D9394',
  deadline: '#FF4C51',
  filing:   '#16B1FF',
  review:   '#9C6FDE',
}

const TYPE_ICON: Record<string, string> = {
  hearing:  'ri-bank-line',
  deadline: 'ri-alarm-warning-line',
  filing:   'ri-file-upload-line',
  review:   'ri-eye-line',
}

const APPT_ICON: Record<Appointment['type'], string> = {
  consultation: 'ri-discuss-line',
  meeting:      'ri-group-line',
  call:         'ri-phone-line',
  signing:      'ri-pen-nib-line',
}


function NextEventReminder({
  appointments,
  onViewFolder,
}: {
  appointments: Appointment[]
  onViewFolder?: (matterId: string) => void
}) {
  const t = useT()
  const now = new Date()
  const todayStr = now.toISOString().split('T')[0]
  const nowTime  = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`

  const next = [...appointments]
    .filter(a => a.date > todayStr || (a.date === todayStr && a.time >= nowTime))
    .sort((a, b) => a.date.localeCompare(b.date) || a.time.localeCompare(b.time))[0]

  if (!next) return null

  const color = '#9C6FDE'
  const icon  = APPT_ICON[next.type]

  return (
    <Box sx={{
      border: '1px solid',
      borderColor: color + '55',
      borderRadius: 2,
      bgcolor: color + '11',
      p: 1.5,
      mb: 1.5,
    }}>
      {/* Header row */}
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.75 }}>
        <i className={icon} style={{ fontSize: '0.95rem', color }} />
        <Typography variant='caption' sx={{ fontWeight: 700, color, textTransform: 'uppercase', letterSpacing: 0.5 }}>
          {t.dashboard.calNextPrefix} {t.calendar[next.type as keyof typeof t.calendar]}
        </Typography>
        <Box sx={{ flex: 1 }} />
        <Typography variant='caption' color='text.disabled'>{fmtDate(next.date)} · {next.time}</Typography>
      </Box>

      {/* Title + client */}
      <Typography variant='body2' sx={{ fontWeight: 600, lineHeight: 1.3 }} noWrap>{next.title}</Typography>
      <Typography variant='caption' color='text.secondary'>{next.client}</Typography>

      {/* Location */}
      {next.location && (
        <Typography variant='caption' color='text.disabled' sx={{ display: 'block', mt: 0.25 }}>
          <i className='ri-map-pin-line' style={{ fontSize: '0.75rem', marginRight: 3 }} />{next.location}
        </Typography>
      )}

      {next.notes && (
        <Typography variant='caption' color='text.secondary' sx={{ display: 'block', mt: 0.5, fontStyle: 'italic' }}>
          {next.notes}
        </Typography>
      )}

      {/* Action */}
      <Button
        size='small'
        variant='outlined'
        sx={{ mt: 1, fontSize: '0.7rem', py: 0.25, borderColor: color, color }}
        startIcon={<i className='ri-folder-open-line' style={{ fontSize: '0.8rem' }} />}
        onClick={() => onViewFolder?.(next.matterId)}
      >
        {t.dashboard.calReviewFolder}
      </Button>
    </Box>
  )
}

export default function CalendarCard({
  hearings,
  matters,
  appointments = [],
  onEventClick,
  fullViewHref,
  onViewFolder,
}: {
  hearings: Hearing[]
  matters: Matter[]
  appointments?: Appointment[]
  onEventClick?: (id: string, type: string) => void
  fullViewHref?: string
  onViewFolder?: (matterId: string) => void
}) {
  const t = useT()
  const cardRef = useRef<HTMLDivElement>(null)
  const [isFullscreen, setIsFullscreen] = useState(false)

  useEffect(() => {
    const handler = () => setIsFullscreen(!!document.fullscreenElement)
    document.addEventListener('fullscreenchange', handler)
    return () => document.removeEventListener('fullscreenchange', handler)
  }, [])

  const toggleFullscreen = useCallback(() => {
    if (!document.fullscreenElement) {
      cardRef.current?.requestFullscreen()
    } else {
      document.exitFullscreen()
    }
  }, [])

  return (
    <Card
      ref={cardRef}
      sx={isFullscreen ? { borderRadius: 0, height: '100vh', display: 'flex', flexDirection: 'column' } : {}}
    >
      <CardHeader
        title={t.calendar.title}
        titleTypographyProps={{ variant: 'subtitle2' }}
        sx={{ pb: 0.5, pt: 1.5, px: 2 }}
        action={
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mr: 0.5 }}>
            {fullViewHref && (
              <Button component='a' href={fullViewHref} size='small' sx={{ fontSize: '0.72rem', py: 0.25, minWidth: 0 }}
                endIcon={<i className='ri-external-link-line' style={{ fontSize: '0.8rem' }} />}>
                {t.dashboard.calFullView}
              </Button>
            )}
            <Tooltip title={isFullscreen ? t.dashboard.calExitFullscreen : t.dashboard.calFullscreen}>
              <IconButton size='small' onClick={toggleFullscreen}>
                <i className={isFullscreen ? 'ri-fullscreen-exit-line' : 'ri-fullscreen-line'} style={{ fontSize: '1rem' }} />
              </IconButton>
            </Tooltip>
          </Box>
        }
      />

      <CardContent sx={{ pt: 0.5, px: 2, pb: '12px !important', flex: isFullscreen ? 1 : undefined, overflow: isFullscreen ? 'auto' : undefined }}>
        <NextEventReminder appointments={appointments} onViewFolder={onViewFolder} />
        <Box sx={{ display: 'flex', gap: 0.75, mb: 1.5, flexWrap: 'wrap' }}>
          {([t.calendar.hearing, t.calendar.deadline, t.calendar.filing] as string[]).map((label, i) => (
            <Chip key={label} label={label} size='small'
              sx={{ fontSize: '0.62rem', height: 18, bgcolor: LEGEND_COLORS[i] + '22', color: LEGEND_COLORS[i], fontWeight: 600 }} />
          ))}
        </Box>
        <LegalCalendarGrid hearings={hearings} matters={matters} onEventClick={onEventClick} />
      </CardContent>
    </Card>
  )
}
