'use client'

import { useParams } 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 { StatusTracker } from '@/components/shared/status-tracker'
import {
  ArrowLeft,
  FileText,
  Clock,
  AlertCircle,
  Download,
  Video,
  File,
  Users,
  Crown,
} 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 { data: session } = useSession()
  const projectId = params.id as string

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

  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 asChild className="mt-4">
          <Link href="/my-submission">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to My Submissions
          </Link>
        </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" asChild className="-ml-4">
          <Link href="/my-submission">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to My Submissions
          </Link>
        </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.roundProjects?.[0]?.round?.program?.year ? `${project.roundProjects[0].round.program.year} Edition` : ''}{project.roundProjects?.[0]?.round?.name ? ` - ${project.roundProjects[0].round.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>
      )}

      <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>

          {/* Files */}
          <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

                    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>
                            <p className="font-medium">{file.fileName}</p>
                            <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>

          {/* 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>
    </div>
  )
}
