"use client";

import { loginAction } from "@/app/actions/session";
import { AuthTransitionLink } from "@/components/auth-transition";
import { DismissibleBottomToast } from "@/components/dismissible-bottom-toast";
import { useI18n } from "@/components/i18n-provider";
import { SubmitButton } from "@/components/submit-button";
import { useState } from "react";

type LoginPageFormProps = {
  error?: string;
  success?: string;
};

function CircleXIcon() {
  return (
    <svg viewBox="0 0 20 20" fill="none" className="h-5 w-5">
      <circle cx="10" cy="10" r="8" fill="currentColor" opacity="0.14" />
      <path
        d="m7 7 6 6M13 7l-6 6"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
      />
    </svg>
  );
}

function EyeIcon({ open }: { open: boolean }) {
  if (open) {
    return (
      <svg viewBox="0 0 24 24" fill="none" className="h-5 w-5">
        <path
          d="M2.5 12s3.4-6 9.5-6 9.5 6 9.5 6-3.4 6-9.5 6-9.5-6-9.5-6Z"
          stroke="currentColor"
          strokeWidth="1.8"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
        <circle cx="12" cy="12" r="2.8" stroke="currentColor" strokeWidth="1.8" />
      </svg>
    );
  }

  return (
    <svg viewBox="0 0 24 24" fill="none" className="h-5 w-5">
      <path
        d="M3 4.5 21 19.5"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
      />
      <path
        d="M10.6 6.2A10 10 0 0 1 12 6c6.1 0 9.5 6 9.5 6a16.6 16.6 0 0 1-3.2 3.8"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path
        d="M6.7 7.1C4.3 8.7 2.5 12 2.5 12s3.4 6 9.5 6c1.4 0 2.6-.3 3.7-.7"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function LoginPageForm({ error, success }: LoginPageFormProps) {
  const { t } = useI18n();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [rememberDevice, setRememberDevice] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const toastNotice = error
    ? {
        tone: "error" as const,
        message:
          error === "invalid"
            ? t("auth.error.invalid")
            : error === "growth-plan-required"
              ? t("auth.error.growthPlanRequired")
            : error === "required"
              ? t("auth.error.required")
              : t("auth.error.default"),
      }
    : success
      ? {
          tone: "success" as const,
          message:
            success === "password-reset"
              ? t("auth.success.passwordReset")
              : t("auth.success.default"),
        }
      : null;

  return (
    <>
      <DismissibleBottomToast
        notice={toastNotice}
        clearSearchParams={["error", "success", "details"]}
      />
      <form action={loginAction}>
        <div className="space-y-3.5">
          <div>
            <label
              htmlFor="officialmail-login-email"
              className="mb-2 block text-[13px] font-semibold text-[#536076]"
            >
              {t("auth.email.label")}
            </label>
            <div className="relative">
              <input
                id="officialmail-login-email"
                required
                type="email"
                name="email"
                value={email}
                autoComplete="email"
                placeholder={t("auth.email.placeholder")}
                onChange={(event) => setEmail(event.target.value)}
                className="h-12 w-full rounded-[12px] border border-[#d7deea] bg-white px-4 pr-12 text-[14px] tracking-[-0.02em] text-[#10182c] outline-none transition-[border-color,box-shadow,background-color] placeholder:text-[#b4bdca] hover:border-[#c1cce0] focus:border-[#2f6df6] focus:bg-[#fbfdff] focus:shadow-[0_0_0_4px_rgba(47,109,246,0.1)]"
              />
              {email ? (
                <button
                  type="button"
                  onClick={() => setEmail("")}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-[#97a2b2] transition-colors hover:text-[#5f6873]"
                  aria-label={t("auth.email.clear")}
                >
                  <CircleXIcon />
                </button>
              ) : null}
            </div>
          </div>

          <div>
            <label
              htmlFor="officialmail-login-password"
              className="mb-2 block text-[13px] font-semibold text-[#536076]"
            >
              {t("auth.password.label")}
            </label>
            <div className="relative">
              <input
                id="officialmail-login-password"
                required
                type={showPassword ? "text" : "password"}
                name="password"
                value={password}
                autoComplete="current-password"
                placeholder={t("auth.password.placeholder")}
                onChange={(event) => setPassword(event.target.value)}
                className="h-12 w-full rounded-[12px] border border-[#d7deea] bg-white px-4 pr-20 text-[14px] tracking-[-0.02em] text-[#10182c] outline-none transition-[border-color,box-shadow,background-color] placeholder:text-[#b4bdca] hover:border-[#c1cce0] focus:border-[#2f6df6] focus:bg-[#fbfdff] focus:shadow-[0_0_0_4px_rgba(47,109,246,0.1)]"
              />
              <div className="absolute right-4 top-1/2 flex -translate-y-1/2 items-center gap-2 text-[#97a2b2]">
                <button
                  type="button"
                  onClick={() => setShowPassword((value) => !value)}
                  className="transition-colors hover:text-[#5f6873]"
                  aria-label={showPassword ? t("auth.password.hide") : t("auth.password.show")}
                >
                  <EyeIcon open={showPassword} />
                </button>
                {password ? (
                  <button
                    type="button"
                    onClick={() => setPassword("")}
                    className="transition-colors hover:text-[#5f6873]"
                    aria-label={t("auth.password.clear")}
                  >
                    <CircleXIcon />
                  </button>
                ) : null}
              </div>
            </div>
          </div>
        </div>

        <div className="mt-4 flex items-center justify-between gap-4">
          <label className="inline-flex cursor-pointer items-center gap-2.5 text-[13px] font-medium text-[#536076]">
            <input
              type="checkbox"
              name="rememberDevice"
              checked={rememberDevice}
              onChange={(event) => setRememberDevice(event.target.checked)}
              className="h-4 w-4 cursor-pointer rounded-[5px] border-[#c8d2e1] text-[#2f6df6] focus:ring-2 focus:ring-[#d7e5ff] focus:ring-offset-0"
            />
            {t("auth.remember")}
          </label>
          <span className="min-w-0 text-right text-[11px] leading-4 text-[#98a2b1] sm:text-[12px]">
            {t("auth.remember.duration")}
          </span>
        </div>

        <SubmitButton
          label={t("auth.login")}
          pendingLabel={t("auth.loggingIn")}
          className="om-btn-primary mt-5 h-12 w-full rounded-[12px] px-5 text-[14px] font-semibold"
        />
      </form>

      <div className="mt-4 flex flex-wrap items-center justify-center gap-x-3 gap-y-2 text-[12px] text-[#7f8999]">
        <AuthTransitionLink
          href="/reset-password"
          className="transition-colors hover:text-[#2f6df6]"
        >
          {t("auth.forgotPassword")}
        </AuthTransitionLink>
        <span className="text-[#d5d9df]">|</span>
        <AuthTransitionLink
          href="/find-id"
          className="transition-colors hover:text-[#2f6df6]"
        >
          {t("auth.findId")}
        </AuthTransitionLink>
      </div>

      <p className="mt-3.5 text-center text-[11px] leading-5 text-[#9aa4b3]">
        {t("auth.login.hint")}
      </p>

      <div className="mt-4 border-t border-[#e6ebf2] pt-4 text-center text-[12px] text-[#7f8999]">
        <span>{t("auth.signupPrompt")}</span>{" "}
        <AuthTransitionLink
          href="/signup"
          className="font-semibold text-[#2f6df6] transition-colors hover:text-[#174acb]"
        >
          {t("auth.signup")}
        </AuthTransitionLink>
      </div>
    </>
  );
}
