"use client";

import { signIn } from "next-auth/react";
import { useState, useEffect, SetStateAction } from "react";
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 [email, setEmail] = useState("");
  const [error, setError] = useState(initialError);
  const [status, setStatus] = useState<"idle" | "sending" | "sent">("idle");

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

    console.log("BEFOERE SIGN IN");
    console.log("window.location.origin:", window.location.origin);
    const res = await signIn("email", { email, redirect: false });
    console.log("AFTER SIGN IN");

    if (res?.error) {
      setError("You are not a valid user.");
      setStatus("idle");
      console.log("Error signing in:", res.error);
    } else {
      console.log("Sign-in link sent to:", email);
      setError(undefined);
      setStatus("sent");
    }
  };

  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 === "sent" && (
          <p className="text-green-600">
            A login link has been sent to your email.
          </p>
        )}
        {status === "sending" && (
          <p className="text-gray-500">Sending login link...</p>
        )}
      </div>
    </form>
  );
}
