import React, { useEffect } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Loader2 } from "lucide-react";

export default function Home() {
  const navigate = useNavigate();

  const { data: user, isLoading } = useQuery({
    queryKey: ['current-user-redirect'],
    queryFn: () => base44.auth.me(),
  });

  useEffect(() => {
    if (user) {
      const userRole = user.user_role || user.role || "admin";
      
      // Route to appropriate dashboard based on role
      const dashboardMap = {
        admin: "Dashboard",
        procurement: "ProcurementDashboard",
        operator: "OperatorDashboard",
        sector: "OperatorDashboard",
        client: "ClientDashboard",
        vendor: "VendorDashboard",
        workforce: "WorkforceDashboard"
      };

      const targetDashboard = dashboardMap[userRole] || "Dashboard";
      navigate(createPageUrl(targetDashboard), { replace: true });
    }
  }, [user, navigate]);

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-[#0A39DF] animate-spin mx-auto mb-4" />
          <p className="text-slate-600 font-medium">Loading your dashboard...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100">
      <div className="text-center">
        <Loader2 className="w-12 h-12 text-[#0A39DF] animate-spin mx-auto mb-4" />
        <p className="text-slate-600 font-medium">Redirecting...</p>
      </div>
    </div>
  );
}