import React, { useState, useEffect } from 'react';
import '../App.css';
import './AdminView.css';
import LoginForm from '../components/admin/LoginForm';
import PharmacyManagement from '../components/admin/PharmacyManagement';
import MedicineManagement from '../components/admin/MedicineManagement';
import PharmacyMedicineLink from '../components/admin/PharmacyMedicineLink';

function AdminView() {
  const [authenticated, setAuthenticated] = useState(false);
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('pharmacies'); // 'pharmacies', 'medicines', 'link'

  useEffect(() => {
    checkAuth();
  }, []);

  const checkAuth = async () => {
    try {
      const response = await fetch('/api/auth/check', {
        credentials: 'include',
      });
      const data = await response.json();
      
      if (data.authenticated) {
        setAuthenticated(true);
        setUser(data.user);
      } else {
        setAuthenticated(false);
        setUser(null);
      }
    } catch (error) {
      console.error('Error checking auth:', error);
      setAuthenticated(false);
    } finally {
      setLoading(false);
    }
  };

  const handleLogin = (userData) => {
    setAuthenticated(true);
    setUser(userData);
  };

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout', {
        method: 'POST',
        credentials: 'include',
      });
      setAuthenticated(false);
      setUser(null);
    } catch (error) {
      console.error('Error logging out:', error);
    }
  };

  if (loading) {
    return (
      <div className="app-main">
        <div className="loading">Checking authentication...</div>
      </div>
    );
  }

  if (!authenticated) {
    return (
      <>
        <header className="app-header">
          <h1>⚙️ Admin Panel</h1>
          <p>Authentication required</p>
        </header>
        <main className="app-main">
          <LoginForm onLogin={handleLogin} />
        </main>
      </>
    );
  }

  return (
    <>
      <header className="app-header">
        <div className="admin-header-content">
          <div>
            <h1>⚙️ Admin Panel</h1>
            <p>Manage pharmacies and medicines</p>
          </div>
          <div className="admin-user-info">
            <span>👤 {user?.username}</span>
            <button className="logout-button" onClick={handleLogout}>
              Logout
            </button>
          </div>
        </div>
      </header>

      <main className="app-main">
        <div className="admin-tabs">
          <button 
            className={`admin-tab ${activeTab === 'pharmacies' ? 'active' : ''}`}
            onClick={() => setActiveTab('pharmacies')}
          >
            🏥 Pharmacies
          </button>
          <button 
            className={`admin-tab ${activeTab === 'medicines' ? 'active' : ''}`}
            onClick={() => setActiveTab('medicines')}
          >
            💊 Medicines
          </button>
          <button 
            className={`admin-tab ${activeTab === 'link' ? 'active' : ''}`}
            onClick={() => setActiveTab('link')}
          >
            🔗 Link Medicine to Pharmacy
          </button>
        </div>

        <div className="admin-content">
          {activeTab === 'pharmacies' && <PharmacyManagement />}
          {activeTab === 'medicines' && <MedicineManagement />}
          {activeTab === 'link' && <PharmacyMedicineLink />}
        </div>
      </main>
    </>
  );
}

export default AdminView;

