import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Doctors from './Doctors';
import Patients from './Patients';
import Appointments from './Appointments';
import Reports from './Reports'; 

function Dashboard() {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('overview');

  // Gufata umushitsi winjiye hamwe n'uburenganzira bwe (Role)
  const userString = localStorage.getItem('hospital_user');
  const user = userString ? JSON.parse(userString) : { username: 'Staff', role: 'Receptionist' };

  // Umutekano: Niba nta muntu winjiye, ahite asubizwa inyuma kuri Login
  useEffect(() => {
    const token = localStorage.getItem('hospital_token');
    if (!token) {
      navigate('/');
    }
  }, [navigate]);

  const logout = () => {
    localStorage.removeItem('hospital_token');
    localStorage.removeItem('hospital_user');
    navigate('/');
  };

  return (
    <div className="flex h-screen bg-slate-50 text-slate-800 font-sans">
      
      {/* 1. SIDEBAR (Agace k'Ibumoso) */}
      <aside className="w-64 bg-slate-900 text-slate-200 flex flex-col justify-between shadow-xl">
        <div>
          <div className="p-6 border-b border-slate-800 text-center">
            <h1 className="text-lg font-black text-white tracking-wider">🏥 HMS CLINIC</h1>
            <p className="text-[10px] text-teal-400 font-bold uppercase mt-1 tracking-widest">
              Role: {user.role} {/* Kwerekana Role ye */}
            </p>
          </div>

          <nav className="p-4 space-y-1.5 flex-1">
            <button 
              onClick={() => setActiveTab('overview')}
              className={`w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider transition ${
                activeTab === 'overview' ? 'bg-teal-600 text-white shadow-md' : 'hover:bg-slate-800 text-slate-400 hover:text-slate-100'
              }`}
            >
              📊 Overview Panel
            </button>

            {/* CONDITION FOR ADMIN ONLY: Abaganga babonwa n'iza Admin gusa */}
            {user.role === 'Admin' && (
              <button 
                onClick={() => setActiveTab('doctors')}
                className={`w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider transition ${
                  activeTab === 'doctors' ? 'bg-teal-600 text-white shadow-md' : 'hover:bg-slate-800 text-slate-400 hover:text-slate-100'
                }`}
              >
                Docs Menu 🩺
              </button>
            )}

            {/* Abarwayi babonwa n'abantu bose (Admin, Receptionist, Doctor) */}
            <button 
              onClick={() => setActiveTab('patients')}
              className={`w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider transition ${
                activeTab === 'patients' ? 'bg-teal-600 text-white shadow-md' : 'hover:bg-slate-800 text-slate-400 hover:text-slate-100'
              }`}
            >
              🛌 Patient Registry
            </button>

            {/* Appointments zibonwa na Admin hamwe na Receptionist gusa */}
            {(user.role === 'Admin' || user.role === 'Receptionist') && (
              <button 
                onClick={() => setActiveTab('appointments')}
                className={`w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider transition ${
                  activeTab === 'appointments' ? 'bg-teal-600 text-white shadow-md' : 'hover:bg-slate-800 text-slate-400 hover:text-slate-100'
                }`}
              >
                📅 Appointments
              </button>
            )}

            {user.role === 'Admin' && (
  <button 
    onClick={() => setActiveTab('reports')}
    className={`w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider transition ${
      activeTab === 'reports' ? 'bg-teal-600 text-white shadow-md' : 'hover:bg-slate-800 text-slate-400 hover:text-slate-100'
    }`}
  >
    📈 System Reports
  </button>
)}

          </nav>
        </div>

        <div className="p-4 border-t border-slate-800">
          <button 
            onClick={logout}
            className="w-full bg-red-600/10 hover:bg-red-600 text-red-400 hover:text-white text-xs font-bold uppercase tracking-wider py-2.5 px-4 rounded-xl transition cursor-pointer text-center"
          >
            🚪 Sign Out Clinic
          </button>
        </div>
      </aside>

      {/* 2. MAIN WORKSPACE (Agace k'Iburyo) */}
      <main className="flex-1 flex flex-col overflow-y-auto">
        <header className="bg-white border-b border-slate-200 py-4 px-8 flex justify-between items-center shadow-sm">
          <h2 className="text-sm font-black text-slate-700 uppercase tracking-widest">{activeTab} Management</h2>
          <div className="text-xs font-semibold text-slate-500 bg-slate-100 px-3 py-1.5 rounded-full flex items-center gap-2">
            <span className="h-2 w-2 rounded-full bg-teal-500 animate-pulse"></span>
            User: <span className="text-slate-800 font-bold">{user.username} ({user.role})</span>
          </div>
        </header>

        <div className="p-8">
          
          {/* OVERVIEW COMPONENT PANEL */}
          {activeTab === 'overview' && (
            <div className="space-y-6">
              <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
                <h3 className="text-lg font-black text-slate-800">Uhawe Ikaze, {user.username}! 👋</h3>
                <p className="text-slate-500 text-xs mt-1">Urubuga rwawe rwafungutse nka **{user.role}**. Koresha menu y'ibumoso ukore akazi kashinzwe inyandiko zawe.</p>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
                {/* Widgets na zo zishunzwe amategeko */}
                {user.role === 'Admin' && (
                  <div onClick={() => setActiveTab('doctors')} className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition cursor-pointer">
                    <div className="text-xl mb-2">🩺</div>
                    <div className="text-xs font-bold text-slate-400 uppercase tracking-wider">Total Doctors</div>
                    <div className="text-lg font-black text-slate-800 mt-1">Manage Staff</div>
                  </div>
                )}
                
                <div onClick={() => setActiveTab('patients')} className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition cursor-pointer">
                  <div className="text-xl mb-2">🛌</div>
                  <div className="text-xs font-bold text-slate-400 uppercase tracking-wider">Patient Records</div>
                  <div className="text-lg font-black text-slate-800 mt-1">Registry / View</div>
                </div>

                {(user.role === 'Admin' || user.role === 'Receptionist') && (
                  <div onClick={() => setActiveTab('appointments')} className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition cursor-pointer">
                    <div className="text-xl mb-2">📅</div>
                    <div className="text-xs font-bold text-slate-400 uppercase tracking-wider">Active Bookings</div>
                    <div className="text-lg font-black text-slate-800 mt-1">Schedules</div>
                  </div>
                )}


                
              </div>
            </div>
          )}

          {/* DYNAMIC TAB RENDERING */}
          {activeTab === 'doctors' && user.role === 'Admin' && <Doctors />}
          {activeTab === 'patients' && <Patients />}
          {activeTab === 'appointments' && (user.role === 'Admin' || user.role === 'Receptionist') && <Appointments />}

          {activeTab === 'reports' && user.role === 'Admin' && <Reports />}


        </div>
      </main>

    </div>
  );
}

export default Dashboard;
