import React, { useState, useEffect } from 'react';
import { 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(null);
  const navigate = useNavigate();

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

  const handleRetrieve = async () => {
    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) {
        navigate('/login');
      }
      setError(err.response?.data?.message || 'Could not load user');
      console.error('Server Error:', err.response?.data || err.message);
    }
  };

  const loadStats = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/stats/getstats', { headers });
      setStats(res.data);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (!token) {
      navigate('/login');
      return;
    }
    handleRetrieve();
    loadStats();
  }, []);

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

  const isAdmin = user && user.role === 'admin';

  const navLink =
    'block rounded-lg px-3 py-2.5 text-sm font-medium text-slate-300 transition-colors hover:bg-slate-800 hover:text-white';

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

        <nav className="flex-1 space-y-1 px-3 py-4">
          <Link to="/dashboard" className={navLink}>
            Overview
          </Link>
          {isAdmin && (
            <Link to="/dashboard/students" className={navLink}>
              Students
            </Link>
          )}
          {isAdmin && (
            <Link to="/dashboard/books" className={navLink}>
              Books
            </Link>
          )}
          <Link to="/dashboard/borrow" className={navLink}>
            Borrow
          </Link>
          <Link to="/dashboard/return" className={navLink}>
            Return
          </Link>
          <Link to="/dashboard/search" className={navLink}>
            Search
          </Link>
          <Link to="/dashboard/reports" className={navLink}>
            Reports
          </Link>
          <Link to="/dashboard/profile" className={navLink}>
            Profile
          </Link>
        </nav>

        <div className="border-t border-slate-700 px-4 py-4">
          {error && <p className="mb-2 text-xs text-red-400">{error}</p>}
          {user && <p className="truncate text-sm font-medium text-white">{user.name}</p>}
          {user && <p className="mt-0.5 truncate text-xs capitalize text-slate-400">{user.role}</p>}
          <button type="button" onClick={handleLogout} className="lms-btn-secondary mt-3 w-full">
            Log out
          </button>
        </div>
      </aside>

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

        <main className="flex-1 overflow-auto p-6">
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <div className="lms-card">
              <p className="text-sm text-slate-400">Students</p>
              <p className="mt-1 text-2xl font-semibold text-white">{stats ? stats.totalStudents : '—'}</p>
            </div>
            <div className="lms-card">
              <p className="text-sm text-slate-400">Books in catalog</p>
              <p className="mt-1 text-2xl font-semibold text-white">{stats ? stats.totalBooks : '—'}</p>
            </div>
            <div className="lms-card">
              <p className="text-sm text-slate-400">Currently borrowed</p>
              <p className="mt-1 text-2xl font-semibold text-amber-400">{stats ? stats.currentlyBorrowed : '—'}</p>
            </div>
            <div className="lms-card">
              <p className="text-sm text-slate-400">Returned (all time)</p>
              <p className="mt-1 text-2xl font-semibold text-green-400">{stats ? stats.totalReturned : '—'}</p>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}

export default Dashboard;
