'use client'

import { useParams, useRouter } from 'next/navigation'
import { useSession } from 'next-auth/react'
import { trpc } from '@/lib/trpc/client'
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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import { WorkspaceChat } from '@/components/mentor/workspace-chat'
import { FilePromotionPanel } from '@/components/mentor/file-promotion-panel'
import { WorkspaceFilesPanel } from '@/components/mentor/workspace-files-panel'
import { FinalDocumentsPanel } from '@/components/applicant/final-documents-panel'
import { ArrowLeft, MessageSquare, FileText, Upload, Users } from 'lucide-react'
import { toast } from 'sonner'

export default function MentorWorkspaceDetailPage() {
  const params = useParams()
  const router = useRouter()
  const { data: session } = useSession()
  const projectId = params.projectId as string

  // Get mentor assignment for this project
  const { data: assignments } = trpc.mentor.getMyProjects.useQuery()
  const assignment = assignments?.find(a => a.projectId === projectId)

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

  // Co-mentor visibility (PR8 multi-mentor): show who else is on the team.
  // Gracefully tolerates stale tabs where the caller no longer has access
  // (assignment dropped) — query just returns nothing in that case.
  const { data: projectMentors } = trpc.mentor.getProjectMentors.useQuery(
    { projectId },
    { enabled: !!projectId, retry: false }
  )

  const currentUserId = session?.user?.id
  const coMentors = (projectMentors ?? []).filter(
    a => a.mentor.id !== currentUserId
  )
  const coMentorNames = coMentors.map(a => a.mentor.name ?? 'Unnamed mentor')
  const visibleCoMentors = coMentorNames.slice(0, 3)
  const hiddenCoMentors = coMentorNames.slice(3)

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-64" />
        <Skeleton className="h-96" />
      </div>
    )
  }

  if (!project) {
    return (
      <div className="space-y-6">
        <Button variant="ghost" size="sm" onClick={() => router.back()}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <FileText className="h-12 w-12 text-muted-foreground/50 mb-3" />
            <p className="font-medium">Project not found</p>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" onClick={() => router.back()}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
        <div className="flex-1">
          <div className="flex items-center gap-3 flex-wrap">
            <h1 className="text-2xl font-bold tracking-tight">{project.title}</h1>
            {project.status && (
              <Badge variant="secondary">{project.status}</Badge>
            )}
          </div>
          {project.teamName && (
            <p className="text-muted-foreground mt-1">{project.teamName}</p>
          )}
          {coMentors.length > 0 && (
            <div className="mt-2 flex items-center gap-1.5 text-sm text-muted-foreground">
              <Users className="h-3.5 w-3.5 shrink-0" />
              <span>
                You + {coMentors.length} co-mentor
                {coMentors.length === 1 ? '' : 's'}:{' '}
                <span className="text-foreground">
                  {visibleCoMentors.join(', ')}
                </span>
                {hiddenCoMentors.length > 0 && (
                  <>
                    {' '}
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <span className="cursor-help underline decoration-dotted underline-offset-2">
                            +{hiddenCoMentors.length} more
                          </span>
                        </TooltipTrigger>
                        <TooltipContent>
                          <div className="text-xs">
                            {hiddenCoMentors.join(', ')}
                          </div>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  </>
                )}
              </span>
            </div>
          )}
        </div>
      </div>

      <Tabs defaultValue="chat" className="w-full">
        <TabsList className="w-full sm:w-auto grid grid-cols-3 sm:inline-grid">
          <TabsTrigger value="chat" className="flex items-center gap-2">
            <MessageSquare className="h-4 w-4" />
            <span className="hidden sm:inline">Chat</span>
          </TabsTrigger>
          <TabsTrigger value="files" className="flex items-center gap-2">
            <FileText className="h-4 w-4" />
            <span className="hidden sm:inline">Files</span>
          </TabsTrigger>
          <TabsTrigger value="promotion" className="flex items-center gap-2">
            <Upload className="h-4 w-4" />
            <span className="hidden sm:inline">Promotion</span>
          </TabsTrigger>
        </TabsList>

        <TabsContent value="chat" className="mt-6">
          {assignment ? (
            <WorkspaceChat mentorAssignmentId={assignment.id} />
          ) : (
            <Card>
              <CardContent className="text-center py-8">
                <MessageSquare className="h-12 w-12 text-muted-foreground/50 mx-auto mb-3" />
                <p className="text-sm text-muted-foreground">Loading workspace...</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="files" className="mt-6">
          {assignment ? (
            <WorkspaceFilesPanel
              projectId={projectId}
              mentorAssignmentId={assignment.id}
            />
          ) : (
            <Card>
              <CardContent className="text-center py-8">
                <FileText className="h-12 w-12 text-muted-foreground/50 mx-auto mb-3" />
                <p className="text-sm text-muted-foreground">Loading workspace…</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="promotion" className="mt-6">
          {assignment ? (
            <FilePromotionPanel projectId={projectId} />
          ) : (
            <Card>
              <CardContent className="text-center py-8">
                <Upload className="h-12 w-12 text-muted-foreground/50 mx-auto mb-3" />
                <p className="text-sm text-muted-foreground">Loading workspace...</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>

      {/* Final Documents (self-hides when not a finalist) */}
      <FinalDocumentsPanel variant="mentor" projectId={projectId} />
    </div>
  )
}
