'use client'

import { useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import type { Route } from 'next'
import { useSession } from 'next-auth/react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { StatusTracker } from '@/components/shared/status-tracker'
import { MentorChat } from '@/components/shared/mentor-chat'
import {
  ArrowLeft,
  FileText,
  Clock,
  AlertCircle,
  AlertTriangle,
  Download,
  Video,
  File,
  Users,
  Crown,
  MessageSquare,
} from 'lucide-react'

const statusColors: Record<string, 'default' | 'success' | 'secondary' | 'destructive' | 'warning'> = {
  DRAFT: 'secondary',
  SUBMITTED: 'default',
  UNDER_REVIEW: 'default',
  ELIGIBLE: 'default',
  SEMIFINALIST: 'success',
  FINALIST: 'success',
  WINNER: 'success',
  REJECTED: 'destructive',
}

const fileTypeIcons: Record<string, typeof FileText> = {
  EXEC_SUMMARY: FileText,
  BUSINESS_PLAN: FileText,
  PRESENTATION: FileText,
  VIDEO_PITCH: Video,
  VIDEO: Video,
  OTHER: File,
  SUPPORTING_DOC: File,
}

const fileTypeLabels: Record<string, string> = {
  EXEC_SUMMARY: 'Executive Summary',
  BUSINESS_PLAN: 'Business Plan',
  PRESENTATION: 'Presentation',
  VIDEO_PITCH: 'Video Pitch',
  VIDEO: 'Video',
  OTHER: 'Other Document',
  SUPPORTING_DOC: 'Supporting Document',
}

export function SubmissionDetailClient() {
  const params = useParams()
  const router = useRouter()
  const { data: session } = useSession()
  const projectId = params.id as string
  const [activeTab, setActiveTab] = useState('details')

  const { data: statusData, isLoading, error } = trpc.applicant.getSubmissionStatus.useQuery(
    { projectId },
    { enabled: !!session?.user }
  )

  const { data: mentorMessages, isLoading: messagesLoading } = trpc.applicant.getMentorMessages.useQuery(
    { projectId },
    { enabled: !!session?.user && activeTab === 'mentor' }
  )

  const utils = trpc.useUtils()
  const sendMessage = trpc.applicant.sendMentorMessage.useMutation({
    onSuccess: () => {
      utils.applicant.getMentorMessages.invalidate({ projectId })
    },
  })

  if (isLoading) {
    return (
      <div className="max-w-4xl mx-auto space-y-6">
        <Skeleton className="h-9 w-40" />
        <Skeleton className="h-8 w-64" />
        <div className="grid gap-6 lg:grid-cols-3">
          <div className="lg:col-span-2 space-y-6">
            <Skeleton className="h-48 w-full" />
            <Skeleton className="h-64 w-full" />
          </div>
          <div>
            <Skeleton className="h-96 w-full" />
          </div>
        </div>
      </div>
    )
  }

  if (error || !statusData) {
    return (
      <div className="max-w-2xl mx-auto">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Error</AlertTitle>
          <AlertDescription>
            {error?.message || 'Submission not found'}
          </AlertDescription>
        </Alert>
        <Button className="mt-4" onClick={() => router.back()}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
      </div>
    )
  }

  const { project, timeline, currentStatus } = statusData
  const isDraft = !project.submittedAt

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      {/* Header */}
      <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 className="flex items-start justify-between">
        <div>
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-semibold tracking-tight">{project.title}</h1>
            <Badge variant={statusColors[currentStatus] || 'secondary'}>
              {currentStatus.replace('_', ' ')}
            </Badge>
          </div>
          <p className="text-muted-foreground">
            {project.program?.year ? `${project.program.year} Edition` : ''}{project.program?.name ? ` - ${project.program.name}` : ''}
          </p>
        </div>
      </div>

      {/* Draft warning */}
      {isDraft && (
        <Alert>
          <Clock className="h-4 w-4" />
          <AlertTitle>Draft Submission</AlertTitle>
          <AlertDescription>
            This submission has not been submitted yet. You can continue editing and submit when ready.
          </AlertDescription>
        </Alert>
      )}

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList>
          <TabsTrigger value="details">Details</TabsTrigger>
          <TabsTrigger value="documents">Documents</TabsTrigger>
          <TabsTrigger value="mentor" className="gap-1.5">
            <MessageSquare className="h-3.5 w-3.5" />
            Mentor
          </TabsTrigger>
        </TabsList>

        {/* Details Tab */}
        <TabsContent value="details">
          <div className="grid gap-6 lg:grid-cols-3">
            {/* Main content */}
            <div className="lg:col-span-2 space-y-6">
              {/* Project details */}
              <Card>
                <CardHeader>
                  <CardTitle>Project Details</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {project.teamName && (
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">Team/Organization</p>
                      <p>{project.teamName}</p>
                    </div>
                  )}
                  {project.description && (
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">Description</p>
                      <p className="whitespace-pre-wrap">{project.description}</p>
                    </div>
                  )}
                  {project.tags && project.tags.length > 0 && (
                    <div>
                      <p className="text-sm font-medium text-muted-foreground mb-2">Tags</p>
                      <div className="flex flex-wrap gap-2">
                        {project.tags.map((tag) => (
                          <Badge key={tag} variant="outline">
                            {tag}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* Metadata */}
              {project.metadataJson && Object.keys(project.metadataJson as Record<string, unknown>).length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle>Additional Information</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <dl className="space-y-3">
                      {Object.entries(project.metadataJson as Record<string, unknown>).map(([key, value]) => (
                        <div key={key} className="flex justify-between">
                          <dt className="text-sm font-medium text-muted-foreground capitalize">
                            {key.replace(/_/g, ' ')}
                          </dt>
                          <dd className="text-sm">{String(value)}</dd>
                        </div>
                      ))}
                    </dl>
                  </CardContent>
                </Card>
              )}
            </div>

            {/* Sidebar */}
            <div className="space-y-6">
              {/* Status timeline */}
              <Card>
                <CardHeader>
                  <CardTitle>Status Timeline</CardTitle>
                </CardHeader>
                <CardContent>
                  <StatusTracker
                    timeline={timeline}
                    currentStatus={currentStatus}
                  />
                </CardContent>
              </Card>

              {/* Dates */}
              <Card>
                <CardHeader>
                  <CardTitle>Key Dates</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">Created</span>
                    <span>{new Date(project.createdAt).toLocaleDateString()}</span>
                  </div>
                  {project.submittedAt && (
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-muted-foreground">Submitted</span>
                      <span>{new Date(project.submittedAt).toLocaleDateString()}</span>
                    </div>
                  )}
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">Last Updated</span>
                    <span>{new Date(project.updatedAt).toLocaleDateString()}</span>
                  </div>
                </CardContent>
              </Card>

              {/* Team Members */}
              {'teamMembers' in project && project.teamMembers && (
                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle className="flex items-center gap-2">
                        <Users className="h-5 w-5" />
                        Team
                      </CardTitle>
                      <Button variant="ghost" size="sm" asChild>
                        <Link href={`/my-submission/${projectId}/team` as Route}>
                          Manage
                        </Link>
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    {(project.teamMembers as Array<{ id: string; role: string; user: { name: string | null; email: string } }>).map((member) => (
                      <div key={member.id} className="flex items-center gap-3">
                        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-muted">
                          {member.role === 'LEAD' ? (
                            <Crown className="h-4 w-4 text-yellow-500" />
                          ) : (
                            <span className="text-xs font-medium">
                              {member.user.name?.charAt(0).toUpperCase() || '?'}
                            </span>
                          )}
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium truncate">
                            {member.user.name || member.user.email}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            {member.role === 'LEAD' ? 'Team Lead' : member.role === 'ADVISOR' ? 'Advisor' : 'Member'}
                          </p>
                        </div>
                      </div>
                    ))}
                  </CardContent>
                </Card>
              )}
            </div>
          </div>
        </TabsContent>

        {/* Documents Tab */}
        <TabsContent value="documents">
          <Card>
            <CardHeader>
              <CardTitle>Uploaded Documents</CardTitle>
              <CardDescription>
                Documents submitted with your application
              </CardDescription>
            </CardHeader>
            <CardContent>
              {project.files.length === 0 ? (
                <p className="text-muted-foreground text-center py-4">
                  No documents uploaded
                </p>
              ) : (
                <div className="space-y-2">
                  {project.files.map((file) => {
                    const Icon = fileTypeIcons[file.fileType] || File
                    const fileRecord = file as typeof file & { isLate?: boolean; roundId?: string | null }

                    return (
                      <div
                        key={file.id}
                        className="flex items-center justify-between p-3 rounded-lg border"
                      >
                        <div className="flex items-center gap-3">
                          <Icon className="h-5 w-5 text-muted-foreground" />
                          <div>
                            <div className="flex items-center gap-2">
                              <p className="font-medium">{file.fileName}</p>
                              {fileRecord.isLate && (
                                <Badge variant="warning" className="text-xs gap-1">
                                  <AlertTriangle className="h-3 w-3" />
                                  Submitted late
                                </Badge>
                              )}
                            </div>
                            <p className="text-sm text-muted-foreground">
                              {fileTypeLabels[file.fileType] || file.fileType}
                            </p>
                          </div>
                        </div>
                        <Button variant="ghost" size="sm" disabled>
                          <Download className="h-4 w-4" />
                        </Button>
                      </div>
                    )
                  })}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Mentor Tab */}
        <TabsContent value="mentor">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <MessageSquare className="h-5 w-5" />
                Mentor Communication
              </CardTitle>
              <CardDescription>
                Chat with your assigned mentor
              </CardDescription>
            </CardHeader>
            <CardContent>
              <MentorChat
                messages={mentorMessages || []}
                currentUserId={session?.user?.id || ''}
                onSendMessage={async (message) => {
                  await sendMessage.mutateAsync({ projectId, message })
                }}
                isLoading={messagesLoading}
                isSending={sendMessage.isPending}
              />
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
