import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { sessionDetailOptions, sessionKeys, sessionMutations, sessionPlanItemsOptions } from '@/api/lessons'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { CheckCircle, XCircle, Clock, GraduationCap } from 'lucide-react'
import { toast } from 'sonner'

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

interface SessionDetailPanelProps {
  sessionId: string | null
  canEdit: boolean
}

export function SessionDetailPanel({ sessionId, canEdit }: SessionDetailPanelProps) {
  const queryClient = useQueryClient()
  const [notes, setNotes] = useState('')
  const [notesLoaded, setNotesLoaded] = useState(false)

  const { data: session, isLoading } = useQuery({
    ...sessionDetailOptions(sessionId ?? ''),
    enabled: !!sessionId,
  })

  const { data: planItems } = useQuery({
    ...sessionPlanItemsOptions(sessionId ?? ''),
    enabled: !!sessionId,
  })

  // Sync notes from session data
  if (session && !notesLoaded) {
    setNotes(session.instructorNotes ?? '')
    setNotesLoaded(true)
  }

  const statusMutation = useMutation({
    mutationFn: (status: string) => sessionMutations.updateStatus(sessionId!, status),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: sessionKeys.detail(sessionId!) })
      queryClient.invalidateQueries({ queryKey: sessionKeys.all })
      toast.success('Attendance recorded')
    },
    onError: (err) => toast.error(err.message),
  })

  const notesMutation = useMutation({
    mutationFn: () => sessionMutations.updateNotes(sessionId!, { instructorNotes: notes }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: sessionKeys.detail(sessionId!) })
      toast.success('Notes saved')
    },
    onError: (err) => toast.error(err.message),
  })

  if (!sessionId) {
    return (
      <div className="flex items-center justify-center h-full text-muted-foreground">
        <div className="text-center space-y-2">
          <GraduationCap className="h-10 w-10 mx-auto opacity-20" />
          <p className="text-sm">Select a session</p>
        </div>
      </div>
    )
  }

  if (isLoading || !session) {
    return (
      <div className="p-4 space-y-4">
        <div className="h-8 bg-muted animate-pulse rounded" />
        <div className="h-20 bg-muted animate-pulse rounded" />
      </div>
    )
  }

  const status = STATUS_CONFIG[session.status] ?? { label: session.status, color: '' }

  return (
    <div className="flex flex-col h-full overflow-hidden">
      {/* Header */}
      <div className="p-4 border-b border-border shrink-0">
        <div className="flex items-center justify-between mb-2">
          <div>
            <h3 className="text-lg font-semibold">{session.memberName ?? 'Unknown Student'}</h3>
            <p className="text-sm text-muted-foreground">
              {session.lessonTypeName ?? 'Lesson'} — {session.instructorName ?? 'No instructor'}
            </p>
          </div>
          <Badge variant="outline" className={status.color}>{status.label}</Badge>
        </div>
        <div className="flex items-center gap-4 text-sm text-muted-foreground">
          <span>{new Date(session.scheduledDate + 'T00:00:00').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}</span>
          <span>{session.scheduledTime}</span>
        </div>
      </div>

      {/* Attendance buttons */}
      {canEdit && session.status === 'scheduled' && (
        <div className="flex gap-2 p-3 border-b border-border shrink-0 bg-muted/30">
          <Button
            className="flex-1 h-12 gap-2 bg-green-600 hover:bg-green-700"
            onClick={() => statusMutation.mutate('attended')}
            disabled={statusMutation.isPending}
          >
            <CheckCircle className="h-5 w-5" />
            Attended
          </Button>
          <Button
            variant="outline"
            className="flex-1 h-12 gap-2 text-red-500 border-red-500/30 hover:bg-red-500/10"
            onClick={() => statusMutation.mutate('missed')}
            disabled={statusMutation.isPending}
          >
            <XCircle className="h-5 w-5" />
            Missed
          </Button>
          <Button
            variant="outline"
            className="flex-1 h-12 gap-2"
            onClick={() => statusMutation.mutate('cancelled')}
            disabled={statusMutation.isPending}
          >
            <Clock className="h-5 w-5" />
            Cancel
          </Button>
        </div>
      )}

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {/* Plan items */}
        {planItems && planItems.length > 0 && (
          <div>
            <Label className="text-xs text-muted-foreground">Lesson Plan Items</Label>
            <div className="mt-2 space-y-1">
              {planItems.map((item) => (
                <div key={item.id} className="flex items-center gap-2 py-1 text-sm">
                  <div className="h-4 w-4 rounded border border-border" />
                  <span>{item.lessonPlanItemId}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Notes */}
        <div className="space-y-2">
          <Label className="text-xs text-muted-foreground">Instructor Notes</Label>
          <Textarea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            placeholder="Session notes, observations, homework..."
            rows={4}
            disabled={!canEdit}
          />
          {canEdit && (
            <Button
              size="sm"
              onClick={() => notesMutation.mutate()}
              disabled={notesMutation.isPending || notes === (session.instructorNotes ?? '')}
            >
              {notesMutation.isPending ? 'Saving...' : 'Save Notes'}
            </Button>
          )}
        </div>

        {/* Previous notes */}
        {session.homeworkAssigned && (
          <div>
            <Label className="text-xs text-muted-foreground">Homework Assigned</Label>
            <p className="text-sm mt-1">{session.homeworkAssigned}</p>
          </div>
        )}
        {session.nextLessonGoals && (
          <div>
            <Label className="text-xs text-muted-foreground">Next Lesson Goals</Label>
            <p className="text-sm mt-1">{session.nextLessonGoals}</p>
          </div>
        )}
        {session.topicsCovered && session.topicsCovered.length > 0 && (
          <div>
            <Label className="text-xs text-muted-foreground">Topics Covered</Label>
            <div className="flex gap-1.5 flex-wrap mt-1">
              {session.topicsCovered.map((topic, i) => (
                <Badge key={i} variant="outline" className="text-xs">{topic}</Badge>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
