"use client";

import { useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import { useAuth } from "@/lib/auth/AuthContext";
import Loader from "@/components/ui/Loader";

type Role = "customer" | "seller" | "transporter";

export function RequireAuth({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const { isAuthenticated, loading } = useAuth();

  useEffect(() => {
    if (!loading && !isAuthenticated) {
      router.replace(`/login?redirect=${encodeURIComponent(pathname)}`);
    }
  }, [loading, isAuthenticated, router, pathname]);

  if (loading || !isAuthenticated) {
    return (
      <div className="rounded-xl bg-white p-10 shadow-sm ring-1 ring-gray-100">
        <Loader label="Loading…" />
      </div>
    );
  }
  return <>{children}</>;
}

export function RequireRole({
  allowed,
  children,
  fallbackHref = "/dashboard",
}: {
  allowed: Role[];
  children: React.ReactNode;
  fallbackHref?: string;
}) {
  const router = useRouter();
  const { user, loading } = useAuth();

  useEffect(() => {
    if (loading) return;
    const type = (user?.type ?? "customer") as Role;
    if (!allowed.includes(type)) {
      router.replace(fallbackHref);
    }
  }, [loading, user, allowed, fallbackHref, router]);

  if (loading) {
    return (
      <div className="rounded-xl bg-white p-10 shadow-sm ring-1 ring-gray-100">
        <Loader label="Loading…" />
      </div>
    );
  }
  const type = (user?.type ?? "customer") as Role;
  if (!allowed.includes(type)) return null;
  return <>{children}</>;
}

export function RequireEmail({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const { user, loading } = useAuth();

  const needsEmail =
    user &&
    (user.type === "customer" || user.type === "seller") &&
    (user.email === null || user.email === "");

  useEffect(() => {
    if (loading) return;
    if (!needsEmail) return;
    if (pathname.startsWith("/profile")) return;
    router.replace("/profile?edit=true");
  }, [loading, needsEmail, pathname, router]);

  if (loading) return null;
  if (needsEmail && !pathname.startsWith("/profile")) return null;
  return <>{children}</>;
}
