import React, { useEffect, useRef } from 'react';
import { Chart, CategoryScale, LinearScale, LineElement, PointElement, LineController, Title, Tooltip, Legend } from 'chart.js';
import { Line } from 'react-chartjs-2';
import Navbar from '../components/Navbar';
import './Dashboard.css';

Chart.register(CategoryScale, LinearScale, LineElement, PointElement, LineController, Title, Tooltip, Legend);

const Dashboard = () => {
  const userStats = {
    totalUsers: [50, 70, 60, 80, 100, 90, 110],
    totalAds: 50,
    totalRevenue: [40, 50, 30, 70, 60, 80, 75]
  };

  const chartData = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
    datasets: [
      {
        label: 'Total Users',
        data: userStats.totalUsers,
        borderColor: 'rgba(75,192,192,1)',
        backgroundColor: 'rgba(75,192,192,0.2)',
        fill: true,
        tension: 0.4,
      },
      {
        label: 'Total Revenue',
        data: userStats.totalRevenue,
        borderColor: 'rgba(153,102,255,1)',
        backgroundColor: 'rgba(153,102,255,0.2)',
        fill: true,
        tension: 0.4,
      }
    ],
  };

  const chartRef = useRef(null);

  useEffect(() => {
    const chartInstance = chartRef.current.chartInstance;

    return () => {
      if (chartInstance) {
        chartInstance.destroy();
      }
    };
  }, []);

  return (
    <div className="dashboard">
      <Navbar />
      <div className="dashboard-container">
        <div className="dashboard-header">
          <h4>Dashboard</h4>
        </div>
        <div className="dashboard-stats">
          <div className="stat-card">
            <h6>Total Users</h6>
            <p>{userStats.totalUsers[userStats.totalUsers.length - 1]}</p>
          </div>
          <div className="stat-card">
            <h6>Total Ads</h6>
            <p>{userStats.totalAds}</p>
          </div>
          <div className="stat-card">
            <h6>Total Revenue</h6>
            <p>${userStats.totalRevenue[userStats.totalRevenue.length - 1]}</p>
          </div>
        </div>
        <div className="chart-container">
          <Line ref={chartRef} data={chartData} />
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
