import React, { useState, useEffect } from 'react'
import { NavLink, Link, useNavigate } from 'react-router-dom';
import axios from 'axios';

function Dashboard() {
  const [user, setUser] = useState(null);
  const [error, setError] = useState('')
  const [stats, setStats] = useState({ studentCount: 0, paymentCount: 0, totalPaid: 0 })
  const navigate = useNavigate()

  const headers = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  };

  const handleRetrieve = async () => {
    const token = localStorage.getItem('token');
    if (!token) {
      navigate('/login');
      return;
    }

    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    }

    try {
      const response = await axios.get('http://localhost:5001/api/auth/me', {
        headers,
      });
      setUser(response.data.user);
      localStorage.setItem('user', JSON.stringify(response.data.user));
    } catch (err) {
      if (!storedUser) {
        setError(err.response?.data?.message || 'Could not load user');
        navigate('/login');
      }
      console.error('Server Error:', err.response?.data || err.message);
    }
  };

  const handleGetStats = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/product/getstats', { headers });
      setStats(res.data);
    } catch (err) {
      console.error('Server Error:', err.response?.data || err.message);
    }
  };

  useEffect(() => {
    handleRetrieve();
    handleGetStats();
  }, []);

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    navigate('/login');
  };

  const navClass = ({ isActive }) => (isActive ? 'nav-link-active' : 'nav-link');

  return (
    <div className="min-h-screen bg-slate-100">
      <aside className="fixed inset-y-0 left-0 w-64 bg-slate-900 text-slate-100 flex flex-col shadow-lg">
        <div className="px-5 py-6 border-b border-slate-700">
          <p className="text-xs font-semibold uppercase tracking-wider text-slate-400">School Fees</p>
          <h1 className="text-lg font-bold text-white mt-1">Dashboard</h1>
        </div>

        <nav className="flex-1 px-3 py-4 space-y-1">
          <NavLink to="/dashboard" end className={navClass}>
            Home
          </NavLink>
          <NavLink to="/dashboard/products" className={navClass}>
            Students
          </NavLink>
          <NavLink to="/dashboard/sales" className={navClass}>
            Payments
          </NavLink>
          <NavLink to="/dashboard/supplier" className={navClass}>
            Reports
          </NavLink>
          <NavLink to="/dashboard/profile" className={navClass}>
            Profile
          </NavLink>
        </nav>

        <div className="px-4 py-4 border-t border-slate-700">
          {error && <p className="text-xs text-red-400 mb-2">{error}</p>}
          {user && (
            <p className="text-sm font-medium text-white truncate">{user.name}</p>
          )}
          {user && (
            <p className="text-xs text-slate-400 truncate mt-0.5">{user.email}</p>
          )}
          <button
            type="button"
            onClick={handleLogout}
            className="mt-3 w-full text-sm font-medium text-slate-300 hover:text-white border border-slate-600 rounded-lg px-3 py-2 hover:bg-slate-800 transition-colors"
          >
            Log out
          </button>
        </div>
      </aside>

      <div className="ml-64 flex min-h-screen flex-col">
        <header className="bg-white border-b border-slate-200 px-6 py-5 shadow-sm">
          <p className="text-sm text-slate-500">Welcome back</p>
          <h2 className="text-xl font-semibold text-slate-800">
            {user ? `Hello, ${user.name}` : 'Dashboard'}
          </h2>
        </header>

        <main className="flex-1 p-6 overflow-auto">
          <div className="grid gap-4 sm:grid-cols-3">
            <div className="stat-card">
              <p className="stat-label">Students</p>
              <p className="stat-value">{stats.studentCount}</p>
            </div>
            <div className="stat-card">
              <p className="stat-label">Payments</p>
              <p className="stat-value">{stats.paymentCount}</p>
            </div>
            <div className="stat-card">
              <p className="stat-label">Total Paid</p>
              <p className="stat-value">{stats.totalPaid.toFixed(2)}</p>
            </div>
          </div>

          <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <Link to="/dashboard/products" className="list-card hover:border-blue-300 transition-colors">
              <p className="font-medium text-slate-800">Manage Students</p>
              <p className="text-sm text-slate-500 mt-1">Add, edit, or remove student records</p>
            </Link>
            <Link to="/dashboard/sales" className="list-card hover:border-blue-300 transition-colors">
              <p className="font-medium text-slate-800">Record Payments</p>
              <p className="text-sm text-slate-500 mt-1">Log fee payments by student</p>
            </Link>
            <Link to="/dashboard/supplier" className="list-card hover:border-blue-300 transition-colors">
              <p className="font-medium text-slate-800">View Reports</p>
              <p className="text-sm text-slate-500 mt-1">Filter payments by date range</p>
            </Link>
            <Link to="/dashboard/profile" className="list-card hover:border-blue-300 transition-colors">
              <p className="font-medium text-slate-800">Your Profile</p>
              <p className="text-sm text-slate-500 mt-1">View account details</p>
            </Link>
          </div>
        </main>
      </div>
    </div>
  )
}

export default Dashboard
