import { useEffect, useState, useCallback } from 'react'
import { fetchAPI, deleteAPI } from '../api/client'
import { useToast } from '../components/Toast'
import Pagination from '../components/Pagination'
import ErrorBanner from '../components/ErrorBanner'
import Loading from '../components/Loading'
import ConfirmModal from '../components/ConfirmModal'

interface BlocklistItem {
  id: number
  release_title: string
  source_title: string | null
  quality: { resolution?: string } | null
  indexer: string | null
  protocol: string
  size: number | null
  message: string | null
  block_reason: string
  created_at: string
}

interface PaginatedResponse {
  data: BlocklistItem[]
  total: number
  page: number
  page_size: number
  total_pages: number
}

const PAGE_SIZE = 50

export default function Blocklist() {
  const { showToast } = useToast()
  const [items, setItems] = useState<BlocklistItem[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [selected, setSelected] = useState<Set<number>>(new Set())
  const [clearAllOpen, setClearAllOpen] = useState(false)
  const [deleting, setDeleting] = useState(false)

  const fetchBlocklist = useCallback(() => {
    setLoading(true)
    setError(null)
    fetchAPI<PaginatedResponse>(`/api/blocklist?page=${page}&page_size=${PAGE_SIZE}`)
      .then(res => {
        setItems(res.data ?? [])
        setTotal(res.total)
        setSelected(new Set())
      })
      .catch(err => setError(err.message || 'Something went wrong. Please try again.'))
      .finally(() => setLoading(false))
  }, [page])

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

  const toggleSelect = (id: number) => {
    setSelected(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const toggleSelectAll = () => {
    if (selected.size === items.length) {
      setSelected(new Set())
    } else {
      setSelected(new Set(items.map(i => i.id)))
    }
  }

  const deleteSelected = async () => {
    setDeleting(true)
    let failed = 0
    for (const id of selected) {
      try {
        await deleteAPI(`/api/blocklist/${id}`)
      } catch {
        failed++
      }
    }
    showToast(failed ? `Deleted ${selected.size - failed} items, ${failed} failed` : `Deleted ${selected.size} items`)
    setDeleting(false)
    fetchBlocklist()
  }

  const clearExpired = async () => {
    try {
      await deleteAPI('/api/blocklist/expired')
      showToast('Expired entries cleared')
      fetchBlocklist()
    } catch {
      showToast('Failed to clear expired entries')
    }
  }

  const clearAll = async () => {
    try {
      await deleteAPI('/api/blocklist')
      showToast('All entries cleared')
      fetchBlocklist()
    } catch {
      showToast('Failed to clear blocklist')
    }
    setClearAllOpen(false)
  }

  const deleteOne = async (id: number) => {
    try {
      await deleteAPI(`/api/blocklist/${id}`)
      setItems(items.filter(i => i.id !== id))
      setTotal(t => t - 1)
      showToast('Entry removed')
    } catch {
      showToast('Failed to remove entry')
    }
  }

  const formatTimeAgo = (dateStr: string): string => {
    const diff = Date.now() - new Date(dateStr).getTime()
    const minutes = Math.floor(diff / 60000)
    if (minutes < 60) return `${minutes}m ago`
    const hours = Math.floor(minutes / 60)
    if (hours < 24) return `${hours}h ago`
    const days = Math.floor(hours / 24)
    return `${days}d ago`
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-semibold text-gray-100">Blocklist</h2>
        <div className="flex gap-2">
          <button onClick={clearExpired} className="bg-orange-600 hover:bg-orange-500 px-4 py-2 rounded text-sm font-semibold min-h-[36px]">
            Clear Expired
          </button>
          <button onClick={() => setClearAllOpen(true)} className="bg-red-600 hover:bg-red-500 px-4 py-2 rounded text-sm font-semibold min-h-[36px]">
            Clear All
          </button>
        </div>
      </div>

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

      {loading ? (
        <Loading />
      ) : items.length === 0 ? (
        <div className="text-gray-500 text-center py-20 text-sm">No blocked releases</div>
      ) : (
        <>
          {selected.size > 0 && (
            <div className="mb-4 flex items-center gap-4">
              <span className="text-sm text-gray-400">{selected.size} selected</span>
              <button
                onClick={deleteSelected}
                disabled={deleting}
                className="bg-red-600 hover:bg-red-500 px-4 py-2 rounded text-sm font-semibold min-h-[36px] disabled:opacity-50"
              >
                Delete Selected
              </button>
            </div>
          )}

<div className="bg-gray-900 border border-gray-800 rounded-lg overflow-hidden">
          <div className="overflow-x-auto">
          <table className="w-full min-w-[640px]">
            <thead>
              <tr className="border-b border-gray-800">
                <th className="px-4 py-3 w-10">
                  <span className="sr-only">
                    <input
                      type="checkbox"
                      checked={selected.size === items.length && items.length > 0}
                      onChange={toggleSelectAll}
                      className="rounded bg-gray-800 border-gray-600"
                      aria-label="Select all"
                    />
                  </span>
                </th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase">Release</th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-24">Indexer</th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-20">Quality</th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-20">Reason</th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-gray-400 uppercase w-20">Date</th>
                <th className="w-10 px-4 py-3" />
              </tr>
            </thead>
            <tbody>
              {items.map(item => (
                <tr key={item.id} className={`border-b border-gray-800/50 hover:bg-gray-800/30 ${selected.has(item.id) ? 'bg-gray-800/20' : ''}`}>
                  <td className="px-4 py-3">
                    <input
                      type="checkbox"
                      checked={selected.has(item.id)}
                      onChange={() => toggleSelect(item.id)}
                      className="rounded bg-gray-800 border-gray-600"
                      aria-label={`Select ${item.release_title}`}
                    />
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-sm text-gray-100 truncate max-w-md">{item.release_title}</p>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-400">{item.indexer ?? '—'}</td>
                  <td className="px-4 py-3 text-sm text-gray-400">{item.quality?.resolution ?? '—'}</td>
                  <td className="px-4 py-3 text-sm text-gray-400 capitalize">{item.block_reason}</td>
                  <td className="px-4 py-3 text-xs text-gray-500">{formatTimeAgo(item.created_at)}</td>
                  <td className="px-4 py-3">
                    <button onClick={() => deleteOne(item.id)} aria-label="Remove from blocklist" className="text-red-400 hover:text-red-300 text-xs min-h-[36px]">
                      ×
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        </div>

          <Pagination
            total={total}
            page={page}
            pageSize={PAGE_SIZE}
            onPageChange={setPage}
          />
        </>
      )}

      <ConfirmModal
        open={clearAllOpen}
        title="Clear Blocklist"
        message="Remove all blocked releases? This cannot be undone."
        onConfirm={clearAll}
        onCancel={() => setClearAllOpen(false)}
        destructive
      />
    </div>
  )
}
