"use client";

import { useState } from "react";
import Link from "next/link";
import { AUTH_ROUTES } from "@/features/auth/constants";
import {
  login,
  signInWithGoogle,
  signInWithKakao,
} from "@/features/auth/actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Separator } from "@/components/ui/separator";
import { InlineSpinner } from "@/components/ui/loading-spinner";

/**
 * [로그인 폼 클라이언트 컴포넌트]
 *
 * 이메일 기억하기 기능을 제공하는 로그인 폼입니다.
 * - localStorage를 사용하여 이메일 저장/불러오기
 * - 체크박스 선택 시 이메일 자동 저장
 * - 서버 액션(login)과 연동
 * - 하이드레이션 이슈 해결을 위해 useEffect 사용
 */
export default function LoginForm() {
  // ========== 상태 관리 ==========
  const [email, setEmail] = useState(() => {
    if (typeof window === "undefined") return "";
    return localStorage.getItem("auto-trade-saved-email") || "";
  });
  const [rememberMe, setRememberMe] = useState(() => {
    if (typeof window === "undefined") return false;
    return !!localStorage.getItem("auto-trade-saved-email");
  });
  const [isLoading, setIsLoading] = useState(false);

  // ========== 폼 제출 핸들러 ==========
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);

    const formData = new FormData(e.currentTarget);

    // localStorage 처리 (동기)
    if (rememberMe) {
      localStorage.setItem("auto-trade-saved-email", email);
    } else {
      localStorage.removeItem("auto-trade-saved-email");
    }

    // 서버 액션 호출 (리다이렉트 발생)
    try {
      await login(formData);
    } catch (error) {
      console.error("Login error:", error);
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* ========== 로그인 폼 ========== */}
      <form className="space-y-5" onSubmit={handleSubmit}>
        {/* ========== 이메일 입력 필드 ========== */}
        <div className="space-y-2">
          <Label htmlFor="email" className="text-sm font-medium">
            이메일
          </Label>
          <Input
            id="email"
            name="email"
            type="email"
            placeholder="your@email.com"
            autoComplete="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="h-11 transition-all duration-200 focus-visible:ring-brand-500"
          />
        </div>

        {/* ========== 비밀번호 입력 필드 ========== */}
        <div className="space-y-2">
          <Label htmlFor="password" className="text-sm font-medium">
            비밀번호
          </Label>
          <Input
            id="password"
            name="password"
            type="password"
            placeholder="••••••••"
            autoComplete="current-password"
            required
            minLength={8}
            pattern="^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,}$"
            title="비밀번호는 최소 8자 이상, 대문자, 소문자, 숫자, 특수문자를 각각 1개 이상 포함해야 합니다."
            className="h-11 transition-all duration-200 focus-visible:ring-brand-500"
          />
        </div>

        {/* ========== 이메일 기억하기 & 비밀번호 찾기 ========== */}
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <Checkbox
              id="remember"
              checked={rememberMe}
              onCheckedChange={(checked) => setRememberMe(checked === true)}
            />
            <Label
              htmlFor="remember"
              className="cursor-pointer text-sm font-normal leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
            >
              이메일 기억하기
            </Label>
          </div>
          <Link
            href={AUTH_ROUTES.FORGOT_PASSWORD}
            className="text-sm font-medium text-brand-600 transition-colors hover:text-brand-700 dark:text-brand-400 dark:hover:text-brand-300"
          >
            비밀번호 찾기
          </Link>
        </div>

        {/* ========== 로그인 버튼 ========== */}
        <Button
          type="submit"
          disabled={isLoading}
          className="h-11 w-full bg-linear-to-r from-brand-500 to-brand-700 font-semibold text-white shadow-lg shadow-brand-500/20 transition-all duration-200 hover:from-brand-600 hover:to-brand-800 hover:shadow-xl hover:shadow-brand-500/25"
          size="lg"
        >
          {isLoading ? (
            <span className="flex items-center gap-2">
              <InlineSpinner />
              로그인 중...
            </span>
          ) : (
            "로그인"
          )}
        </Button>

        {/* ========== 회원가입 링크 ========== */}
        <p className="text-center text-sm text-muted-foreground">
          계정이 없으신가요?{" "}
          <Link
            href={AUTH_ROUTES.SIGNUP}
            className="font-semibold text-brand-600 transition-colors hover:text-brand-700 dark:text-brand-400 dark:hover:text-brand-300"
          >
            회원가입 하기
          </Link>
        </p>
      </form>

      {/* ========== 소셜 로그인 구분선 ========== */}
      <div className="relative">
        <Separator className="my-6" />
        <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-white px-3 text-xs font-medium text-muted-foreground dark:bg-brand-950">
          또는 소셜 로그인
        </span>
      </div>

      {/* ========== 소셜 로그인 버튼들 ========== */}
      <div className="grid grid-cols-2 gap-3">
        {/* ========== Google 로그인 버튼 ========== */}
        <form action={signInWithGoogle}>
          <Button
            type="submit"
            variant="outline"
            className="h-11 w-full border-brand-200/50 bg-white shadow-sm transition-all duration-200 hover:bg-brand-50 hover:shadow-md dark:border-brand-800/50 dark:bg-brand-950/50 dark:hover:bg-brand-900/50"
          >
            <svg className="mr-2 h-5 w-5" viewBox="0 0 24 24">
              <path
                fill="currentColor"
                d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
              />
              <path
                fill="currentColor"
                d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
              />
              <path
                fill="currentColor"
                d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
              />
              <path
                fill="currentColor"
                d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
              />
            </svg>
            Google
          </Button>
        </form>

        {/* ========== Kakao 로그인 버튼 ========== */}
        <form action={signInWithKakao}>
          <Button
            type="submit"
            variant="outline"
            className="h-11 w-full border-none bg-[#FEE500] font-semibold text-[#3C1E1E] shadow-sm transition-all duration-200 hover:bg-[#FDD835] hover:shadow-md"
          >
            <svg
              className="mr-2 h-5 w-5"
              viewBox="0 0 24 24"
              fill="currentColor"
            >
              <path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9-4.03-9-9-9zm-1.5 14.5h-3v-9h3v9zm3 0h-3v-5h3v5zm0-6h-3v-3h3v3z" />
            </svg>
            Kakao
          </Button>
        </form>
      </div>
    </div>
  );
}
