"use client";

import { signIn } from "next-auth/react";
import { useState, useEffect, SetStateAction } from "react";
import { useRouter } from "next/navigation";
import { Input } from "@/app/shadcn_components/ui/input";
import { Button } from "@/app/shadcn_components/ui/button";
import { ChevronRightIcon } from "@heroicons/react/20/solid";

export default function EmailSignInButton({
  error: initialError,
}: {
  error: string | undefined;
}) {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [error, setError] = useState(initialError);
  const [status, setStatus] = useState<"idle" | "sending">("idle");

  const handleSubmit = async (e: { preventDefault: () => void }) => {
    e.preventDefault();
    setStatus("sending");

    const res = await signIn("email", { email, redirect: false });

    if (res?.error) {
      setError("You are not a valid user.");
      setStatus("idle");
      return;
    }

    router.push(`/auth/verify-code?email=${encodeURIComponent(email)}`);
  };

  const handleEmailChange = (e: {
    target: { value: SetStateAction<string> };
  }) => {
    setEmail(e.target.value);
    if (error) setError(undefined);
  };

  // Keep server-side error synced
  useEffect(() => setError(initialError), [initialError]);

  return (
    <form onSubmit={handleSubmit} className="w-full">
      <div className="flex items-center w-full space-x-1">
        <Input
          type="email"
          value={email}
          onChange={handleEmailChange}
          placeholder="Enter email"
          required
          className="flex-1 h-10 rounded-lg border-gray-300"
        />
        <Button
          type="submit"
          disabled={status === "sending"}
          className="h-10 w-10 bg-brandblue text-white hover:bg-hoverblue rounded-lg flex items-center justify-center"
        >
          <ChevronRightIcon className="h-5 w-5" />
        </Button>
      </div>

      <div className="min-h-[3rem] text-center">
        {error && <p className="text-red-500">{error}</p>}
        {status === "sending" && (
          <p className="text-gray-500">Sending sign-in code...</p>
        )}
      </div>
    </form>
  );
}
