import { useEffect, useState, useCallback } from 'react'
import { fetchAPI, postAPI } from '../api/client'
import { useToast } from '../components/Toast'
import ErrorBanner from '../components/ErrorBanner'

interface DiscoverItem {
  tmdb_id: number
  title: string
  year: number | null
  media_type: string
  overview: string
  poster_url: string
  backdrop_url: string
  vote_average: number
  in_library: boolean
}

interface DiscoverResponse {
  data: DiscoverItem[]
  page: number
}

export default function Discover() {
  const { showToast } = useToast()
  const [items, setItems] = useState<DiscoverItem[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [mediaType, setMediaType] = useState<string>('movie')
  const [tab, setTab] = useState<string>('trending')
  const [page, setPage] = useState(1)
  const [adding, setAdding] = useState<Set<number>>(new Set())

  const fetchData = useCallback(() => {
    setLoading(true)
    setError(null)
    fetchAPI<DiscoverResponse>(`/api/discover/${tab}?type=${mediaType}&page=${page}`)
      .then(res => {
        setItems(res.data ?? [])
      })
      .catch(err => setError(err.message || 'Failed to load discover content'))
      .finally(() => setLoading(false))
  }, [tab, mediaType, page])

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

  const handleMediaTypeChange = (value: string) => {
    setMediaType(value)
    setPage(1)
  }

  const handleTabChange = (value: string) => {
    setTab(value)
    setPage(1)
  }

  const handleAddToLibrary = async (item: DiscoverItem) => {
    setAdding(prev => new Set(prev).add(item.tmdb_id))
    try {
      const result = await postAPI<{ id: number; existing?: boolean }>(
        '/api/discover/add',
        { tmdb_id: item.tmdb_id, media_type: item.media_type }
      )
      setItems(prev =>
        prev.map(i => i.tmdb_id === item.tmdb_id ? { ...i, in_library: true } : i)
      )
      if (result.existing) {
        showToast(`"${item.title}" is already in your library`)
      } else {
        showToast(`Added "${item.title}" to library`)
      }
    } catch {
      showToast(`Failed to add "${item.title}" to library`)
    } finally {
      setAdding(prev => {
        const next = new Set(prev)
        next.delete(item.tmdb_id)
        return next
      })
    }
  }

  return (
    <div>
      <h2 className="text-2xl font-semibold mb-2 text-gray-100">Discover</h2>
      <p className="text-gray-500 text-sm mb-6">Browse trending and popular content from TMDB</p>

      <div className="flex gap-3 mb-6">
        <div className="flex rounded-lg overflow-hidden border border-gray-700">
          <button
            onClick={() => handleTabChange('trending')}
            className={`px-4 py-2 text-sm font-medium transition-colors ${
              tab === 'trending' ? 'bg-indigo-600 text-white' : 'bg-gray-800 text-gray-400 hover:text-gray-200'
            }`}
          >
            Trending
          </button>
          <button
            onClick={() => handleTabChange('popular')}
            className={`px-4 py-2 text-sm font-medium transition-colors ${
              tab === 'popular' ? 'bg-indigo-600 text-white' : 'bg-gray-800 text-gray-400 hover:text-gray-200'
            }`}
          >
            Popular
          </button>
        </div>
        <select
          value={mediaType}
          onChange={e => handleMediaTypeChange(e.target.value)}
          className="bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-gray-100 text-sm"
        >
          <option value="movie">Movies</option>
          <option value="series">Series</option>
        </select>
      </div>

      {error && <ErrorBanner error={error} onRetry={fetchData} />}

      {loading ? (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
          {Array.from({ length: 12 }).map((_, i) => (
            <div key={i} className="bg-gray-900 border border-gray-800 rounded-lg overflow-hidden animate-pulse">
              <div className="aspect-[2/3] bg-gray-800" />
            </div>
          ))}
        </div>
      ) : items.length === 0 ? (
        <div className="text-gray-500 text-center py-20 text-sm">No results found</div>
      ) : (
        <>
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
            {items.map(item => (
              <div
                key={item.tmdb_id}
                className="group relative bg-gray-900 border border-gray-800 rounded-lg overflow-hidden hover:border-gray-700 transition-colors"
              >
                {item.poster_url ? (
                  <img
                    src={item.poster_url}
                    alt={item.title}
                    className="w-full aspect-[2/3] object-cover"
                    loading="lazy"
                  />
                ) : (
                  <div className="w-full aspect-[2/3] bg-gray-800 flex items-center justify-center">
                    <span className="text-3xl text-gray-400 font-bold">
                      {item.title.charAt(0).toUpperCase()}
                    </span>
                  </div>
                )}

                {item.in_library && (
                  <div className="absolute top-2 right-2 bg-green-600 rounded-full w-6 h-6 flex items-center justify-center text-white text-xs font-bold z-10">
                    ✓
                  </div>
                )}

                <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex flex-col justify-end p-3">
                  <p className="text-white text-sm font-medium leading-tight mb-1 line-clamp-2">{item.title}</p>
                  <div className="flex items-center gap-2 text-xs text-gray-300 mb-2">
                    {item.year && <span>{item.year}</span>}
                    <span>⭐ {item.vote_average.toFixed(1)}</span>
                  </div>
                  {item.in_library ? (
                    <button
                      disabled
                      className="bg-green-800 text-green-300 text-xs px-3 py-1.5 rounded font-medium cursor-not-allowed"
                    >
                      In Library
                    </button>
                  ) : (
                    <button
                      onClick={() => handleAddToLibrary(item)}
                      disabled={adding.has(item.tmdb_id)}
                      className="bg-indigo-600 hover:bg-indigo-500 disabled:bg-indigo-800 disabled:cursor-wait text-white text-xs px-3 py-1.5 rounded font-medium transition-colors"
                    >
                      {adding.has(item.tmdb_id) ? 'Adding...' : 'Add to Library'}
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>

          <div className="flex items-center justify-center gap-4 mt-8">
            <button
              onClick={() => setPage(p => Math.max(1, p - 1))}
              disabled={page === 1}
              className="px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-700 transition-colors"
            >
              ← Previous
            </button>
            <span className="text-sm text-gray-400">Page {page}</span>
            <button
              onClick={() => setPage(p => p + 1)}
              disabled={page >= 10}
              className="px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-700 transition-colors"
            >
              Next →
            </button>
          </div>
        </>
      )}
    </div>
  )
}
