'use client'

import { useState } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Badge } from '@/components/ui/badge'
import { AnimatedCard } from '@/components/shared/animated-container'
import { MessageCircle, Users, ChevronDown, ChevronUp } from 'lucide-react'

export function MentoringPanel({ roundId }: { roundId: string }) {
  const [expandedMentorId, setExpandedMentorId] = useState<string | null>(null)

  const { data: mentoringData, isLoading } = trpc.analytics.getMentoringDashboard.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  const { data: roundStats } = trpc.analytics.getRoundTypeStats.useQuery(
    { roundId },
    { refetchInterval: 30_000 },
  )

  const stats = roundStats?.stats as {
    mentorAssignments: number
    totalMessages: number
  } | undefined

  const assignments = mentoringData?.assignments ?? []
  const activeMentors = mentoringData?.activeMentors ?? 0
  const totalMentors = mentoringData?.totalMentors ?? 0

  return (
    <div className="space-y-4">
      {/* Stats Cards */}
      {isLoading ? (
        <div className="grid grid-cols-3 gap-3">
          {[...Array(3)].map((_, i) => <Skeleton key={i} className="h-20 rounded-lg" />)}
        </div>
      ) : (
        <div className="grid grid-cols-3 gap-3">
          <Card className="p-3 text-center">
            <p className="text-xl font-semibold tabular-nums">
              {activeMentors}/{totalMentors}
            </p>
            <p className="text-xs text-muted-foreground mt-0.5">Active Mentors</p>
          </Card>
          <Card className="p-3 text-center">
            <p className="text-xl font-semibold tabular-nums">
              {mentoringData?.totalMessages ?? stats?.totalMessages ?? 0}
            </p>
            <p className="text-xs text-muted-foreground mt-0.5">Messages</p>
          </Card>
          <Card className="p-3 text-center">
            <p className="text-xl font-semibold tabular-nums">
              {stats?.mentorAssignments ?? assignments.length}
            </p>
            <p className="text-xs text-muted-foreground mt-0.5">Assignments</p>
          </Card>
        </div>
      )}

      {/* Mentor-Mentee Pairings */}
      <AnimatedCard index={1}>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="flex items-center gap-2 text-sm">
              <Users className="h-4 w-4 text-brand-teal" />
              Mentor-Mentee Pairings
            </CardTitle>
          </CardHeader>
          <CardContent>
            {assignments.length > 0 ? (
              <div className="space-y-2 max-h-[400px] overflow-y-auto -mr-2 pr-2">
                {assignments.map((mentor: any) => {
                  const isExpanded = expandedMentorId === mentor.mentorId
                  return (
                    <div key={mentor.mentorId} className="border rounded-lg">
                      <button
                        type="button"
                        className="w-full text-left px-3 py-2.5 hover:bg-muted/50 transition-colors rounded-lg"
                        onClick={() => setExpandedMentorId(isExpanded ? null : mentor.mentorId)}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <span className="text-sm font-medium">{mentor.mentorName}</span>
                            {mentor.projects?.some((p: any) => p.messageCount > 0) && (
                              <Badge variant="secondary" className="text-[10px] px-1.5">
                                Recently active
                              </Badge>
                            )}
                          </div>
                          <div className="flex items-center gap-2">
                            <Badge variant="outline" className="tabular-nums text-xs">
                              {mentor.projects?.length ?? 0} projects
                            </Badge>
                            {isExpanded
                              ? <ChevronUp className="h-3 w-3 text-muted-foreground" />
                              : <ChevronDown className="h-3 w-3 text-muted-foreground" />}
                          </div>
                        </div>
                      </button>
                      {isExpanded && mentor.projects && (
                        <div className="border-t divide-y">
                          {mentor.projects.map((proj: any) => (
                            <Link
                              key={proj.id}
                              href={`/observer/projects/${proj.id}` as Route}
                              className="flex items-center justify-between gap-2 px-3 py-2 hover:bg-muted/50 transition-colors"
                            >
                              <div className="min-w-0 flex-1">
                                <p className="text-sm truncate">{proj.title}</p>
                                <p className="text-xs text-muted-foreground truncate">
                                  {proj.teamName ?? ''}
                                </p>
                              </div>
                              <div className="flex items-center gap-1 shrink-0 text-xs text-muted-foreground">
                                <MessageCircle className="h-3 w-3" />
                                <span className="tabular-nums">{proj.messageCount}</span>
                              </div>
                            </Link>
                          ))}
                        </div>
                      )}
                    </div>
                  )
                })}
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">No mentor assignments yet.</p>
            )}
          </CardContent>
        </Card>
      </AnimatedCard>
    </div>
  )
}
