import { useState, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import client from '../api/client'
import SiteCard from '../components/SiteCard'

export default function SitesPage() {
  const [sites, setSites] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const navigate = useNavigate()

  const fetchSites = useCallback(async () => {
    try {
      const { data } = await client.get('/api/sites/')
      setSites(data)
      setError('')
    } catch {
      setError('Failed to load sites')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchSites()
    const id = setInterval(fetchSites, 30000)
    return () => clearInterval(id)
  }, [fetchSites])

  const active = sites.filter(s => !s.is_locked && new Date(s.license_expires_at) > new Date()).length
  const locked = sites.filter(s => s.is_locked).length
  const expired = sites.filter(s => !s.is_locked && new Date(s.license_expires_at) <= new Date()).length

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold text-white">Sites</h1>
          <p className="text-gray-500 text-sm mt-0.5">{sites.length} registered</p>
        </div>
        <button
          onClick={() => navigate('/sites/register')}
          className="flex items-center gap-2 bg-cyan-600 hover:bg-cyan-500 text-white text-sm font-semibold px-4 py-2 rounded-lg transition-colors"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
          Register New Site
        </button>
      </div>

      {/* Summary row */}
      {sites.length > 0 && (
        <div className="grid grid-cols-3 gap-3 mb-6">
          <div className="bg-gray-900 border border-gray-700 rounded-lg px-4 py-3 text-center">
            <p className="text-2xl font-bold text-emerald-400">{active}</p>
            <p className="text-gray-500 text-xs mt-0.5">Active</p>
          </div>
          <div className="bg-gray-900 border border-gray-700 rounded-lg px-4 py-3 text-center">
            <p className="text-2xl font-bold text-yellow-400">{locked}</p>
            <p className="text-gray-500 text-xs mt-0.5">Locked</p>
          </div>
          <div className="bg-gray-900 border border-gray-700 rounded-lg px-4 py-3 text-center">
            <p className="text-2xl font-bold text-red-400">{expired}</p>
            <p className="text-gray-500 text-xs mt-0.5">Expired</p>
          </div>
        </div>
      )}

      {loading && (
        <div className="text-center py-16 text-gray-600">Loading…</div>
      )}

      {error && (
        <div className="text-red-400 bg-red-900/20 border border-red-800/50 rounded-lg px-4 py-3 text-sm">{error}</div>
      )}

      {!loading && !error && sites.length === 0 && (
        <div className="text-center py-16">
          <p className="text-gray-600 text-sm">No sites registered yet.</p>
          <button
            onClick={() => navigate('/sites/register')}
            className="mt-4 text-cyan-400 hover:text-cyan-300 text-sm underline"
          >
            Register your first site
          </button>
        </div>
      )}

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {sites.map(site => (
          <SiteCard key={site.site_id} site={site} />
        ))}
      </div>
    </div>
  )
}
