'use client';
import EmailAuthForm from '@/app/auth/email/auth-form';
import { Dialog, DialogContent, DialogTitle } from '@workspace/airo-ui/components/dialog';
import {
  createContext,
  forwardRef,
  ReactNode,
  useContext,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';

type LoginDialogContextType = {
  openLoginDialog: (isRedirect?: boolean) => void;
  closeLoginDialog: () => void;
};

const LoginDialogContext = createContext<LoginDialogContextType | undefined>(undefined);

export function LoginDialogProvider({ children }: { children: ReactNode }) {
  const dialogRef = useRef<{ show: (isRedirect?: boolean) => void; hide: () => void }>(null);

  const openLoginDialog = (isRedirect = true) => dialogRef.current?.show(isRedirect);
  const closeLoginDialog = () => dialogRef.current?.hide();

  return (
    <LoginDialogContext.Provider value={{ openLoginDialog, closeLoginDialog }}>
      <LoginDialog ref={dialogRef} />
      {children}
    </LoginDialogContext.Provider>
  );
}

export function useLoginDialog() {
  const context = useContext(LoginDialogContext);
  if (!context) {
    throw new Error('useLoginDialog must be used within a LoginDialogProvider');
  }
  return context;
}

interface LoginDialogRef {
  show: () => void;
  hide: () => void;
}

const LoginDialog = forwardRef<LoginDialogRef>((props, ref) => {
  const [open, setOpen] = useState(false);
  const [isRedirect, setIsRedirect] = useState(false);

  useImperativeHandle(ref, () => ({
    show: (isRedirect = ture) => {
      setOpen(true);
      setIsRedirect(isRedirect);
    },
    hide,
  }));

  function hide() {
    setIsRedirect(false);
    setOpen(false);
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className='rounded-0 h-full w-full px-12 py-[4.5rem] sm:h-auto sm:w-[496px] sm:!rounded-[50px]'>
        <DialogTitle className='sr-only'>Login</DialogTitle>
        <div className=''>
          <EmailAuthForm hide={hide} isRedirect={isRedirect} />
        </div>
      </DialogContent>
    </Dialog>
  );
});

LoginDialog.displayName = 'LoginDialog';
