'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,
  Pencil,
  ExternalLink,
  Building2,
  Eye,
  EyeOff,
  Globe,
  Search,
} from 'lucide-react'

const visibilityIcons = {
  ADMIN_ONLY: EyeOff,
  JURY_VISIBLE: Eye,
  PUBLIC: Globe,
}

const partnerTypeColors: Record<string, string> = {
  SPONSOR: 'bg-yellow-100 text-yellow-800',
  PARTNER: 'bg-blue-100 text-blue-800',
  SUPPORTER: 'bg-green-100 text-green-800',
  MEDIA: 'bg-purple-100 text-purple-800',
  OTHER: 'bg-gray-100 text-gray-800',
}

export default function PartnersPage() {
  const { data, isLoading } = trpc.partner.list.useQuery({ perPage: 50 })
  const partners = data?.data

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

  const filteredPartners = useMemo(() => {
    if (!partners) return []
    return partners.filter((partner) => {
      const matchesSearch =
        !debouncedSearch ||
        partner.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        partner.description?.toLowerCase().includes(debouncedSearch.toLowerCase())
      const matchesType = typeFilter === 'all' || partner.partnerType === typeFilter
      const matchesActive =
        activeFilter === 'all' ||
        (activeFilter === 'active' && partner.isActive) ||
        (activeFilter === 'inactive' && !partner.isActive)
      return matchesSearch && matchesType && matchesActive
    })
  }, [partners, debouncedSearch, typeFilter, activeFilter])

  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>
        {/* Partner cards skeleton */}
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {[...Array(6)].map((_, i) => (
            <Card key={i}>
              <CardContent className="p-4">
                <div className="flex items-start gap-4">
                  <Skeleton className="h-12 w-12 rounded-lg" />
                  <div className="flex-1 space-y-2">
                    <Skeleton className="h-5 w-32" />
                    <Skeleton className="h-4 w-20" />
                    <Skeleton className="h-4 w-full" />
                  </div>
                </div>
              </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">Partners</h1>
          <p className="text-muted-foreground">
            Manage partner and sponsor organizations
          </p>
        </div>
        <Link href="/admin/partners/new">
          <Button>
            <Plus className="mr-2 h-4 w-4" />
            Add Partner
          </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 partners..."
            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="SPONSOR">Sponsor</SelectItem>
              <SelectItem value="PARTNER">Partner</SelectItem>
              <SelectItem value="SUPPORTER">Supporter</SelectItem>
              <SelectItem value="MEDIA">Media</SelectItem>
              <SelectItem value="OTHER">Other</SelectItem>
            </SelectContent>
          </Select>
          <Select value={activeFilter} onValueChange={setActiveFilter}>
            <SelectTrigger className="w-[160px]">
              <SelectValue placeholder="All statuses" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All statuses</SelectItem>
              <SelectItem value="active">Active</SelectItem>
              <SelectItem value="inactive">Inactive</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

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

      {/* Partners Grid */}
      {filteredPartners.length > 0 ? (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filteredPartners.map((partner) => {
            const VisibilityIcon = visibilityIcons[partner.visibility as keyof typeof visibilityIcons] || Eye
            return (
              <Card key={partner.id} className={!partner.isActive ? 'opacity-60' : ''}>
                <CardContent className="p-4">
                  <div className="flex items-start gap-4">
                    <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-muted shrink-0">
                      <Building2 className="h-6 w-6" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <h3 className="font-medium truncate">{partner.name}</h3>
                        {!partner.isActive && (
                          <Badge variant="secondary">Inactive</Badge>
                        )}
                      </div>
                      <div className="flex items-center gap-2 mt-1">
                        <Badge className={partnerTypeColors[partner.partnerType] || ''} variant="outline">
                          {partner.partnerType}
                        </Badge>
                        <VisibilityIcon className="h-3 w-3 text-muted-foreground" />
                      </div>
                      {partner.description && (
                        <p className="text-sm text-muted-foreground mt-2 line-clamp-2">
                          {partner.description}
                        </p>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center justify-end gap-2 mt-4 pt-4 border-t">
                    {partner.website && (
                      <a
                        href={partner.website}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <Button variant="ghost" size="sm">
                          <ExternalLink className="h-4 w-4 mr-1" />
                          Website
                        </Button>
                      </a>
                    )}
                    <Link href={`/admin/partners/${partner.id}`}>
                      <Button variant="ghost" size="sm">
                        <Pencil className="h-4 w-4 mr-1" />
                        Edit
                      </Button>
                    </Link>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      ) : partners && partners.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 partners match your filters
            </p>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <Building2 className="h-12 w-12 text-muted-foreground/40" />
            <h3 className="mt-3 text-lg font-medium">No partners yet</h3>
            <p className="mt-1 text-sm text-muted-foreground max-w-sm">
              Add sponsor and partner organizations to showcase on the platform.
            </p>
            <Button className="mt-4" asChild>
              <Link href="/admin/partners/new">
                <Plus className="mr-2 h-4 w-4" />
                Add Partner
              </Link>
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
