'use client';

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from 'react';

interface CustomerAuthContextValue {
  email: string | null;
  name: string | null;
  isAuthenticated: boolean;
  isMenuManager: boolean;
  isLoading: boolean;
  refreshSession: () => Promise<void>;
  logout: () => Promise<void>;
}

const CustomerAuthContext = createContext<CustomerAuthContextValue>({
  email: null,
  name: null,
  isAuthenticated: false,
  isMenuManager: false,
  isLoading: true,
  refreshSession: async () => {},
  logout: async () => {},
});

export function CustomerAuthProvider({ children }: { children: ReactNode }) {
  const [email, setEmail] = useState<string | null>(null);
  const [name, setName] = useState<string | null>(null);
  const [isMenuManager, setIsMenuManager] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  const refreshSession = useCallback(async () => {
    try {
      const response = await fetch('/api/auth/customer/session', { cache: 'no-store' });
      const data = (await response.json()) as {
        authenticated: boolean;
        email: string | null;
        name?: string | null;
        isMenuManager?: boolean;
      };

      if (data.authenticated && data.email) {
        setEmail(data.email);
        setName(data.name ?? null);
        setIsMenuManager(Boolean(data.isMenuManager));
      } else {
        setEmail(null);
        setName(null);
        setIsMenuManager(false);
      }
    } catch {
      setEmail(null);
      setName(null);
      setIsMenuManager(false);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const logout = useCallback(async () => {
    try {
      await fetch('/api/auth/customer/logout', {
        method: 'POST',
        credentials: 'include',
        cache: 'no-store',
      });
    } finally {
      setEmail(null);
      setName(null);
      setIsMenuManager(false);
      window.dispatchEvent(new Event('shahi-customer-auth-changed'));
      window.location.assign('/');
    }
  }, []);

  useEffect(() => {
    void refreshSession();
  }, [refreshSession]);

  useEffect(() => {
    const onAuthChanged = () => {
      void refreshSession();
    };
    const onVisible = () => {
      if (document.visibilityState === 'visible') {
        void refreshSession();
      }
    };

    window.addEventListener('shahi-customer-auth-changed', onAuthChanged);
    document.addEventListener('visibilitychange', onVisible);
    return () => {
      window.removeEventListener('shahi-customer-auth-changed', onAuthChanged);
      document.removeEventListener('visibilitychange', onVisible);
    };
  }, [refreshSession]);

  const value = useMemo(
    () => ({
      email,
      name,
      isAuthenticated: Boolean(email),
      isMenuManager,
      isLoading,
      refreshSession,
      logout,
    }),
    [email, name, isMenuManager, isLoading, refreshSession, logout],
  );

  return <CustomerAuthContext.Provider value={value}>{children}</CustomerAuthContext.Provider>;
}

export function useCustomerAuth() {
  return useContext(CustomerAuthContext);
}