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';
import PharmacyProductLink from '../components/admin/PharmacyProductLink';

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">Comprobando autenticación...</div>
      </div>
    );
  }

  if (!authenticated) {
    return (
      <>
        <header className="app-header">
          <h1>⚙️ Panel de Administración</h1>
          <p>Autenticación requerida</p>
        </header>
        <main className="app-main">
          <LoginForm onLogin={handleLogin} />
        </main>
      </>
    );
  }

  return (
    <>
      <header className="app-header">
        <div className="admin-header-content">
          <div>
            <h1>⚙️ Panel de Administración</h1>
            <p>Gestiona farmacias y medicamentos</p>
          </div>
          <div className="admin-user-info">
            <span>👤 {user?.username}</span>
            <button className="logout-button" onClick={handleLogout}>
              Cerrar sesión
            </button>
          </div>
        </div>
      </header>

      <main className="app-main">
        <div className="admin-tabs">
          <button 
            className={`admin-tab ${activeTab === 'pharmacies' ? 'active' : ''}`}
            onClick={() => setActiveTab('pharmacies')}
          >
            🏥 Farmacias
          </button>
          <button 
            className={`admin-tab ${activeTab === 'medicines' ? 'active' : ''}`}
            onClick={() => setActiveTab('medicines')}
          >
            💊 Medicamentos
          </button>
          <button 
            className={`admin-tab ${activeTab === 'link' ? 'active' : ''}`}
            onClick={() => setActiveTab('link')}
          >
            🔗 Vincular Medicamento a Farmacia
          </button>
          <button 
            className={`admin-tab ${activeTab === 'link-product' ? 'active' : ''}`}
            onClick={() => setActiveTab('link-product')}
          >
            🍎 Vincular Producto a Farmacia
          </button>
        </div>

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

export default AdminView;

