"use client";

import { useState, useEffect, FormEvent } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { User, Lock, Eye, EyeOff, ArrowRight, Phone, Mail, MapPin } from "lucide-react";
import Swal from "sweetalert2";

const SAVE_KEY = "momo_saved_credentials"; // localStorage 키

export default function LoginPage() {
  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); // 기본 ON
  const [saveCreds, setSaveCreds] = useState(false); // 아이디/비밀번호 저장

  // 마운트 시 저장된 자격증명 불러오기
  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 */ }
  }, []);

  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) {
        // 저장 옵션에 따라 localStorage 동기화
        try {
          if (saveCreds) {
            localStorage.setItem(SAVE_KEY, JSON.stringify({ userId, password }));
          } else {
            localStorage.removeItem(SAVE_KEY);
          }
        } catch { /* ignore */ }
        router.push(data.redirectTo || "/dashboard");
      } else {
        Swal.fire({
          icon: "error",
          title: "로그인 실패",
          text: data.message || "아이디 또는 비밀번호를 확인하세요.",
        });
      }
    } catch {
      Swal.fire({ icon: "error", title: "서버 오류", text: "잠시 후 다시 시도하세요." });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col lg:flex-row bg-white">
      {/* 좌측: 브랜드 히어로 패널 */}
      <div className="relative lg:flex-1 lg:min-h-screen overflow-hidden bg-gradient-to-br from-[#0d3b24] via-[#1b5e3a] to-[#0f4a2a] px-10 py-16 lg:py-0 flex flex-col justify-between">
        {/* 배경 패턴 */}
        <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%), radial-gradient(circle at 50% 50%, rgba(60,179,113,0.18) 0, transparent 55%)",
          }}
        />
        <div
          className="absolute inset-0 pointer-events-none"
          style={{
            backgroundImage:
              "linear-gradient(rgba(255,255,255,0.04) 1px, transparent 0), linear-gradient(90deg, rgba(255,255,255,0.04) 1px, transparent 0)",
            backgroundSize: "48px 48px",
          }}
        />
        {/* 반짝이 파티클 */}
        <div className="absolute inset-0 pointer-events-none">
          <div className="absolute top-[12%] left-[18%] w-1 h-1 rounded-full bg-emerald-200/80 animate-pulse" />
          <div className="absolute top-[25%] right-[22%] w-2 h-2 rounded-full bg-emerald-300/60 animate-pulse" style={{ animationDelay: "1s" }} />
          <div className="absolute bottom-[28%] left-[35%] w-1.5 h-1.5 rounded-full bg-emerald-200/70 animate-pulse" style={{ animationDelay: "2s" }} />
          <div className="absolute top-[60%] right-[15%] w-1 h-1 rounded-full bg-emerald-100/80 animate-pulse" style={{ animationDelay: "0.5s" }} />
        </div>

        <div className="relative z-10">
          <div className="flex items-center gap-3">
            <img src="/momo-icon.svg" alt="MOMO" className="w-11 h-11" />
            <span className="text-white/95 text-sm font-semibold tracking-widest">
              MOMO DISTRIBUTION
            </span>
          </div>
        </div>

        <div className="relative z-10 flex-1 flex flex-col justify-center py-12 lg:py-0">
          <img src="/momo-logo.svg" alt="MOMO" className="w-[280px] lg:w-[360px] mb-6 drop-shadow-[0_8px_24px_rgba(0,0,0,0.35)]" />
          <h2 className="text-white text-3xl lg:text-4xl font-bold mb-3 tracking-tight">
            모모유통 <span className="text-emerald-200">유통관리 ERP</span>
          </h2>
          <p className="text-emerald-100/80 text-base lg:text-lg leading-relaxed max-w-lg">
            발주 · 입고 · 명세서 · 정산까지 —<br />
            유통 업무의 모든 흐름을 한 곳에서.
          </p>
        </div>

        <div className="relative z-10 text-emerald-100/70 text-[12px] space-y-1.5">
          <div className="flex items-center gap-2">
            <MapPin size={13} className="shrink-0" />
            <span><span className="text-emerald-200 font-semibold mr-2">본사</span>경기도 의왕시 벌모루길 46 B동</span>
          </div>
          <div className="flex items-center gap-2">
            <MapPin size={13} className="shrink-0" />
            <span><span className="text-emerald-200 font-semibold mr-2">지사</span>경기도 김포시 고촌읍 김포대로 451번길 210</span>
          </div>
          <div className="flex items-center gap-4 pt-1 text-emerald-100/60">
            <span className="flex items-center gap-1.5"><Phone size={12} />010-6624-5315</span>
            <span className="flex items-center gap-1.5"><Mail size={12} />momo8443@daum.net</span>
          </div>
        </div>
      </div>

      {/* 우측: 로그인 폼 */}
      <div className="lg:flex-1 flex items-center justify-center px-6 py-16 lg:py-0 bg-slate-50">
        <div className="w-full max-w-md">
          <div className="mb-10">
            <div className="inline-flex items-center gap-2 text-emerald-700 text-xs font-bold tracking-widest mb-3">
              <span className="w-6 h-[2px] bg-emerald-600" />
              WELCOME BACK
            </div>
            <h1 className="text-3xl font-bold text-slate-900 mb-2">로그인</h1>
            <p className="text-slate-500 text-sm">
              계정 정보를 입력하고 유통관리 ERP에 접속하세요.
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label className="block text-[12px] font-semibold text-slate-600 mb-2 tracking-wide">
                아이디
              </label>
              <div className="relative group">
                <User
                  size={16}
                  className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-emerald-600 transition-colors"
                />
                <input
                  type="text"
                  value={userId}
                  onChange={(e) => setUserId(e.target.value)}
                  placeholder="아이디를 입력하세요"
                  autoFocus
                  autoComplete="username"
                  className="w-full h-12 pl-11 pr-4 rounded-xl border border-slate-200 bg-white text-sm text-slate-900 placeholder-slate-400 shadow-sm focus:outline-none focus:border-emerald-500 focus:ring-4 focus:ring-emerald-500/10 transition"
                />
              </div>
            </div>

            <div>
              <label className="block text-[12px] font-semibold text-slate-600 mb-2 tracking-wide">
                비밀번호
              </label>
              <div className="relative group">
                <Lock
                  size={16}
                  className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-emerald-600 transition-colors"
                />
                <input
                  type={showPw ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="비밀번호를 입력하세요"
                  autoComplete="current-password"
                  className="w-full h-12 pl-11 pr-12 rounded-xl border border-slate-200 bg-white text-sm text-slate-900 placeholder-slate-400 shadow-sm focus:outline-none focus:border-emerald-500 focus:ring-4 focus:ring-emerald-500/10 transition"
                />
                <button
                  type="button"
                  onClick={() => setShowPw((v) => !v)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 p-1.5 text-slate-400 hover:text-slate-700 transition-colors"
                  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.5 cursor-pointer select-none">
                <input
                  type="checkbox"
                  checked={remember}
                  onChange={(e) => setRemember(e.target.checked)}
                  className="w-5 h-5 accent-emerald-600 cursor-pointer"
                />
                <span className="text-sm text-slate-700 font-semibold">로그인 계속 유지</span>
                <span className="text-xs text-slate-400 ml-auto">한 번 로그인 후 계속 자동 로그인</span>
              </label>
              <label className="flex items-center gap-2.5 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-5 h-5 accent-emerald-600 cursor-pointer"
                />
                <span className="text-sm text-slate-700 font-semibold">아이디/비밀번호 저장</span>
                <span className="text-xs text-slate-400 ml-auto">이 기기에 저장 (공용 PC 비추천)</span>
              </label>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="group relative 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-lg shadow-emerald-600/25 hover:shadow-emerald-600/40 hover:-translate-y-0.5 active:translate-y-0 transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:translate-y-0 flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <span className="w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin" />
                  로그인 중...
                </>
              ) : (
                <>
                  로그인
                  <ArrowRight size={16} className="group-hover:translate-x-0.5 transition-transform" />
                </>
              )}
            </button>
          </form>

          <div className="mt-8 text-center">
            <p className="text-sm text-slate-500">
              아직 계정이 없으신가요?{" "}
              <Link href="/signup" className="text-emerald-700 font-semibold hover:underline">
                회원가입
              </Link>
            </p>
          </div>

          <div className="mt-12 pt-6 border-t border-slate-200 text-center">
            <p className="text-[11px] text-slate-400 tracking-wide">
              &copy; 2026 MOMO DISTRIBUTION. All rights reserved.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
