'use client'

import { useState, useMemo } from 'react'
import { useDebounce } from '@/hooks/use-debounce'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Plus,
  FileText,
  Video,
  Link as LinkIcon,
  File,
  Pencil,
  ExternalLink,
  Search,
} from 'lucide-react'

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

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

export default function LearningHubPage() {
  const { data, isLoading } = trpc.learningResource.list.useQuery({ perPage: 50 })
  const resources = data?.data

  const [search, setSearch] = useState('')
  const debouncedSearch = useDebounce(search, 300)
  const [typeFilter, setTypeFilter] = useState('all')
  const [cohortFilter, setCohortFilter] = useState('all')

  const filteredResources = useMemo(() => {
    if (!resources) return []
    return resources.filter((resource) => {
      const matchesSearch =
        !debouncedSearch ||
        resource.title.toLowerCase().includes(debouncedSearch.toLowerCase())
      const matchesType = typeFilter === 'all' || resource.resourceType === typeFilter
      const matchesCohort = cohortFilter === 'all' || resource.cohortLevel === cohortFilter
      return matchesSearch && matchesType && matchesCohort
    })
  }, [resources, debouncedSearch, typeFilter, cohortFilter])

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <Skeleton className="h-8 w-48" />
            <Skeleton className="mt-2 h-4 w-72" />
          </div>
          <Skeleton className="h-9 w-32" />
        </div>
        {/* Toolbar skeleton */}
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <Skeleton className="h-10 flex-1" />
          <div className="flex items-center gap-2">
            <Skeleton className="h-10 w-[160px]" />
            <Skeleton className="h-10 w-[160px]" />
          </div>
        </div>
        {/* Resource list skeleton */}
        <div className="grid gap-4">
          {[...Array(5)].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>
                <Skeleton className="h-8 w-8 rounded" />
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Learning Hub</h1>
          <p className="text-muted-foreground">
            Manage educational resources for jury members
          </p>
        </div>
        <Link href="/admin/learning/new">
          <Button>
            <Plus className="mr-2 h-4 w-4" />
            Add Resource
          </Button>
        </Link>
      </div>

      {/* Toolbar */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search resources..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9"
          />
        </div>
        <div className="flex items-center gap-2">
          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger className="w-[160px]">
              <SelectValue placeholder="All types" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All types</SelectItem>
              <SelectItem value="PDF">PDF</SelectItem>
              <SelectItem value="VIDEO">Video</SelectItem>
              <SelectItem value="DOCUMENT">Document</SelectItem>
              <SelectItem value="LINK">Link</SelectItem>
              <SelectItem value="OTHER">Other</SelectItem>
            </SelectContent>
          </Select>
          <Select value={cohortFilter} onValueChange={setCohortFilter}>
            <SelectTrigger className="w-[160px]">
              <SelectValue placeholder="All cohorts" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All cohorts</SelectItem>
              <SelectItem value="ALL">All (cohort)</SelectItem>
              <SelectItem value="SEMIFINALIST">Semifinalist</SelectItem>
              <SelectItem value="FINALIST">Finalist</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Results count */}
      {resources && (
        <p className="text-sm text-muted-foreground">
          {filteredResources.length} of {resources.length} resources
        </p>
      )}

      {/* Resource List */}
      {filteredResources.length > 0 ? (
        <div className="grid gap-4">
          {filteredResources.map((resource) => {
            const Icon = resourceTypeIcons[resource.resourceType as keyof typeof resourceTypeIcons] || File
            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">
                    <Icon className="h-5 w-5" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <h3 className="font-medium truncate">{resource.title}</h3>
                      {!resource.isPublished && (
                        <Badge variant="secondary">Draft</Badge>
                      )}
                    </div>
                    <div className="flex items-center gap-2 text-sm text-muted-foreground">
                      <Badge className={cohortColors[resource.cohortLevel] || ''} variant="outline">
                        {resource.cohortLevel}
                      </Badge>
                      <span>{resource.resourceType}</span>
                      <span>-</span>
                      <span>{resource._count.accessLogs} views</span>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    {resource.externalUrl && (
                      <a
                        href={resource.externalUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <Button variant="ghost" size="icon">
                          <ExternalLink className="h-4 w-4" />
                        </Button>
                      </a>
                    )}
                    <Link href={`/admin/learning/${resource.id}`}>
                      <Button variant="ghost" size="icon">
                        <Pencil className="h-4 w-4" />
                      </Button>
                    </Link>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      ) : resources && resources.length > 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-8 text-center">
            <Search className="h-8 w-8 text-muted-foreground/40" />
            <p className="mt-2 text-sm text-muted-foreground">
              No resources match your filters
            </p>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <FileText className="h-12 w-12 text-muted-foreground/40" />
            <h3 className="mt-3 text-lg font-medium">No resources yet</h3>
            <p className="mt-1 text-sm text-muted-foreground max-w-sm">
              Add learning materials like videos, documents, and links for program participants.
            </p>
            <Button className="mt-4" asChild>
              <Link href="/admin/learning/new">
                <Plus className="mr-2 h-4 w-4" />
                Add Resource
              </Link>
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
