"use client";

import * as Dialog from "@radix-ui/react-dialog";
import { useFormStatus } from "react-dom";
import { useLoginModal } from "@/app/LoginModalContext";
import { login } from "@/auth/actions";
import "./LoginModal.css";
import "./login/LoginForm.css";

function ModalFormContent({ returnUrl }: { returnUrl: string }) {
  const { pending } = useFormStatus();
  const { closeLoginModal } = useLoginModal();

  return (
    <Dialog.Content
      className="LoginModal"
      onEscapeKeyDown={(e) => pending && e.preventDefault()}
      onPointerDownOutside={(e) => pending && e.preventDefault()}
      onCloseAutoFocus={(e) => e.preventDefault()}
    >
      <div className="LoginModal-content">
        <Dialog.Close asChild disabled={pending}>
          <button
            className="LoginModal-close"
            aria-label="Close"
            disabled={pending}
            onClick={() => !pending && closeLoginModal()}
          >
            ×
          </button>
        </Dialog.Close>
        <Dialog.Title className="LoginModal-title">sidetrail</Dialog.Title>
        <Dialog.Description className="LoginModal-subtitle">
          sign in with your{" "}
          <a href="https://internethandle.org/#start" target="_blank" rel="noopener noreferrer">
            internet handle
          </a>
        </Dialog.Description>
        <div className="LoginForm">
          <input
            type="text"
            name="loginHint"
            placeholder="alice.bsky.social"
            className="LoginForm-input"
            required
            autoFocus
            readOnly={pending}
          />
          <input type="hidden" name="returnUrl" value={returnUrl} />
          <button type="submit" className="LoginForm-button" disabled={pending}>
            {pending ? "signing in..." : "continue"}
          </button>
        </div>
      </div>
    </Dialog.Content>
  );
}

export function LoginModal() {
  const { isOpen, closeLoginModal } = useLoginModal();
  const returnUrl = typeof window !== "undefined" ? window.location.pathname : "/";

  const handleOpenChange = (open: boolean) => {
    if (!open) {
      closeLoginModal();
    }
  };

  return (
    <Dialog.Root open={isOpen} onOpenChange={handleOpenChange}>
      <Dialog.Portal>
        <Dialog.Overlay className="LoginModal-backdrop" />
        <form action={login}>
          <ModalFormContent returnUrl={returnUrl} />
        </form>
      </Dialog.Portal>
    </Dialog.Root>
  );
}
