'use client'

import { Suspense, use, useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Checkbox } from '@/components/ui/checkbox'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Progress } from '@/components/ui/progress'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
  AlertTriangle,
  ArrowLeft,
  Bot,
  Check,
  Inbox,
  Loader2,
  Search,
  Sparkles,
  Users,
  UserPlus,
} from 'lucide-react'
import { getInitials, formatEnumLabel } from '@/lib/utils'

interface PageProps {
  params: Promise<{ id: string }>
}

function MentorAssignmentContent({ projectId }: { projectId: string }) {
  const router = useRouter()
  const utils = trpc.useUtils()
  const [search, setSearch] = useState('')
  const [pendingMentorId, setPendingMentorId] = useState<string | null>(null)
  const [unassignTarget, setUnassignTarget] = useState<{
    assignmentId: string
    mentorName: string
  } | null>(null)
  const [selectedCandidateIds, setSelectedCandidateIds] = useState<Set<string>>(
    new Set(),
  )

  const { data: project, isLoading: projectLoading } = trpc.project.get.useQuery({ id: projectId })

  // Already-assigned mentors (full list). Project.get spreads the underlying
  // `mentorAssignments` relation so we can read it directly.
  const assignedMentorAssignments = useMemo(() => {
    if (!project) return []
    // The Prisma relation is included via `...project` spread; type comes
    // through the tRPC client.
    type Assignment = NonNullable<typeof project>['mentorAssignments'][number]
    return ((project as unknown as { mentorAssignments?: Assignment[] }).mentorAssignments ?? []).filter(
      (a) => !a.droppedAt,
    )
  }, [project])
  const assignedMentorIds = useMemo(
    () => new Set(assignedMentorAssignments.map((a) => a.mentorId)),
    [assignedMentorAssignments],
  )

  const { data: candidatesData, isLoading: candidatesLoading } =
    trpc.mentor.getCandidates.useQuery({ projectId }, { enabled: !!project })

  const {
    data: suggestionsData,
    isLoading: suggestionsLoading,
    refetch: refetchSuggestions,
  } = trpc.mentor.getSuggestions.useQuery(
    { projectId, limit: 5 },
    { enabled: !!project },
  )

  const assignMutation = trpc.mentor.assign.useMutation({
    onSuccess: () => {
      toast.success('Mentor added')
      utils.project.get.invalidate({ id: projectId })
      utils.mentor.getCandidates.invalidate({ projectId })
      utils.mentor.getSuggestions.invalidate({ projectId })
      utils.mentor.getMentorPool.invalidate()
      setPendingMentorId(null)
    },
    onError: (err) => {
      toast.error(err.message)
      setPendingMentorId(null)
    },
  })

  const bulkAssignMutation = trpc.mentor.bulkAssign.useMutation({
    onSuccess: (result) => {
      if (result.totalAssigned === 0) {
        toast.info('No new assignments — every chosen mentor was already on this team.')
      } else {
        toast.success(
          `Added ${result.totalAssigned} mentor${
            result.totalAssigned === 1 ? '' : 's'
          } to this team${
            result.emailsSent > 0
              ? ` · ${result.emailsSent} email${result.emailsSent === 1 ? '' : 's'} sent`
              : ' · emails will go out when the mentoring round opens'
          }`,
        )
      }
      utils.project.get.invalidate({ id: projectId })
      utils.mentor.getCandidates.invalidate({ projectId })
      utils.mentor.getSuggestions.invalidate({ projectId })
      utils.mentor.getMentorPool.invalidate()
      setSelectedCandidateIds(new Set())
    },
    onError: (err) => toast.error(err.message),
  })

  const unassignMutation = trpc.mentor.unassign.useMutation({
    onSuccess: () => {
      toast.success('Mentor removed')
      utils.project.get.invalidate({ id: projectId })
      utils.mentor.getCandidates.invalidate({ projectId })
      utils.mentor.getSuggestions.invalidate({ projectId })
      setUnassignTarget(null)
    },
    onError: (err) => {
      toast.error(err.message)
      setUnassignTarget(null)
    },
  })

  const filteredCandidates = useMemo(() => {
    if (!candidatesData) return []
    const base = candidatesData.candidates.filter((c) => !assignedMentorIds.has(c.id))
    const q = search.trim().toLowerCase()
    if (!q) return base
    return base.filter((c) => {
      const hay = [c.name ?? '', c.email, ...(c.expertiseTags ?? []), c.country ?? '']
        .join(' ')
        .toLowerCase()
      return hay.includes(q)
    })
  }, [candidatesData, search, assignedMentorIds])

  const filteredSuggestions = useMemo(() => {
    if (!suggestionsData) return []
    return suggestionsData.suggestions.filter((s) => !assignedMentorIds.has(s.mentorId))
  }, [suggestionsData, assignedMentorIds])

  if (projectLoading) return <MentorAssignmentSkeleton />
  if (!project) {
    return (
      <Card>
        <CardContent className="py-12 text-center">
          <p>Project not found</p>
        </CardContent>
      </Card>
    )
  }

  const teamSize = project.teamMembers?.length ?? 0
  const aiSource = suggestionsData?.source ?? 'ai'

  const handleAssignManual = (mentorId: string) => {
    setPendingMentorId(mentorId)
    assignMutation.mutate({ projectId, mentorId, method: 'MANUAL' })
  }

  const handleAssignFromSuggestion = (
    mentorId: string,
    suggestion: {
      confidenceScore: number
      expertiseMatchScore: number
      reasoning: string
    },
  ) => {
    setPendingMentorId(mentorId)
    assignMutation.mutate({
      projectId,
      mentorId,
      method: aiSource === 'ai' ? 'AI_SUGGESTED' : 'ALGORITHM',
      aiConfidenceScore: suggestion.confidenceScore,
      expertiseMatchScore: suggestion.expertiseMatchScore,
      aiReasoning: suggestion.reasoning,
    })
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" className="-ml-4" onClick={() => router.back()}>
          <ArrowLeft className="mr-2 h-4 w-4" /> Back
        </Button>
      </div>

      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Mentor Assignment</h1>
        <p className="text-muted-foreground">{project.title}</p>
      </div>

      {/* ─── Project Context ─── */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Project Context</CardTitle>
          <CardDescription>What this project needs from a mentor</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 gap-x-6 gap-y-3 text-sm md:grid-cols-3">
            <div>
              <div className="text-muted-foreground text-xs uppercase tracking-wide">Ocean Issue</div>
              <div className="font-medium">
                {project.oceanIssue ? formatEnumLabel(project.oceanIssue) : '—'}
              </div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs uppercase tracking-wide">Category</div>
              <div className="font-medium">
                {project.competitionCategory ? formatEnumLabel(project.competitionCategory) : '—'}
              </div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs uppercase tracking-wide">Country</div>
              <div className="font-medium">{project.country ?? '—'}</div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs uppercase tracking-wide">Team Size</div>
              <div className="font-medium">{teamSize}</div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs uppercase tracking-wide">
                Mentoring Requested
              </div>
              <div className="font-medium">{project.wantsMentorship ? 'Yes' : 'No'}</div>
            </div>
          </div>
          {project.tags && project.tags.length > 0 && (
            <div className="mt-4">
              <div className="text-muted-foreground mb-1.5 text-xs uppercase tracking-wide">
                Project Tags
              </div>
              <div className="flex flex-wrap gap-1">
                {project.tags.map((tag: string) => (
                  <Badge key={tag} variant="secondary" className="text-xs">
                    {tag}
                  </Badge>
                ))}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* ─── Pending Change Requests ─── */}
      <PendingChangeRequestsPanel projectId={projectId} />

      {/* ─── Currently Assigned ─── */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Currently Assigned</CardTitle>
          <CardDescription>
            {assignedMentorAssignments.length === 0
              ? 'No mentors assigned yet'
              : `${assignedMentorAssignments.length} mentor${
                  assignedMentorAssignments.length === 1 ? '' : 's'
                } on this team`}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {assignedMentorAssignments.length === 0 ? (
            <div className="rounded-md border border-dashed py-8 text-center">
              <Users className="text-muted-foreground mx-auto mb-2 h-8 w-8" />
              <p className="text-muted-foreground text-sm">
                No mentors assigned yet — add one below.
              </p>
            </div>
          ) : (
            <ul className="divide-y">
              {assignedMentorAssignments.map((a) => {
                const m = a.mentor
                const tags = m.expertiseTags ?? []
                return (
                  <li
                    key={a.id}
                    className="flex items-start justify-between gap-4 py-4 first:pt-0 last:pb-0"
                  >
                    <div className="flex flex-1 items-start gap-4">
                      <Avatar className="h-12 w-12">
                        <AvatarFallback>
                          {getInitials(m.name || m.email)}
                        </AvatarFallback>
                      </Avatar>
                      <div className="min-w-0 flex-1">
                        <Link
                          href={`/admin/mentors/${m.id}`}
                          className="font-medium hover:underline"
                        >
                          {m.name || 'Unnamed'}
                        </Link>
                        <p className="text-muted-foreground text-sm">{m.email}</p>
                        {tags.length > 0 && (
                          <div className="mt-1 flex flex-wrap gap-1">
                            {tags.slice(0, 5).map((tag: string) => (
                              <Badge key={tag} variant="secondary" className="text-xs">
                                {tag}
                              </Badge>
                            ))}
                            {tags.length > 5 && (
                              <Badge variant="outline" className="text-xs">
                                +{tags.length - 5}
                              </Badge>
                            )}
                          </div>
                        )}
                        <p className="text-muted-foreground mt-2 text-xs">
                          Assigned{' '}
                          {new Date(a.assignedAt).toLocaleDateString(undefined, {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                          })}
                        </p>
                      </div>
                    </div>
                    <div className="flex flex-col items-end gap-2">
                      <Badge variant="outline" className="text-xs">
                        {a.method.replace(/_/g, ' ')}
                      </Badge>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() =>
                          setUnassignTarget({
                            assignmentId: a.id,
                            mentorName: m.name || m.email,
                          })
                        }
                        disabled={unassignMutation.isPending}
                      >
                        Unassign
                      </Button>
                    </div>
                  </li>
                )
              })}
            </ul>
          )}
        </CardContent>
      </Card>

      {/* ─── Add a Mentor ─── */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <UserPlus className="h-5 w-5" />
            Add a Mentor
          </CardTitle>
          <CardDescription>
            Stack additional mentors on this team. Browse all eligible mentors or use AI to surface the best fits.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Tabs defaultValue="manual" className="space-y-4">
            <TabsList>
              <TabsTrigger value="manual">
                <Users className="mr-2 h-4 w-4" /> Manual Picker
              </TabsTrigger>
              <TabsTrigger value="ai">
                <Sparkles className="mr-2 h-4 w-4" /> AI Suggestions
              </TabsTrigger>
            </TabsList>

            <TabsContent value="manual" className="space-y-4">
              <div className="relative">
                <Search className="text-muted-foreground absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2" />
                <Input
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder="Search by name, email, country, or expertise tag…"
                  className="pl-9"
                />
              </div>
              {selectedCandidateIds.size > 0 && (
                <div className="flex flex-col gap-2 rounded-md border border-primary/30 bg-primary/5 px-4 py-2.5 text-sm sm:flex-row sm:items-center sm:justify-between">
                  <div>
                    <span className="font-medium">{selectedCandidateIds.size}</span>{' '}
                    <span className="text-muted-foreground">
                      mentor{selectedCandidateIds.size === 1 ? '' : 's'} selected
                    </span>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    <Button
                      size="sm"
                      onClick={() =>
                        bulkAssignMutation.mutate({
                          mentorIds: Array.from(selectedCandidateIds),
                          projectIds: [projectId],
                        })
                      }
                      disabled={bulkAssignMutation.isPending}
                    >
                      {bulkAssignMutation.isPending && (
                        <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
                      )}
                      Add {selectedCandidateIds.size} mentor
                      {selectedCandidateIds.size === 1 ? '' : 's'}
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => setSelectedCandidateIds(new Set())}
                    >
                      Clear
                    </Button>
                  </div>
                </div>
              )}
              {candidatesLoading ? (
                <div className="space-y-2">
                  {[1, 2, 3].map((i) => (
                    <Skeleton key={i} className="h-14 w-full" />
                  ))}
                </div>
              ) : filteredCandidates.length === 0 ? (
                <div className="text-muted-foreground py-8 text-center text-sm">
                  {assignedMentorIds.size > 0 && search.trim() === ''
                    ? 'All eligible mentors are already assigned.'
                    : 'No matching mentors. Try a different search.'}
                </div>
              ) : (
                <div className="overflow-hidden rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-10">
                          <Checkbox
                            checked={
                              filteredCandidates.length > 0 &&
                              filteredCandidates.every((c) =>
                                selectedCandidateIds.has(c.id),
                              )
                            }
                            onCheckedChange={(checked) => {
                              setSelectedCandidateIds((prev) => {
                                const next = new Set(prev)
                                if (checked) {
                                  filteredCandidates.forEach((c) => next.add(c.id))
                                } else {
                                  filteredCandidates.forEach((c) => next.delete(c.id))
                                }
                                return next
                              })
                            }}
                            aria-label="Select all visible mentors"
                          />
                        </TableHead>
                        <TableHead>Mentor</TableHead>
                        <TableHead>Expertise</TableHead>
                        <TableHead>Country</TableHead>
                        <TableHead className="text-right">Load</TableHead>
                        <TableHead className="text-right">Overlap</TableHead>
                        <TableHead></TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredCandidates.map((c) => (
                        <TableRow
                          key={c.id}
                          data-state={
                            selectedCandidateIds.has(c.id) ? 'selected' : undefined
                          }
                        >
                          <TableCell>
                            <Checkbox
                              checked={selectedCandidateIds.has(c.id)}
                              onCheckedChange={(checked) =>
                                setSelectedCandidateIds((prev) => {
                                  const next = new Set(prev)
                                  if (checked) next.add(c.id)
                                  else next.delete(c.id)
                                  return next
                                })
                              }
                              aria-label={`Select ${c.name ?? c.email}`}
                            />
                          </TableCell>
                          <TableCell>
                            <div className="font-medium">{c.name ?? 'Unnamed'}</div>
                            <div className="text-muted-foreground text-xs">{c.email}</div>
                          </TableCell>
                          <TableCell>
                            <div className="flex flex-wrap gap-1">
                              {c.expertiseTags.slice(0, 4).map((tag) => (
                                <Badge key={tag} variant="secondary" className="text-xs">
                                  {tag}
                                </Badge>
                              ))}
                              {c.expertiseTags.length > 4 && (
                                <Badge variant="outline" className="text-xs">
                                  +{c.expertiseTags.length - 4}
                                </Badge>
                              )}
                            </div>
                          </TableCell>
                          <TableCell className="text-sm">{c.country ?? '—'}</TableCell>
                          <TableCell className="text-right text-sm tabular-nums">
                            {c.currentAssignments}
                            {c.maxAssignments != null ? `/${c.maxAssignments}` : ''}
                          </TableCell>
                          <TableCell className="text-right">
                            <Badge
                              variant={
                                c.overlapScore >= 0.5
                                  ? 'default'
                                  : c.overlapScore > 0
                                    ? 'secondary'
                                    : 'outline'
                              }
                              className="text-xs tabular-nums"
                            >
                              {Math.round(c.overlapScore * 100)}%
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Button
                              size="sm"
                              onClick={() => handleAssignManual(c.id)}
                              disabled={assignMutation.isPending}
                            >
                              {assignMutation.isPending && pendingMentorId === c.id ? (
                                <Loader2 className="h-4 w-4 animate-spin" />
                              ) : (
                                <>
                                  <Check className="mr-1 h-3.5 w-3.5" /> Add
                                </>
                              )}
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </TabsContent>

            <TabsContent value="ai" className="space-y-4">
              {aiSource === 'fallback' && (
                <div className="flex items-start gap-3 rounded-md border border-amber-300 bg-amber-50 p-3 text-sm">
                  <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600" />
                  <div>
                    <p className="font-medium">AI matching unavailable</p>
                    <p className="text-muted-foreground">
                      Showing expertise-tag overlap instead. Configure{' '}
                      <code>OPENAI_API_KEY</code> to enable AI matching.
                    </p>
                  </div>
                </div>
              )}
              <div className="flex items-center justify-end">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => refetchSuggestions()}
                  disabled={suggestionsLoading}
                >
                  {suggestionsLoading ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    'Refresh'
                  )}
                </Button>
              </div>
              {suggestionsLoading ? (
                <div className="space-y-3">
                  {[1, 2, 3].map((i) => (
                    <Skeleton key={i} className="h-24 w-full" />
                  ))}
                </div>
              ) : filteredSuggestions.length === 0 ? (
                <p className="text-muted-foreground py-8 text-center text-sm">
                  {assignedMentorIds.size > 0
                    ? 'All top suggestions are already assigned.'
                    : 'No suggestions available.'}
                </p>
              ) : (
                <div className="space-y-3">
                  {filteredSuggestions.map((s, i) => (
                    <div
                      key={s.mentorId}
                      className="flex items-start justify-between rounded-md border p-4"
                    >
                      <div className="flex flex-1 gap-3">
                        <div className="relative">
                          <Avatar className="h-12 w-12">
                            <AvatarFallback>
                              {s.mentor
                                ? getInitials(s.mentor.name || s.mentor.email)
                                : '?'}
                            </AvatarFallback>
                          </Avatar>
                          {i === 0 && (
                            <div className="bg-primary text-primary-foreground absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold">
                              1
                            </div>
                          )}
                        </div>
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-2">
                            <p className="font-medium">{s.mentor?.name || 'Unnamed'}</p>
                            <Badge variant="outline" className="gap-1 text-xs">
                              <Bot className="h-3 w-3" />{' '}
                              {aiSource === 'ai' ? 'AI' : 'Tag overlap'}
                            </Badge>
                          </div>
                          <p className="text-muted-foreground text-sm">{s.mentor?.email}</p>
                          {s.mentor?.expertiseTags && s.mentor.expertiseTags.length > 0 && (
                            <div className="mt-2 flex flex-wrap gap-1">
                              {s.mentor.expertiseTags.slice(0, 5).map((tag) => (
                                <Badge key={tag} variant="secondary" className="text-xs">
                                  {tag}
                                </Badge>
                              ))}
                            </div>
                          )}
                          <div className="mt-3 space-y-1.5">
                            <div className="flex items-center gap-2 text-xs">
                              <span className="text-muted-foreground w-28">Confidence:</span>
                              <Progress value={s.confidenceScore * 100} className="h-1.5 flex-1" />
                              <span className="w-10 text-right tabular-nums">
                                {Math.round(s.confidenceScore * 100)}%
                              </span>
                            </div>
                            <div className="flex items-center gap-2 text-xs">
                              <span className="text-muted-foreground w-28">
                                Expertise Match:
                              </span>
                              <Progress
                                value={s.expertiseMatchScore * 100}
                                className="h-1.5 flex-1"
                              />
                              <span className="w-10 text-right tabular-nums">
                                {Math.round(s.expertiseMatchScore * 100)}%
                              </span>
                            </div>
                          </div>
                          {s.reasoning && (
                            <p className="text-muted-foreground mt-2 text-xs italic">
                              &quot;{s.reasoning}&quot;
                            </p>
                          )}
                        </div>
                      </div>
                      <Button
                        size="sm"
                        onClick={() => handleAssignFromSuggestion(s.mentorId, s)}
                        disabled={assignMutation.isPending}
                      >
                        {assignMutation.isPending && pendingMentorId === s.mentorId ? (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                          <>
                            <Check className="mr-1 h-3.5 w-3.5" /> Add
                          </>
                        )}
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>

      {/* ─── Unassign confirm ─── */}
      <AlertDialog
        open={!!unassignTarget}
        onOpenChange={(open) => {
          if (!open) setUnassignTarget(null)
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Unassign mentor?</AlertDialogTitle>
            <AlertDialogDescription>
              {unassignTarget
                ? `Remove ${unassignTarget.mentorName} from this team? Other co-mentors will remain.`
                : ''}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={unassignMutation.isPending}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={(e) => {
                e.preventDefault()
                if (!unassignTarget) return
                unassignMutation.mutate({ assignmentId: unassignTarget.assignmentId })
              }}
              disabled={unassignMutation.isPending}
            >
              {unassignMutation.isPending ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                'Unassign'
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}

// ─────────────────────────────────────────────────────────────────────────────
// Pending Change Requests panel
// ─────────────────────────────────────────────────────────────────────────────

function PendingChangeRequestsPanel({ projectId }: { projectId: string }) {
  const utils = trpc.useUtils()
  const { data: requests, isLoading } = trpc.mentor.listChangeRequests.useQuery({
    projectId,
    status: 'PENDING',
  })

  const [resolveTarget, setResolveTarget] = useState<{
    id: string
    status: 'RESOLVED' | 'DISMISSED'
    requesterName: string
  } | null>(null)
  const [resolutionNote, setResolutionNote] = useState('')

  const resolveMutation = trpc.mentor.resolveChangeRequest.useMutation({
    onSuccess: (_, variables) => {
      toast.success(
        `Request marked ${variables.status === 'RESOLVED' ? 'resolved' : 'dismissed'}`,
      )
      utils.mentor.listChangeRequests.invalidate()
      setResolveTarget(null)
      setResolutionNote('')
    },
    onError: (err) => toast.error(err.message),
  })

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Inbox className="h-5 w-5" />
            Pending change requests
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Skeleton className="h-24 w-full" />
        </CardContent>
      </Card>
    )
  }

  if (!requests || requests.length === 0) {
    return null
  }

  return (
    <>
      <Card className="border-amber-300">
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Inbox className="h-5 w-5 text-amber-600" />
            Pending change requests
            <Badge variant="secondary" className="ml-1">
              {requests.length}
            </Badge>
          </CardTitle>
          <CardDescription>
            Team members or mentors have asked admin to change a mentor on this team.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <ul className="space-y-3">
            {requests.map((r) => (
              <ChangeRequestRow
                key={r.id}
                request={r}
                onResolve={(status) =>
                  setResolveTarget({
                    id: r.id,
                    status,
                    requesterName:
                      r.requestedBy?.name ?? r.requestedBy?.email ?? 'Unknown',
                  })
                }
              />
            ))}
          </ul>
        </CardContent>
      </Card>

      <Dialog
        open={!!resolveTarget}
        onOpenChange={(open) => {
          if (!open) {
            setResolveTarget(null)
            setResolutionNote('')
          }
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {resolveTarget?.status === 'RESOLVED'
                ? 'Mark request resolved'
                : 'Dismiss request'}
            </DialogTitle>
            <DialogDescription>
              {resolveTarget?.status === 'RESOLVED'
                ? `You've taken action on the request from ${resolveTarget?.requesterName}. Optionally add a note explaining what was done.`
                : `Close the request from ${resolveTarget?.requesterName} without action. Optionally add a note explaining why.`}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-2">
            <Label htmlFor="resolution-note">Resolution note (optional)</Label>
            <Textarea
              id="resolution-note"
              value={resolutionNote}
              onChange={(e) => setResolutionNote(e.target.value)}
              placeholder="e.g. Replaced Jane with John based on expertise mismatch."
              rows={4}
              maxLength={2000}
            />
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setResolveTarget(null)
                setResolutionNote('')
              }}
              disabled={resolveMutation.isPending}
            >
              Cancel
            </Button>
            <Button
              onClick={() => {
                if (!resolveTarget) return
                resolveMutation.mutate({
                  id: resolveTarget.id,
                  status: resolveTarget.status,
                  resolutionNote: resolutionNote.trim() || undefined,
                })
              }}
              disabled={resolveMutation.isPending}
            >
              {resolveMutation.isPending ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : resolveTarget?.status === 'RESOLVED' ? (
                'Mark Resolved'
              ) : (
                'Dismiss'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}

type ChangeRequestRowProps = {
  request: {
    id: string
    reason: string
    createdAt: Date
    requestedBy: { id: string; name: string | null; email: string } | null
    targetAssignment: {
      id: string
      mentor: { id: string; name: string | null; email: string }
    } | null
  }
  onResolve: (status: 'RESOLVED' | 'DISMISSED') => void
}

function ChangeRequestRow({ request, onResolve }: ChangeRequestRowProps) {
  const [expanded, setExpanded] = useState(false)
  const reasonIsLong = request.reason.length > 240
  return (
    <li className="rounded-md border bg-card p-4">
      <div className="flex items-start justify-between gap-4">
        <div className="min-w-0 flex-1 space-y-2">
          <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
            <span className="font-medium">
              {request.requestedBy?.name ?? request.requestedBy?.email ?? 'Unknown'}
            </span>
            {request.requestedBy?.email && request.requestedBy.name && (
              <span className="text-muted-foreground text-xs">
                {request.requestedBy.email}
              </span>
            )}
            <span className="text-muted-foreground text-xs">
              ·{' '}
              {new Date(request.createdAt).toLocaleDateString(undefined, {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
              })}
            </span>
          </div>
          {request.targetAssignment && (
            <div className="text-muted-foreground text-xs">
              About:{' '}
              <span className="font-medium">
                {request.targetAssignment.mentor.name ||
                  request.targetAssignment.mentor.email}
              </span>
            </div>
          )}
          <p
            className={
              expanded || !reasonIsLong
                ? 'text-sm whitespace-pre-wrap'
                : 'text-sm whitespace-pre-wrap line-clamp-4'
            }
          >
            {request.reason}
          </p>
          {reasonIsLong && (
            <button
              type="button"
              className="text-primary text-xs hover:underline"
              onClick={() => setExpanded((v) => !v)}
            >
              {expanded ? 'Show less' : 'Show more'}
            </button>
          )}
        </div>
        <div className="flex shrink-0 flex-col gap-2">
          <Button size="sm" onClick={() => onResolve('RESOLVED')}>
            Mark Resolved
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() => onResolve('DISMISSED')}
          >
            Dismiss
          </Button>
        </div>
      </div>
    </li>
  )
}

function MentorAssignmentSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-9 w-36" />
      <div className="space-y-2">
        <Skeleton className="h-8 w-64" />
        <Skeleton className="h-4 w-48" />
      </div>
      <Card>
        <CardHeader>
          <Skeleton className="h-6 w-48" />
        </CardHeader>
        <CardContent>
          <Skeleton className="h-32 w-full" />
        </CardContent>
      </Card>
    </div>
  )
}

export default function MentorAssignmentPage({ params }: PageProps) {
  const { id } = use(params)
  return (
    <Suspense fallback={<MentorAssignmentSkeleton />}>
      <MentorAssignmentContent projectId={id} />
    </Suspense>
  )
}
