"use client";

import { useEffect, useRef, useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import { Lock, Eye, EyeOff, ArrowRight, Shield } from "lucide-react";
import { apiCall } from "@/lib/api/client";
import "../login/login.css";

/**
 * 첫 로그인 비밀번호 강제 변경 화면.
 * - 로그인 응답의 force_password_change=true 일 때 useLogin 이 여기로 보냄
 * - sessionStorage.pwChangeNext 에 원래 가려던 경로가 보관되어 있음
 * - 성공 시 그 경로로 이동
 *
 * 디자인: login 의 cosmic 배경 + glass 카드 스코프 (`.inv-login`) 를 그대로 재사용.
 */
export default function ChangePasswordPage() {
  const router = useRouter();
  const { theme, resolvedTheme } = useTheme();
  const isDark = (resolvedTheme ?? theme) === "dark";

  const rootRef = useRef<HTMLDivElement>(null);
  const cosmosRef = useRef<HTMLDivElement>(null);
  const cardRef = useRef<HTMLDivElement>(null);
  const errRef = useRef<HTMLDivElement>(null);

  const [currentPw, setCurrentPw] = useState("");
  const [newPw, setNewPw] = useState("");
  const [confirmPw, setConfirmPw] = useState("");
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    root.classList.toggle("dark", isDark);
  }, [isDark]);

  // 로그인과 동일한 cosmic 배경 생성
  useEffect(() => {
    const co = cosmosRef.current;
    if (!co) return;
    const cs = ["rgba(var(--v5-primary-rgb),.8)", "rgba(var(--v5-cyan-rgb),.7)", "rgba(var(--v5-pink-rgb),.7)"];
    for (let i = 0; i < 30; i++) {
      const s = document.createElement("div");
      s.className = "star" + (Math.random() > 0.83 ? " c" : "");
      if (s.classList.contains("c")) s.style.setProperty("--sc", cs[(Math.random() * 3) | 0]);
      s.style.left = Math.random() * 100 + "%";
      s.style.top = Math.random() * 100 + "%";
      s.style.setProperty("--d", 2 + Math.random() * 5 + "s");
      s.style.setProperty("--dl", Math.random() * 5 + "s");
      s.style.setProperty("--mo", 0.3 + Math.random() * 0.7 + "");
      co.appendChild(s);
    }
    return () => {
      co.querySelectorAll(".star").forEach((el) => el.remove());
    };
  }, []);

  useEffect(() => {
    if (!error || !cardRef.current || !errRef.current) return;
    const card = cardRef.current;
    const errEl = errRef.current;
    card.classList.remove("denied");
    void card.offsetWidth;
    card.classList.add("denied");
    errEl.classList.add("show");
    const t1 = setTimeout(() => card.classList.remove("denied"), 600);
    const t2 = setTimeout(() => errEl.classList.remove("show"), 3000);
    return () => {
      clearTimeout(t1);
      clearTimeout(t2);
    };
  }, [error]);

  const handleRipple = useCallback((e: React.MouseEvent<HTMLButtonElement>) => {
    const btn = e.currentTarget;
    const r = btn.getBoundingClientRect();
    const d = document.createElement("div");
    d.className = "rip";
    const sz = Math.max(r.width, r.height) * 2;
    d.style.width = d.style.height = sz + "px";
    d.style.left = e.clientX - r.left - sz / 2 + "px";
    d.style.top = e.clientY - r.top - sz / 2 + "px";
    btn.appendChild(d);
    setTimeout(() => d.remove(), 600);
  }, []);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");

    if (!currentPw || !newPw || !confirmPw) {
      setError("모든 항목을 입력해주세요.");
      return;
    }
    if (newPw.length < 8) {
      setError("새 비밀번호는 8자 이상이어야 합니다.");
      return;
    }
    if (newPw === currentPw) {
      setError("기존 비밀번호와 동일합니다. 다른 비밀번호를 사용하세요.");
      return;
    }
    if (newPw !== confirmPw) {
      setError("새 비밀번호 확인이 일치하지 않습니다.");
      return;
    }

    setIsLoading(true);
    try {
      const result = await apiCall<{ token?: string }>("POST", "/auth/change-password", {
        current_password: currentPw,
        new_password: newPw,
      });
      if (!result.success) {
        setError(result.message || "비밀번호 변경에 실패했습니다.");
        setIsLoading(false);
        return;
      }
      // 새 JWT 로 교체 — 서버 가드 필터가 force_password_change=false 새 토큰에서만 다른 API 를 허용한다.
      const newToken = result.data?.token;
      if (newToken) {
        localStorage.setItem("authToken", newToken);
        document.cookie = `authToken=${newToken}; path=/; max-age=86400; SameSite=Lax`;
      }
      const next = sessionStorage.getItem("pwChangeNext") || "/main";
      sessionStorage.removeItem("pwChangeNext");
      router.push(next);
    } catch (err: any) {
      setError(err?.message || "네트워크 오류");
      setIsLoading(false);
    }
  }

  return (
    <div ref={rootRef} className="inv-login">
      <div ref={cosmosRef} className="cosmos">
        <div className="neb neb-1" />
        <div className="neb neb-2" />
        <div className="neb neb-3" />
        <div className="neb neb-4" />
        <div className="shooting-star" style={{ top: "12%", left: "70%" }} />
        <div className="shooting-star" style={{ top: "35%", left: "55%" }} />
      </div>

      <div ref={cardRef} className="login-card">
        <div className="login-orbit">
          <div className="orbit-ring" />
          <div className="orbit-ring-2" />
          <div className="orbit-dot" />
          <div className="orbit-core" />
        </div>

        <div
          className="logo"
          style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }}
        >
          <Shield width={22} height={22} />
          <h1 style={{ margin: 0 }}>비밀번호 변경</h1>
        </div>
        <div className="login-sub">첫 로그인입니다. 새 비밀번호를 설정해주세요.</div>

        <form onSubmit={onSubmit}>
          <div className="fg">
            <div className="fi-wrap pw-w">
              <Lock className="fi-icon" width={16} height={16} />
              <input
                className="fi"
                name="current_password"
                type={showCurrent ? "text" : "password"}
                placeholder="현재 비밀번호 (초기 비밀번호)"
                value={currentPw}
                onChange={(e) => setCurrentPw(e.target.value)}
                disabled={isLoading}
                autoComplete="current-password"
              />
              <button
                type="button"
                className="pw-b"
                onClick={() => setShowCurrent((v) => !v)}
                disabled={isLoading}
              >
                {showCurrent ? <EyeOff width={16} height={16} /> : <Eye width={16} height={16} />}
              </button>
            </div>
          </div>

          <div className="fg">
            <div className="fi-wrap pw-w">
              <Lock className="fi-icon" width={16} height={16} />
              <input
                className={`fi${error ? " error" : ""}`}
                name="new_password"
                type={showNew ? "text" : "password"}
                placeholder="새 비밀번호 (8자 이상)"
                value={newPw}
                onChange={(e) => setNewPw(e.target.value)}
                disabled={isLoading}
                autoComplete="new-password"
              />
              <button
                type="button"
                className="pw-b"
                onClick={() => setShowNew((v) => !v)}
                disabled={isLoading}
              >
                {showNew ? <EyeOff width={16} height={16} /> : <Eye width={16} height={16} />}
              </button>
            </div>
          </div>

          <div className="fg">
            <div className="fi-wrap pw-w">
              <Lock className="fi-icon" width={16} height={16} />
              <input
                className={`fi${error ? " error" : ""}`}
                name="confirm_password"
                type={showNew ? "text" : "password"}
                placeholder="새 비밀번호 확인"
                value={confirmPw}
                onChange={(e) => setConfirmPw(e.target.value)}
                disabled={isLoading}
                autoComplete="new-password"
              />
            </div>
          </div>

          <div className="login-divider">
            <span>change</span>
          </div>

          <button
            type="submit"
            className="lbtn"
            disabled={isLoading}
            onMouseDown={handleRipple}
          >
            {isLoading ? (
              <span className="spinner" />
            ) : (
              <>
                <span>변경하기</span>
                <ArrowRight width={16} height={16} />
              </>
            )}
          </button>
        </form>

        <div ref={errRef} className="err-msg">
          {error || "새 비밀번호를 입력해주세요"}
        </div>
        <div className="login-ft">&copy; 2026 Invy.one</div>
      </div>
    </div>
  );
}
