'use client'

import { useEffect, useState, useCallback } from 'react'
import type { Game } from '@/types'
import GameDetailModal from './GameDetailModal'
import FilterPanel from '@/components/FilterPanel'

interface Props {
  libraryId: string
}

export default function GamesView({ libraryId }: Props) {
  const [games, setGames] = useState<Game[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [selected, setSelected] = useState<Game | null>(null)
  const [search, setSearch] = useState('')
  const [selectedTagIds, setSelectedTagIds] = useState<Set<string>>(new Set())
  const [assignments, setAssignments] = useState<Record<string, string[]>>({})
  const [filterRefreshKey, setFilterRefreshKey] = useState(0)

  const toggleTag = (tagId: string) =>
    setSelectedTagIds((prev) => {
      const next = new Set(prev)
      next.has(tagId) ? next.delete(tagId) : next.add(tagId)
      return next
    })

  useEffect(() => {
    fetch(`/api/games?libraryId=${encodeURIComponent(libraryId)}`)
      .then((r) => r.json())
      .then((data) => {
        setGames(data)
        setLoading(false)
      })
      .catch(() => {
        setError('Failed to load games')
        setLoading(false)
      })
  }, [libraryId])

  const fetchAssignments = useCallback(() => {
    fetch(`/api/tags/library-assignments?libraryId=${encodeURIComponent(libraryId)}`)
      .then((r) => r.json())
      .then(setAssignments)
      .catch(() => {})
  }, [libraryId])

  useEffect(() => { fetchAssignments() }, [fetchAssignments])

  const filtered = games.filter((game) => {
    if (search && !game.title.toLowerCase().includes(search.toLowerCase())) return false
    if (selectedTagIds.size > 0) {
      const gameTags = assignments[`${libraryId}:${game.id}`] ?? []
      if (![...selectedTagIds].every((id) => gameTags.includes(id))) return false
    }
    return true
  })

  return (
    <div className="flex gap-6 items-start">
      <div className="w-52 flex-shrink-0">
        <FilterPanel
          libraryId={libraryId}
          assignments={assignments}
          search={search}
          onSearchChange={setSearch}
          selectedTagIds={selectedTagIds}
          onTagToggle={toggleTag}
          refreshKey={filterRefreshKey}
        />
      </div>
      <div className="flex-1 min-w-0">
        {loading ? (
          <LoadingGrid />
        ) : error ? (
          <ErrorMessage message={error} />
        ) : games.length === 0 ? (
          <EmptyState />
        ) : (
          <div className="grid gap-4 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
            {filtered.map((game) => (
              <button
                key={game.id}
                onClick={() => setSelected(game)}
                className="group text-left rounded-xl overflow-hidden border transition-all focus:outline-none focus-visible:ring-2"
                style={{
                  borderColor: 'var(--border)',
                  backgroundColor: 'var(--surface)',
                }}
                onMouseEnter={(e) => {
                  ;(e.currentTarget as HTMLElement).style.borderColor = 'var(--accent)'
                  ;(e.currentTarget as HTMLElement).style.transform = 'translateY(-2px)'
                }}
                onMouseLeave={(e) => {
                  ;(e.currentTarget as HTMLElement).style.borderColor = 'var(--border)'
                  ;(e.currentTarget as HTMLElement).style.transform = 'translateY(0)'
                }}
              >
                <div className="aspect-[3/4] w-full relative overflow-hidden" style={{ backgroundColor: 'var(--border)' }}>
                  {game.coverUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img
                      src={game.coverUrl}
                      alt={game.title}
                      className="absolute inset-0 w-full h-full object-cover"
                    />
                  ) : (
                    <div className="absolute inset-0 flex items-center justify-center text-4xl">
                      🎮
                    </div>
                  )}
                </div>
                <div className="p-2">
                  <p
                    className="text-xs font-medium truncate leading-tight"
                    style={{ color: 'var(--text-primary)' }}
                    title={game.title}
                  >
                    {game.title}
                  </p>
                </div>
              </button>
            ))}
          </div>
        )}

        {selected && (
          <GameDetailModal
            game={selected}
            libraryId={libraryId}
            onClose={() => setSelected(null)}
            onTagsChanged={() => { setFilterRefreshKey((k) => k + 1); fetchAssignments() }}
          />
        )}
      </div>
    </div>
  )
}

function LoadingGrid() {
  return (
    <div className="grid gap-4 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
      {Array.from({ length: 12 }).map((_, i) => (
        <div key={i} className="rounded-xl overflow-hidden" style={{ backgroundColor: 'var(--surface)' }}>
          <div className="aspect-[3/4] w-full animate-pulse" style={{ backgroundColor: 'var(--border)' }} />
          <div className="p-2">
            <div className="h-3 rounded animate-pulse" style={{ backgroundColor: 'var(--border)', width: '70%' }} />
          </div>
        </div>
      ))}
    </div>
  )
}

function ErrorMessage({ message }: { message: string }) {
  return (
    <div className="rounded-lg border p-8 text-center" style={{ borderColor: 'var(--border)', color: 'var(--text-secondary)' }}>
      {message}
    </div>
  )
}

function EmptyState() {
  return (
    <div className="rounded-lg border p-12 text-center" style={{ borderColor: 'var(--border)', color: 'var(--text-secondary)' }}>
      <p className="text-lg mb-1">No games found</p>
      <p className="text-sm">Each game should be a folder containing a .zip file.</p>
    </div>
  )
}
