import { useState, useEffect } from 'react'
import { Line } from 'react-chartjs-2'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
} from 'chart.js'
import api from '../api'
import './PositionChart.css'

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip
)

export default function PositionChart({ casinoName, siteName, onClose }) {
  const [history, setHistory] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.getPositionHistory(casinoName, siteName).then(
      (result) => {
        setHistory(result)
        setLoading(false)
      }
    ).catch(() => {
      setLoading(false)
    })
  }, [casinoName, siteName])

  const chartData = history.length > 0 ? {
    labels: history.map(h => h.label),
    datasets: [{
      label: 'Position',
      data: history.map(h => Number(h.position)),
      borderColor: '#6366f1',
      backgroundColor: 'rgba(99, 102, 241, 0.1)',
      fill: true,
      tension: 0.3,
      pointBackgroundColor: '#6366f1',
      pointRadius: history.length > 30 ? 0 : 4,
    }],
  } : null

  return (
    <div className="position-chart-overlay" onClick={onClose}>
      <div className="position-chart-modal" onClick={(e) => e.stopPropagation()}>
        <div className="chart-header">
          <h3>Position History: {casinoName} on {siteName}</h3>
          <button className="close-btn" onClick={onClose}>&times;</button>
        </div>

        {loading ? (
          <div className="chart-loading">Loading chart...</div>
        ) : history.length === 0 ? (
          <div className="chart-empty">No position history found</div>
        ) : (
          <div className="chart-container">
            <Line
              data={chartData}
              options={{
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                  y: {
                    reverse: true,
                    beginAtZero: false,
                    title: { display: true, text: 'Position (lower is better)', color: '#9ca3af' },
                    ticks: { color: '#9ca3af' },
                    grid: { color: 'rgba(58, 63, 86, 0.5)' },
                  },
                  x: {
                    title: { display: true, text: 'Date', color: '#9ca3af' },
                    ticks: { color: '#9ca3af', maxRotation: 45 },
                    grid: { color: 'rgba(58, 63, 86, 0.5)' },
                  },
                },
                plugins: {
                  legend: { display: false },
                  tooltip: {
                    backgroundColor: '#1e2136',
                    titleColor: '#e8ebf2',
                    bodyColor: '#e8ebf2',
                    borderColor: '#3a3f56',
                    borderWidth: 1,
                    callbacks: {
                      label: (context) => `Position: ${context.parsed.y}`,
                    },
                  },
                },
              }}
            />
          </div>
        )}
      </div>
    </div>
  )
}
