import React from "react";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import App from "@/App";
import { ProtectedRoute, useAuth } from "@features/auth";
import { ComponentDemo, EditPosition } from "@/components";

// Simple login page component
const LoginPage = () => {
  const { isAuthenticated, signinRedirect } = useAuth();

  // Redirect to main app if already authenticated
  if (isAuthenticated) {
    return <Navigate to="/" replace />;
  }

  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-[#131215]">
      <div className="text-center text-white mb-8">
        <h1 className="text-3xl font-bold mb-4">App</h1>
        <p className="text-[#adaab7] mb-8">
          Please log in to access the application
        </p>
        <button
          className="px-8 py-3 bg-[#653cee] text-white rounded-md hover:bg-[#5433c9]"
          onClick={() => signinRedirect()}
        >
          Log In
        </button>
      </div>
    </div>
  );
};

// Callback page for handling authentication redirects
const CallbackPage = () => {
  const { isLoading, isAuthenticated, error } = useAuth();

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-[#131215]">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-[#653cee]"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-[#131215]">
        <div className="text-center text-red-500">
          <div className="text-xl mb-4">Authentication Error</div>
          <div className="mb-4">{error.message}</div>
          <button
            className="mt-4 px-4 py-2 bg-[#653cee] text-white rounded-md"
            onClick={() => (window.location.href = "/login")}
          >
            Return to Login
          </button>
        </div>
      </div>
    );
  }

  // Redirect to main app if authentication was successful
  return <Navigate to="/" replace />;
};

// Main router component
export const AppRouter = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route path="/callback" element={<CallbackPage />} />
        <Route path="/components" element={<ComponentDemo />} />
        <Route
          path="/edit-position"
          element={
            <div className="min-h-screen">
              <EditPosition
                onSave={(data) => console.log("Saved:", data)}
                onCancel={() => window.history.back()}
              />
            </div>
          }
        />
        <Route
          path="/*"
          element={
            <ProtectedRoute>
              <App />
            </ProtectedRoute>
          }
        />
      </Routes>
    </BrowserRouter>
  );
};
