import React, { useState, useMemo } from "react"
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  LineElement,
  PointElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js"
import { Line } from "react-chartjs-2"
import styles from "./stats.module.scss"

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

interface AdminStatsChartProps {
  users: number[]
  deposits: number[]
  withdrawals: number[]
}

type DataType = "users" | "deposits" | "withdrawals"

const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]

const AdminStatsChart: React.FC<AdminStatsChartProps> = ({ users, deposits, withdrawals }) => {
  const [activeType, setActiveType] = useState<DataType>("users")

  const chartData = useMemo(() => {
    let data: number[] = []
    let label = ""

    switch(activeType){
      case "users":
        data = users.length === 12 ? users : Array(12).fill(0)
        label = "Users Registered"
        break
      case "deposits":
        data = deposits.length === 12 ? deposits : Array(12).fill(0)
        label = "Deposits ($)"
        break
      case "withdrawals":
        data = withdrawals.length === 12 ? withdrawals : Array(12).fill(0)
        label = "Withdrawals ($)"
        break
    }

    return {
      labels: MONTHS,
      datasets: [
        {
          label,
          data,
          fill: true,
          backgroundColor: "rgba(255, 140, 0, 0.2)",
          borderColor: "rgba(255, 140, 0, 1)",
          tension: 0.3,
          pointRadius: 5,
        },
      ],
    }
  }, [activeType, users, deposits, withdrawals])

  const options = {
    responsive: true,
    plugins: {
      legend: { position: "top" as const, labels: { color: "#fff" } },
      title: { display: true, text: "Monthly Stats", color: "#fff", font: { size: 18 } },
      tooltip: { mode: "index" as const, intersect: false },
    },
    scales: {
      x: { ticks: { color: "#fff" }, grid: { color: "#333" } },
      y: { ticks: { color: "#fff" }, grid: { color: "#333" } },
    },
  }

  return (
    <div className={styles["admin-stats-chart"]}>
      <div className={styles["admin-stats-chart__buttons"]}>
        <button className={activeType==="users" ? styles.active : ""} onClick={()=>setActiveType("users")}>Users</button>
        <button className={activeType==="deposits" ? styles.active : ""} onClick={()=>setActiveType("deposits")}>Deposits</button>
        <button className={activeType==="withdrawals" ? styles.active : ""} onClick={()=>setActiveType("withdrawals")}>Withdrawals</button>
      </div>

      <div className={styles["admin-stats-chart__canvas"]}>
        <Line data={chartData} options={options} />
      </div>
    </div>
  )
}

export default AdminStatsChart
