import { BrowserRouter, Routes, Route, Navigate, useLocation } from "react-router-dom";
import { supabase } from "./services/supabase";
import { useEffect, useState, createContext, useContext } from "react";
import Login from "./components/Login";
import EmployeeCard from "./components/EmployeeCard";
import IdCardGenerator from "./Generator";
import "./components/Login.css";

const AuthContext = createContext(null);

export const useAuth = () => useContext(AuthContext);

const ALLOWED_DOMAIN = "@gomezleemarketing.com";
const GLM_LOGO = "https://dbit.digitalcompass.agency/storage/v1/object/public/public-assets/GLM_completo.png";

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!supabase) {
      console.warn("Supabase no configurado - falta VITE_SUPABASE_ANON_KEY");
      setLoading(false);
      return;
    }

    supabase.auth.getSession().then(({ data: { session } }) => {
      setUser(session?.user ?? null);
      setLoading(false);
    });

    const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
      setUser(session?.user ?? null);
      setLoading(false);
    });

    return () => subscription.unsubscribe();
  }, []);

  const signOut = async () => {
    if (supabase) await supabase.auth.signOut();
  };

  if (loading) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#EEF6E8',
        fontFamily: 'Arial, sans-serif'
      }}>
        <div style={{
          width: 40, height: 40, border: '3px solid #D0D0D0',
          borderTopColor: '#6CC24A', borderRadius: '50%',
          animation: 'spin 0.8s linear infinite'
        }} />
      </div>
    );
  }

  return (
    <AuthContext.Provider value={{ user, signOut, loading }}>
      {children}
    </AuthContext.Provider>
  );
}

function ProtectedRoute({ children }) {
  const { user, signOut, loading } = useAuth();
  const location = useLocation();

  if (loading) return null;

  if (!user) {
    return <Navigate to="/empleado-id/login" state={{ from: location }} replace />;
  }

  if (!user.email?.endsWith(ALLOWED_DOMAIN)) {
    signOut();
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#EEF6E8',
        fontFamily: 'Arial, sans-serif',
        padding: '20px',
        textAlign: 'center'
      }}>
        <img src={GLM_LOGO} alt="GLM" style={{ maxWidth: 220, marginBottom: 24 }} />
        <h1 style={{ color: '#4F758B', fontSize: 24, fontWeight: 700, marginBottom: 16 }}>
          Acceso no autorizado
        </h1>
        <p style={{ color: '#6B8FA3', fontSize: 16, marginBottom: 24, maxWidth: 400 }}>
          Solo se permite acceso con cuentas corporativas <strong>@gomezleemarketing.com</strong>.
          Tu cuenta <strong>{user.email}</strong> no tiene permisos.
        </p>
        <button
          onClick={signOut}
          style={{
            padding: '14px 32px',
            fontSize: 15,
            fontWeight: 600,
            fontFamily: 'Arial',
            color: '#fff',
            background: '#4F758B',
            border: 'none',
            borderRadius: 10,
            cursor: 'pointer'
          }}
        >
          Cerrar sesión y volver a intentar
        </button>
      </div>
    );
  }

  return children;
}

function PublicRoute({ children }) {
  const { user, loading } = useAuth();
  const location = useLocation();

  if (loading) return null;

  if (user?.email?.endsWith(ALLOWED_DOMAIN)) {
    const from = location.state?.from?.pathname || '/empleado-id/';
    return <Navigate to={from} replace />;
  }

  return children;
}

export default function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <Routes>
          <Route
            path="/empleado-id/login"
            element={
              <PublicRoute>
                <Login />
              </PublicRoute>
            }
          />

          <Route
            path="/empleado-id/"
            element={
              <ProtectedRoute>
                <IdCardGenerator />
              </ProtectedRoute>
            }
          />

          <Route
            path="/empleado-id/:employeeNumber"
            element={
              <ProtectedRoute>
                <EmployeeCard />
              </ProtectedRoute>
            }
          />

          <Route path="*" element={<Navigate to="/empleado-id/" replace />} />
        </Routes>
      </BrowserRouter>
    </AuthProvider>
  );
}