"use client";

import Link from "next/link";
import { loginAction } from "@/app/actions/session";
import { DismissibleBottomToast } from "@/components/dismissible-bottom-toast";
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 [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const toastNotice = error
    ? {
        tone: "error" as const,
        message:
          error === "invalid"
            ? "비밀번호가 일치하지 않습니다."
            : error === "required"
              ? "이메일과 비밀번호를 입력해주세요."
              : "로그인 처리 중 오류가 발생했습니다.",
      }
    : success
      ? {
          tone: "success" as const,
          message:
            success === "password-reset"
              ? "비밀번호가 변경되었습니다. 새 비밀번호로 로그인하세요."
              : "처리가 완료되었습니다.",
        }
      : null;

  return (
    <>
      <DismissibleBottomToast
        notice={toastNotice}
        clearSearchParams={["error", "success", "details"]}
      />
      <form action={loginAction}>
        <div className="overflow-hidden rounded-[14px] border border-[#cfd6dd] bg-white sm:rounded-[16px]">
          <label className="relative block border-b border-[#dfe4ea] px-4 pb-2.5 pt-3.5">
            <span className="block text-[12px] font-semibold text-[#9aa3ad]">
              이메일 주소
            </span>
            <input
              required
              type="email"
              name="email"
              value={email}
              autoComplete="email"
              placeholder="이메일 주소를 입력하세요"
              onChange={(event) => setEmail(event.target.value)}
              className="mt-1.5 h-7 w-full border-0 bg-transparent pr-10 text-[15px] leading-none tracking-[-0.02em] text-[#101418] outline-none placeholder:text-[#c0c6cf] sm:text-[16px]"
            />
            {email ? (
              <button
                type="button"
                onClick={() => setEmail("")}
                className="absolute right-4 top-1/2 -translate-y-1/2 text-[#8f98a4] transition-colors hover:text-[#5f6873]"
                aria-label="이메일 지우기"
              >
                <CircleXIcon />
              </button>
            ) : null}
          </label>

          <label className="relative block px-4 pb-2.5 pt-3.5">
            <span className="block text-[12px] font-semibold text-[#9aa3ad]">
              비밀번호
            </span>
            <input
              required
              type={showPassword ? "text" : "password"}
              name="password"
              value={password}
              autoComplete="current-password"
              placeholder="비밀번호 입력"
              onChange={(event) => setPassword(event.target.value)}
              className="mt-1.5 h-7 w-full border-0 bg-transparent pr-20 text-[15px] leading-none tracking-[-0.02em] text-[#101418] outline-none placeholder:text-[#c0c6cf] sm:text-[16px]"
            />
            <div className="absolute right-4 top-1/2 flex -translate-y-1/2 items-center gap-2 text-[#8f98a4]">
              <button
                type="button"
                onClick={() => setShowPassword((value) => !value)}
                className="transition-colors hover:text-[#5f6873]"
                aria-label={showPassword ? "비밀번호 숨기기" : "비밀번호 보기"}
              >
                <EyeIcon open={showPassword} />
              </button>
              {password ? (
                <button
                  type="button"
                  onClick={() => setPassword("")}
                  className="transition-colors hover:text-[#5f6873]"
                  aria-label="비밀번호 지우기"
                >
                  <CircleXIcon />
                </button>
              ) : null}
            </div>
          </label>
        </div>

        <p className="mt-4 text-[13px] leading-6 text-[#7f8791] sm:text-[14px]">
          회원가입에서 생성한 대표 메일 주소와 동일한 비밀번호로 바로 로그인합니다.
        </p>

        <SubmitButton
          label="로그인"
          pendingLabel="로그인 중..."
          className="om-btn-primary mt-5 h-12 w-full rounded-[14px] px-5 text-[14px] font-semibold"
        />
      </form>

      <div className="mt-5 flex flex-wrap items-center justify-center gap-x-3 gap-y-2 text-[13px] text-[#7f8791]">
        <Link href="/reset-password" className="transition-colors hover:text-[#101418]">
          비밀번호 찾기
        </Link>
        <span className="text-[#d5d9df]">|</span>
        <Link href="/find-id" className="transition-colors hover:text-[#101418]">
          아이디 찾기
        </Link>
        <span className="text-[#d5d9df]">|</span>
        <Link href="/signup" className="transition-colors hover:text-[#101418]">
          회원가입
        </Link>
      </div>

      <p className="mt-4 text-center text-[12px] leading-5 text-[#9099a5]">
        로그인 계정은 별도 서비스 아이디가 아니라 대표 메일 주소 자체입니다.
      </p>
    </>
  );
}
