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

export default function CrawlDetail() {
  const { id } = useParams()
  const [crawl, setCrawl] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.fetchCrawlById(id).then(
      (data) => {
        setCrawl(data)
        setLoading(false)
      }
    ).catch(() => {
      setLoading(false)
    })
  }, [id])

  if (loading) return <div className="loading-state">Loading crawl details...</div>
  if (!crawl) return <div className="error-state">Crawl not found</div>

  const screenshotUrl = crawl.screenshot_path ? `/screenshots/${crawl.screenshot_path}` : null

  return (
    <div className="crawl-detail">
      <h2>Crawl Details</h2>

      <div className="detail-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="detail-meta">
        <p><strong>URL:</strong> <a href={crawl.url} target="_blank" rel="noreferrer">{crawl.url}</a></p>
        <p><strong>Crawled at:</strong> {new Date(crawl.crawled_at).toLocaleString()}</p>
        <p><strong>Casinos Found:</strong> {crawl.casinos?.length || 0}</p>
      </div>

      {crawl.screenshot_path && (
        <div className="screenshot-section">
          <h4>Screenshot</h4>
          <img src={screenshotUrl} alt={`Screenshot of ${crawl.site_name}`} className="screenshot" />
        </div>
      )}

      <div className="casino-table-section">
        <h4>Casino Rankings</h4>
        <table className="casino-table">
          <thead>
            <tr>
              <th>#</th>
              <th>Casino Name</th>
              <th>Bonus / Offer</th>
              <th>Link</th>
            </tr>
          </thead>
          <tbody>
            {crawl.casinos?.map((casino) => (
              <tr key={casino.id}>
                <td className="position">{casino.position}</td>
                <td className="casino-name">
                  {casino.favicon_url && <img src={casino.favicon_url} alt="" className="casino-favicon" />}
                  {casino.casino_name}
                </td>
                <td className="bonus">{casino.bonus_offer || '-'}</td>
                <td className="link">
                  {casino.url ? <a href={casino.url} target="_blank" rel="noreferrer">Open</a> : '-'}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
