import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import api from '../api'
import './Dashboard.css'

export default function Dashboard() {
  const [crawls, setCrawls] = useState([])
  const [loading, setLoading] = useState(true)
  const [running, setRunning] = useState(false)
  const [runError, setRunError] = useState('')

  const loadData = () => {
    api.fetchAllCrawls().then(
      (data) => {
        setCrawls(data)
        setLoading(false)
      }
    ).catch(() => {
      setLoading(false)
    })
  }

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

  const handleRunCrawl = async () => {
    setRunning(true)
    setRunError('')
    try {
      await api.runAllCrawls()
      loadData()
    } catch (err) {
      setRunError(err.response?.data?.error || 'Failed to run crawl')
    } finally {
      setRunning(false)
    }
  }

  return (
    <div className="dashboard">
      <div className="dashboard-header">
        <h2>Crawler Dashboard</h2>
        <button className="crawl-button" onClick={handleRunCrawl} disabled={running}>
          {running ? 'Running...' : 'Run Crawl Now'}
        </button>
      </div>

      {runError && <div className="crawl-error">{runError}</div>}

      {loading ? (
        <div className="loading-state">Loading crawl data...</div>
      ) : crawls.length === 0 ? (
        <div className="empty-state">
          <p>No crawls yet. Click "Run Crawl Now" to start collecting data.</p>
        </div>
      ) : (
        <div className="crawl-list">
          {crawls.map((crawl) => (
            <Link to={`/crawl/${crawl.crawl_id}`} key={crawl.crawl_id} className="crawl-card">
              <div className="crawl-card-header">
                <span className={`status-badge status-${crawl.status === 'completed' ? 'success' : crawl.status.includes('failed') ? 'error' : 'pending'}`}>
                  {crawl.status}
                </span>
                <h3>{crawl.site_name}</h3>
              </div>
              <div className="crawl-card-body">
                <p className="crawl-url">{crawl.url}</p>
                <p className="crawl-date">{new Date(crawl.crawled_at).toLocaleString()}</p>
                <div className="crawl-stats">
                  <span>Casinos Found: <strong>{crawl.casinos?.length || 0}</strong></span>
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  )
}
