"use client";

import { useState, useEffect, FormEvent } from "react";
import { useRouter } from "next/navigation";
import { User, Lock, Eye, EyeOff } from "lucide-react";
import Swal from "sweetalert2";

const SAVE_KEY = "momo_saved_credentials";

export default function MobileLoginPage() {
  const router = useRouter();
  const [userId, setUserId] = useState("");
  const [password, setPassword] = useState("");
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);
  const [remember, setRemember] = useState(true);
  const [saveCreds, setSaveCreds] = useState(false);
  const [splash, setSplash] = useState(true);

  useEffect(() => {
    try {
      const raw = localStorage.getItem(SAVE_KEY);
      if (!raw) return;
      const saved = JSON.parse(raw) as { userId?: string; password?: string };
      if (saved.userId) setUserId(saved.userId);
      if (saved.password) setPassword(saved.password);
      setSaveCreds(true);
    } catch {
      /* ignore */
    }
  }, []);

  // 스플래시: 3 초 후 자연스럽게 fade-out
  useEffect(() => {
    const t = setTimeout(() => setSplash(false), 3000);
    return () => clearTimeout(t);
  }, []);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (!userId || !password) {
      Swal.fire({ icon: "warning", title: "아이디와 비밀번호를 입력하세요." });
      return;
    }
    setLoading(true);
    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId, password, remember }),
      });
      const data = await res.json();
      if (data.success) {
        try {
          if (saveCreds) {
            localStorage.setItem(SAVE_KEY, JSON.stringify({ userId, password }));
          } else {
            localStorage.removeItem(SAVE_KEY);
          }
        } catch {
          /* ignore */
        }
        // 모바일은 항상 /m/dashboard 로
        router.push("/m/dashboard");
      } else {
        Swal.fire({
          icon: "error",
          title: "로그인 실패",
          text: data.message || "아이디 또는 비밀번호를 확인하세요.",
        });
      }
    } catch {
      Swal.fire({ icon: "error", title: "서버 오류", text: "잠시 후 다시 시도하세요." });
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* 스플래시 — 1.5초 동안 표시 후 fade-out */}
      <div
        className={`fixed inset-0 z-[60] flex flex-col items-center justify-center bg-gradient-to-br from-[#0d3b24] via-[#1b5e3a] to-[#0f4a2a] transition-opacity duration-500 ${
          splash ? "opacity-100" : "opacity-0 pointer-events-none"
        }`}
        aria-hidden={!splash}
      >
        <div className="absolute inset-0 pointer-events-none opacity-30"
          style={{
            backgroundImage:
              "radial-gradient(circle at 20% 30%, rgba(126,217,167,0.25) 0, transparent 40%), radial-gradient(circle at 80% 70%, rgba(46,139,87,0.3) 0, transparent 45%)",
          }}
        />
        <div className="relative z-10 flex flex-col items-center">
          <img src="/momo-icon.svg" alt="MOMO" className="w-24 h-24 mb-5 drop-shadow-2xl animate-pulse" />
          <h1 className="text-white text-2xl font-bold tracking-tight">모모유통 ERP</h1>
          <p className="text-emerald-100/70 text-sm mt-2">유통 업무 통합 관리</p>
          <div className="mt-8 flex items-center gap-2 text-emerald-100/80 text-xs">
            <span className="w-4 h-4 border-2 border-emerald-200/40 border-t-emerald-200 rounded-full animate-spin" />
            로딩 중...
          </div>
        </div>
      </div>

    <div
      className="min-h-[100dvh] flex flex-col bg-gradient-to-br from-[#0d3b24] via-[#1b5e3a] to-[#0f4a2a] px-6"
      style={{ paddingTop: "max(env(safe-area-inset-top), 1rem)", paddingBottom: "max(env(safe-area-inset-bottom), 1rem)" }}
    >
      {/* 배경 패턴 */}
      <div
        className="absolute inset-0 pointer-events-none opacity-30"
        style={{
          backgroundImage:
            "radial-gradient(circle at 20% 30%, rgba(126,217,167,0.25) 0, transparent 40%), radial-gradient(circle at 80% 70%, rgba(46,139,87,0.3) 0, transparent 45%)",
        }}
      />

      {/* 헤더: 로고 + 타이틀 */}
      <div className="relative z-10 pt-8 pb-6 flex flex-col items-center">
        <img src="/momo-icon.svg" alt="MOMO" className="w-16 h-16 mb-3 drop-shadow-lg" />
        <h1 className="text-white text-xl font-bold tracking-tight">모모유통 ERP</h1>
        <p className="text-emerald-100/70 text-xs mt-1">유통 업무 통합 관리</p>
      </div>

      {/* 폼 카드 */}
      <div className="relative z-10 flex-1 flex items-center">
        <form
          onSubmit={handleSubmit}
          className="w-full bg-white rounded-2xl shadow-2xl px-5 py-6 space-y-4"
        >
          <div>
            <label className="block text-[11px] font-semibold text-slate-600 mb-1.5 tracking-wide">
              아이디
            </label>
            <div className="relative group">
              <User
                size={16}
                className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400"
              />
              <input
                type="text"
                value={userId}
                onChange={(e) => setUserId(e.target.value)}
                placeholder="아이디"
                autoFocus
                autoComplete="username"
                inputMode="text"
                className="w-full h-11 pl-10 pr-3 rounded-xl border border-slate-200 bg-white text-sm text-slate-900 placeholder-slate-400 focus:outline-none focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 transition"
              />
            </div>
          </div>

          <div>
            <label className="block text-[11px] font-semibold text-slate-600 mb-1.5 tracking-wide">
              비밀번호
            </label>
            <div className="relative group">
              <Lock
                size={16}
                className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400"
              />
              <input
                type={showPw ? "text" : "password"}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="비밀번호"
                autoComplete="current-password"
                className="w-full h-11 pl-10 pr-10 rounded-xl border border-slate-200 bg-white text-sm text-slate-900 placeholder-slate-400 focus:outline-none focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 transition"
              />
              <button
                type="button"
                onClick={() => setShowPw((v) => !v)}
                className="absolute right-2.5 top-1/2 -translate-y-1/2 p-1.5 text-slate-400 active:text-slate-700"
                tabIndex={-1}
              >
                {showPw ? <EyeOff size={16} /> : <Eye size={16} />}
              </button>
            </div>
          </div>

          <div className="space-y-2 pt-1">
            <label className="flex items-center gap-2 cursor-pointer select-none">
              <input
                type="checkbox"
                checked={remember}
                onChange={(e) => setRemember(e.target.checked)}
                className="w-4 h-4 accent-emerald-600"
              />
              <span className="text-xs text-slate-700">로그인 유지</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer select-none">
              <input
                type="checkbox"
                checked={saveCreds}
                onChange={(e) => {
                  setSaveCreds(e.target.checked);
                  if (!e.target.checked) {
                    try {
                      localStorage.removeItem(SAVE_KEY);
                    } catch {
                      /* ignore */
                    }
                  }
                }}
                className="w-4 h-4 accent-emerald-600"
              />
              <span className="text-xs text-slate-700">아이디/비밀번호 저장</span>
            </label>
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full h-12 rounded-xl bg-gradient-to-r from-emerald-700 to-emerald-600 text-white text-sm font-bold tracking-wide shadow-md active:translate-y-px transition disabled:opacity-60"
          >
            {loading ? "로그인 중..." : "로그인"}
          </button>
        </form>
      </div>

      {/* 푸터 */}
      <div className="relative z-10 text-center pb-4 pt-2">
        <p className="text-[10px] text-emerald-100/60 tracking-wide">
          &copy; 2026 MOMO DISTRIBUTION
        </p>
      </div>
    </div>
    </>
  );
}
