import { useState, useEffect } from 'react'
import api from '../api'
import PositionChart from './PositionChart'
import './CasinoReport.css'

export default function CasinoReport() {
  const [data, setData] = useState([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [expanded, setExpanded] = useState({})
  const [modalOpen, setModalOpen] = useState(false)
  const [selectedCasino, setSelectedCasino] = useState(null)
  const [selectedSite, setSelectedSite] = useState(null)

  useEffect(() => {
    api.fetchCasinoReport().then(
      (result) => {
        setData(result)
        setLoading(false)
      }
    ).catch(() => {
      setLoading(false)
    })
  }, [])

  const toggleExpand = (name) => {
    setExpanded(prev => ({ ...prev, [name]: !prev[name] }))
  }

  const openChart = (casinoName, siteName) => {
    setSelectedCasino(casinoName)
    setSelectedSite(siteName)
    setModalOpen(true)
  }

  const closeChart = () => {
    setModalOpen(false)
    setSelectedCasino(null)
    setSelectedSite(null)
  }

  const filtered = data.filter(casino =>
    casino.casino_name.toLowerCase().includes(search.toLowerCase())
  )

  return (
    <div className="casino-report">
      <div className="report-header">
        <h2>Casino Report</h2>
        <p className="report-subtitle">Which sites each casino appears on</p>
      </div>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Search casinos..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      {loading ? (
        <div className="loading-state">Loading report...</div>
      ) : filtered.length === 0 ? (
        <div className="empty-state">No casinos found</div>
      ) : (
        <div className="report-stats">
          <span className="stat">{data.length} unique casinos</span>
          <span className="stat">{data.reduce((sum, c) => sum + (c.sites?.length || 0), 0)} casino-site listings</span>
        </div>
      )}

      <div className="casino-list">
        {filtered.map((casino) => (
          <div key={casino.casino_name} className="casino-card">
            <button
              className="casino-card-header"
              onClick={() => toggleExpand(casino.casino_name)}
            >
              <span className={`expand-icon ${expanded[casino.casino_name] ? 'open' : ''}`}>&#9654;</span>
              <div className="casino-info">
                {casino.favicon_url && (
                  <img src={casino.favicon_url} alt="" className="casino-favicon" />
                )}
                <div className="casino-name-group">
                  <h3>{casino.casino_name}</h3>
                  {casino.casino_url && (
                    <a href={casino.casino_url} target="_blank" rel="noreferrer" className="casino-url">{casino.casino_url}</a>
                  )}
                </div>
              </div>
              <div className="site-count">{casino.sites?.length || 0} sites</div>
            </button>

            {expanded[casino.casino_name] && (
              <div className="sites-table">
                <table>
                  <thead>
                    <tr>
                      <th>Position</th>
                      <th>Site Name</th>
                      <th>Site URL</th>
                      <th>Last Crawled</th>
                    </tr>
                  </thead>
                  <tbody>
                    {casino.sites?.map((site) => (
                      <tr key={site.crawl_id}>
                        <td className="position">{site.position}</td>
                        <td className="site-name">
                          <button
                            className="site-name-link"
                            onClick={() => openChart(casino.casino_name, site.site_name)}
                          >
                            {site.site_name}
                          </button>
                        </td>
                        <td className="site-url">
                          <a href={site.site_url} target="_blank" rel="noreferrer">{site.site_url}</a>
                        </td>
                        <td className="crawled-at">{new Date(site.crawled_at).toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        ))}
      </div>

      {modalOpen && (
        <PositionChart
          casinoName={selectedCasino}
          siteName={selectedSite}
          onClose={closeChart}
        />
      )}
    </div>
  )
}
