import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { sessionListOptions } from '@/api/lessons'
import type { LessonSession } from '@/types/lesson'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { SessionDetailPanel } from './session-detail-panel'
import { CheckCircle, Clock, XCircle, AlertCircle } from 'lucide-react'

const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof CheckCircle }> = {
  scheduled: { label: 'Scheduled', color: 'bg-blue-500/10 text-blue-500', icon: Clock },
  attended: { label: 'Attended', color: 'bg-green-500/10 text-green-500', icon: CheckCircle },
  missed: { label: 'Missed', color: 'bg-red-500/10 text-red-500', icon: XCircle },
  makeup: { label: 'Makeup', color: 'bg-purple-500/10 text-purple-500', icon: Clock },
  cancelled: { label: 'Cancelled', color: 'bg-muted text-muted-foreground', icon: XCircle },
}

interface LessonsTodayOverviewProps {
  canEdit: boolean
}

export function LessonsTodayOverview({ canEdit }: LessonsTodayOverviewProps) {
  const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null)
  const [groupBy, setGroupBy] = useState<'time' | 'instructor'>('time')

  const today = new Date().toISOString().slice(0, 10)

  const { data, isLoading } = useQuery({
    ...sessionListOptions({
      page: 1,
      limit: 100,
      sort: 'scheduled_time',
      order: 'asc',
      scheduledDateFrom: today,
      scheduledDateTo: today,
    }),
    staleTime: 30_000,
    refetchInterval: 60_000,
  })

  const sessions = data?.data ?? []

  // Check if a session is upcoming (within next 30 min)
  function isUpcoming(session: LessonSession) {
    if (session.status !== 'scheduled') return false
    const now = new Date()
    const [hours, minutes] = session.scheduledTime.split(':').map(Number)
    const sessionTime = new Date(session.scheduledDate + 'T00:00:00')
    sessionTime.setHours(hours, minutes)
    const diff = sessionTime.getTime() - now.getTime()
    return diff > 0 && diff <= 30 * 60_000
  }

  // Check if overdue (scheduled, past time)
  function isOverdue(session: LessonSession) {
    if (session.status !== 'scheduled') return false
    const now = new Date()
    const [hours, minutes] = session.scheduledTime.split(':').map(Number)
    const sessionTime = new Date(session.scheduledDate + 'T00:00:00')
    sessionTime.setHours(hours, minutes)
    return sessionTime.getTime() < now.getTime()
  }

  // Group by instructor
  const byInstructor = sessions.reduce((acc, s) => {
    const name = s.instructorName ?? 'Unassigned'
    if (!acc[name]) acc[name] = []
    acc[name].push(s)
    return acc
  }, {} as Record<string, LessonSession[]>)

  // Status counts
  const scheduled = sessions.filter(s => s.status === 'scheduled').length
  const attended = sessions.filter(s => s.status === 'attended').length
  const missed = sessions.filter(s => s.status === 'missed').length

  return (
    <div className="flex flex-col h-full">
      {/* Summary bar */}
      <div className="flex items-center gap-3 px-3 py-2 border-b border-border shrink-0 bg-card/50">
        <span className="text-sm font-medium">Today</span>
        <Badge variant="outline" className="text-xs">{sessions.length} sessions</Badge>
        {scheduled > 0 && <Badge variant="outline" className="text-xs bg-blue-500/10 text-blue-500">{scheduled} scheduled</Badge>}
        {attended > 0 && <Badge variant="outline" className="text-xs bg-green-500/10 text-green-500">{attended} attended</Badge>}
        {missed > 0 && <Badge variant="outline" className="text-xs bg-red-500/10 text-red-500">{missed} missed</Badge>}
        <div className="flex-1" />
        <div className="flex gap-1">
          <Button variant={groupBy === 'time' ? 'default' : 'ghost'} size="sm" className="h-7 text-xs" onClick={() => setGroupBy('time')}>By Time</Button>
          <Button variant={groupBy === 'instructor' ? 'default' : 'ghost'} size="sm" className="h-7 text-xs" onClick={() => setGroupBy('instructor')}>By Instructor</Button>
        </div>
      </div>

      {/* Split view */}
      <div className="flex flex-1 min-h-0">
        {/* Session list */}
        <div className="w-[40%] border-r border-border overflow-y-auto">
          {isLoading ? (
            <div className="p-3 space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className="h-14 bg-muted animate-pulse rounded-lg" />
              ))}
            </div>
          ) : sessions.length === 0 ? (
            <div className="flex items-center justify-center h-full text-muted-foreground">
              <p className="text-sm">No sessions today</p>
            </div>
          ) : groupBy === 'time' ? (
            <div className="px-2 py-2 space-y-1">
              {sessions.map((session) => (
                <SessionRow
                  key={session.id}
                  session={session}
                  selected={selectedSessionId === session.id}
                  upcoming={isUpcoming(session)}
                  overdue={isOverdue(session)}
                  onClick={() => setSelectedSessionId(session.id)}
                />
              ))}
            </div>
          ) : (
            <div className="px-2 py-2 space-y-3">
              {Object.entries(byInstructor).map(([instructor, instructorSessions]) => (
                <div key={instructor}>
                  <p className="text-xs font-semibold text-muted-foreground px-2 mb-1">{instructor}</p>
                  <div className="space-y-1">
                    {instructorSessions.map((session) => (
                      <SessionRow
                        key={session.id}
                        session={session}
                        selected={selectedSessionId === session.id}
                        upcoming={isUpcoming(session)}
                        overdue={isOverdue(session)}
                        onClick={() => setSelectedSessionId(session.id)}
                      />
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Detail panel */}
        <div className="w-[60%] overflow-hidden">
          <SessionDetailPanel sessionId={selectedSessionId} canEdit={canEdit} />
        </div>
      </div>
    </div>
  )
}

function SessionRow({ session, selected, upcoming, overdue, onClick }: {
  session: LessonSession
  selected: boolean
  upcoming: boolean
  overdue: boolean
  onClick: () => void
}) {
  const cfg = STATUS_CONFIG[session.status] ?? { label: session.status, color: '', icon: Clock }
  const StatusIcon = cfg.icon

  return (
    <button
      className={`w-full text-left p-3 rounded-lg transition-colors ${
        selected ? 'bg-primary/10 border border-primary/20' :
        upcoming ? 'bg-yellow-500/5 border border-yellow-500/20 hover:bg-yellow-500/10' :
        overdue ? 'bg-red-500/5 border border-red-500/20 hover:bg-red-500/10' :
        'hover:bg-muted border border-transparent'
      }`}
      onClick={onClick}
    >
      <div className="flex items-center justify-between mb-0.5">
        <span className="text-sm font-medium">{session.scheduledTime}</span>
        <div className="flex items-center gap-1">
          {overdue && <AlertCircle className="h-3.5 w-3.5 text-red-500" />}
          <Badge variant="outline" className={`text-[10px] ${cfg.color}`}>
            <StatusIcon className="h-2.5 w-2.5 mr-0.5" />
            {cfg.label}
          </Badge>
        </div>
      </div>
      <div className="text-sm">{session.memberName ?? 'Unknown'}</div>
      <div className="flex items-center justify-between text-xs text-muted-foreground mt-0.5">
        <span>{session.lessonTypeName ?? 'Lesson'}</span>
        <span>{session.instructorName ?? ''}</span>
      </div>
    </button>
  )
}
