"use client";

import {
  createContext,
  useContext,
  useEffect,
  useState,
  type ReactNode,
} from "react";
import { useParams } from "next/navigation";
import DataService from "@/config/axios";
import { ActiveTenantProvider } from "@/platform/context/active-tenant-context";

type TenantInfo = {
  clientId: string;
  slug: string;
  status: string;
  name: string;
};

export type TenantLayoutContext = {
  tenant: TenantInfo | null;
  loading: boolean;
  error: string | null;
};

const TenantSlugContext = createContext<TenantLayoutContext>({
  tenant: null,
  loading: true,
  error: null,
});

export function useTenantSlugContext() {
  return useContext(TenantSlugContext);
}

/**
 * Seeds active org from resolved slug and exposes public tenant profile for landing/login.
 */
export default function TenantSlugLayout({ children }: { children: ReactNode }) {
  const params = useParams();
  const slug = String(params.slug || "");
  const [tenant, setTenant] = useState<TenantInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      if (!slug) {
        setLoading(false);
        setError("Missing slug");
        return;
      }
      try {
        const res = await DataService.get(
          `/platform/resolve?slug=${encodeURIComponent(slug)}`
        );
        const data = res.data?.data as TenantInfo | undefined;
        if (cancelled) return;
        if (!data?.clientId) {
          setError("Tenant not found");
          setTenant(null);
        } else {
          setTenant({
            clientId: data.clientId,
            slug: data.slug,
            status: data.status,
            name: data.name || data.slug,
          });
          try {
            localStorage.setItem("nizamify_active_org", data.clientId);
          } catch {
            /* ignore */
          }
        }
      } catch {
        if (!cancelled) {
          setError("Tenant not found");
          setTenant(null);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [slug]);

  return (
    <TenantSlugContext.Provider value={{ tenant, loading, error }}>
      <ActiveTenantProvider>{children}</ActiveTenantProvider>
    </TenantSlugContext.Provider>
  );
}
