import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Store, LogOut } from 'lucide-react'
import { fetchSites } from '../api'

export default function SiteSelectorPage() {
  const [sites, setSites] = useState([])
  const [loading, setLoading] = useState(true)
  const navigate = useNavigate()

  useEffect(() => {
    fetchSites()
      .then(data => {
        setSites(data)
        // Auto-navigate if only one site
        if (data.length === 1) navigate(`/${data[0].id}`, { replace: true })
      })
      .finally(() => setLoading(false))
  }, [])

  function logout() {
    sessionStorage.removeItem('manager_token')
    navigate('/login', { replace: true })
  }

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center">
      <div className="w-8 h-8 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
    </div>
  )

  return (
    <div className="min-h-screen bg-slate-50 p-6">
      <div className="max-w-md mx-auto space-y-5">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-bold text-slate-800">Select Venue</h1>
          <button onClick={logout} className="text-slate-400 hover:text-slate-600 flex items-center gap-1 text-sm">
            <LogOut size={16} /> Log out
          </button>
        </div>

        {sites.length === 0 ? (
          <p className="text-slate-500 text-center py-12">No venues assigned to your account.</p>
        ) : (
          <div className="space-y-3">
            {sites.map(site => (
              <button
                key={site.id}
                onClick={() => navigate(`/${site.id}`)}
                className="w-full bg-white rounded-2xl p-5 shadow-sm hover:shadow-md transition-shadow text-left flex items-center gap-4"
              >
                <div className="w-12 h-12 bg-sky-100 rounded-xl flex items-center justify-center flex-shrink-0">
                  <Store className="text-sky-600" size={22} />
                </div>
                <div>
                  <p className="font-bold text-slate-800">{site.name}</p>
                  <p className="text-xs text-slate-400 font-mono">{site.site_id}</p>
                </div>
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
