"use client";

import { useEffect, useState } from "react";
import type { AuthMethod } from "@/types";

export interface AuthPolicyPreview {
  email: string;
  domain: string | null;
  matchedOrganizations: Array<{
    id: string;
    name: string;
    slug: string;
    invite_only: boolean;
    enforce_sso: boolean;
  }>;
  allowedMethods: AuthMethod[];
  autoJoinEnabled: boolean;
}

const DEFAULT_PREVIEW: AuthPolicyPreview = {
  email: "",
  domain: null,
  matchedOrganizations: [],
  allowedMethods: ["password", "magic_link", "google", "github", "azure"],
  autoJoinEnabled: false,
};

export function useAuthPolicyPreview(email: string) {
  const [preview, setPreview] = useState<AuthPolicyPreview>(DEFAULT_PREVIEW);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const normalizedEmail = email.trim().toLowerCase();
    if (!normalizedEmail || !normalizedEmail.includes("@")) {
      setPreview(DEFAULT_PREVIEW);
      setLoading(false);
      return;
    }

    let cancelled = false;
    setLoading(true);

    const timer = window.setTimeout(async () => {
      try {
        const res = await fetch(
          `/api/auth/policies/lookup?email=${encodeURIComponent(normalizedEmail)}`
        );
        const data = await res.json();
        if (!cancelled && res.ok) {
          setPreview(data as AuthPolicyPreview);
        }
      } catch (error) {
        console.error("Failed to load auth policy preview", error);
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }, 250);

    return () => {
      cancelled = true;
      window.clearTimeout(timer);
    };
  }, [email]);

  return {
    preview,
    loading,
  };
}
