'use client'

import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import {
  FileText,
  Video,
  Link as LinkIcon,
  File,
  Download,
  ExternalLink,
  BookOpen,
} from 'lucide-react'

const resourceTypeIcons = {
  PDF: FileText,
  VIDEO: Video,
  DOCUMENT: File,
  LINK: LinkIcon,
  OTHER: File,
}

const cohortColors = {
  ALL: 'bg-gray-100 text-gray-800',
  SEMIFINALIST: 'bg-blue-100 text-blue-800',
  FINALIST: 'bg-purple-100 text-purple-800',
}

export default function JuryLearningPage() {
  const [downloadingId, setDownloadingId] = useState<string | null>(null)

  const { data, isLoading } = trpc.learningResource.myResources.useQuery({})
  const utils = trpc.useUtils()

  const handleDownload = async (resourceId: string) => {
    setDownloadingId(resourceId)
    try {
      const { url } = await utils.learningResource.getDownloadUrl.fetch({ id: resourceId })
      window.open(url, '_blank')
    } catch (error) {
      console.error('Download failed:', error)
    } finally {
      setDownloadingId(null)
    }
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold">Learning Hub</h1>
          <p className="text-muted-foreground">
            Educational resources for jury members
          </p>
        </div>
        <div className="grid gap-4">
          {[1, 2, 3].map((i) => (
            <Card key={i}>
              <CardContent className="flex items-center gap-4 py-4">
                <Skeleton className="h-10 w-10 rounded-lg" />
                <div className="flex-1 space-y-2">
                  <Skeleton className="h-5 w-48" />
                  <Skeleton className="h-4 w-32" />
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    )
  }

  const resources = data?.resources || []
  const userCohortLevel = data?.userCohortLevel || 'ALL'

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Learning Hub</h1>
        <p className="text-muted-foreground">
          Educational resources for jury members
        </p>
        {userCohortLevel !== 'ALL' && (
          <Badge className={cohortColors[userCohortLevel]} variant="outline">
            Your access level: {userCohortLevel}
          </Badge>
        )}
      </div>

      {resources.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <BookOpen className="h-12 w-12 text-muted-foreground mb-4" />
            <h3 className="text-lg font-medium mb-2">No resources available</h3>
            <p className="text-muted-foreground">
              Check back later for learning materials
            </p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4">
          {resources.map((resource) => {
            const Icon = resourceTypeIcons[resource.resourceType]
            const isDownloading = downloadingId === resource.id

            return (
              <Card key={resource.id}>
                <CardContent className="flex items-center gap-4 py-4">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted shrink-0">
                    <Icon className="h-5 w-5" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="font-medium">{resource.title}</h3>
                    {resource.description && (
                      <p className="text-sm text-muted-foreground mt-1 line-clamp-2">
                        {resource.description}
                      </p>
                    )}
                    <div className="flex items-center gap-2 mt-2">
                      <Badge variant="outline" className={cohortColors[resource.cohortLevel]}>
                        {resource.cohortLevel}
                      </Badge>
                      <Badge variant="secondary">
                        {resource.resourceType}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    {resource.externalUrl ? (
                      <a
                        href={resource.externalUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <Button>
                          <ExternalLink className="mr-2 h-4 w-4" />
                          Open
                        </Button>
                      </a>
                    ) : resource.objectKey ? (
                      <Button
                        onClick={() => handleDownload(resource.id)}
                        disabled={isDownloading}
                      >
                        <Download className="mr-2 h-4 w-4" />
                        {isDownloading ? 'Loading...' : 'Download'}
                      </Button>
                    ) : null}
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      )}
    </div>
  )
}
