"use client";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { X, Eye, EyeOff } from "lucide-react";
import { AVATARS } from "@/lib/avatars";
import { setCachedProfile } from "@/lib/userId";
import type { UserProfile } from "@/types";
import Modal from "@/components/Modal";
import Button from "@/components/Button";
import Input from "@/components/Input";

type Tab = "login" | "register";

interface AuthModalProps {
  open: boolean;
  onClose: () => void;
  onAuth: (profile: UserProfile) => void;
  defaultTab?: Tab;
}

export default function AuthModal({ open, onClose, onAuth, defaultTab = "login" }: AuthModalProps) {
  const [tab, setTab] = useState<Tab>(defaultTab);
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [avatar, setAvatar] = useState<string>(AVATARS[0].emoji);
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const resetForm = () => {
    setUsername("");
    setPassword("");
    setConfirmPassword("");
    setAvatar(AVATARS[0].emoji);
    setShowPassword(false);
    setError("");
    setLoading(false);
  };

  useEffect(() => {
    if (open) {
      setTab(defaultTab);
      resetForm();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  const switchTab = (t: Tab) => {
    setTab(t);
    resetForm();
  };

  const handleSubmit = async () => {
    const trimmedUsername = username.trim();
    if (!trimmedUsername) {
      setError("请输入用户名");
      return;
    }

    if (!password) {
      setError("请输入密码");
      return;
    }

    if (tab === "register") {
      if (trimmedUsername.length < 2 || trimmedUsername.length > 16) {
        setError("用户名需要 2-16 个字符");
        return;
      }
      if (password.length < 6) {
        setError("密码至少 6 个字符");
        return;
      }
      if (password !== confirmPassword) {
        setError("两次密码不一致");
        return;
      }
    }

    setLoading(true);
    setError("");

    try {
      const endpoint = tab === "login" ? "/api/auth/login" : "/api/auth/register";
      const payload =
        tab === "login"
          ? { username: trimmedUsername, password }
          : { username: trimmedUsername, password, avatar };

      const res = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error ?? "操作失败");
        return;
      }

      const profile: UserProfile = {
        id: data.id,
        username: data.username,
        avatar: data.avatar,
      };

      localStorage.setItem("nowhatever_user_id", profile.id);
      setCachedProfile(profile);
      onAuth(profile);
      onClose();
      resetForm();
    } catch {
      setError("网络错误，请重试");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose}>
      <div className="mb-4 flex items-center justify-between">
        <span className="text-lg font-bold text-heading">欢迎</span>
        <button
          onClick={onClose}
          className="flex h-8 w-8 items-center justify-center rounded-full bg-elevated text-muted transition-colors active:bg-subtle"
        >
          <X size={16} />
        </button>
      </div>

      <div className="flex gap-1 rounded-xl bg-elevated p-1">
        {(["login", "register"] as const).map((t) => (
          <button
            key={t}
            onClick={() => switchTab(t)}
            className={`relative flex-1 rounded-lg py-2 text-sm font-semibold transition-colors ${
              tab === t ? "text-heading" : "text-muted"
            }`}
          >
            {tab === t && (
              <motion.div
                layoutId="auth-tab"
                className="absolute inset-0 rounded-lg bg-subtle shadow-sm"
                transition={{ type: "spring", stiffness: 400, damping: 30 }}
              />
            )}
            <span className="relative z-10">
              {t === "login" ? "登录" : "注册"}
            </span>
          </button>
        ))}
      </div>

      <div className="mt-5">
        <p className="text-xs font-medium text-muted">用户名</p>
        <Input
          type="text"
          value={username}
          onChange={(e) => {
            setUsername(e.target.value.slice(0, 16));
            setError("");
          }}
          placeholder={tab === "register" ? "2-16 个字符" : "请输入用户名"}
          maxLength={16}
          size="xl"
          className="mt-2"
        />
      </div>

      <div className="mt-4">
        <p className="text-xs font-medium text-muted">密码</p>
        <div className="relative mt-2">
          <Input
            type={showPassword ? "text" : "password"}
            value={password}
            onChange={(e) => {
              setPassword(e.target.value);
              setError("");
            }}
            placeholder={tab === "register" ? "至少 6 个字符" : "请输入密码"}
            size="xl"
            className="pr-10"
          />
          <button
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            aria-label={showPassword ? "隐藏密码" : "显示密码"}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-muted transition-colors active:text-secondary"
          >
            {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
          </button>
        </div>
      </div>

      {tab === "register" && (
        <div className="mt-4">
          <p className="text-xs font-medium text-muted">确认密码</p>
          <Input
            type={showPassword ? "text" : "password"}
            value={confirmPassword}
            onChange={(e) => {
              setConfirmPassword(e.target.value);
              setError("");
            }}
            placeholder="再次输入密码"
            size="xl"
            className="mt-2"
          />
        </div>
      )}

      {tab === "register" && (
        <div className="mt-4">
          <p className="text-xs font-medium text-muted">
            选择头像
            <span className="ml-1 text-dim">（可选）</span>
          </p>
          <div className="mt-2 grid grid-cols-6 gap-2">
            {AVATARS.map((a) => (
              <button
                key={a.emoji}
                onClick={() => setAvatar(a.emoji)}
                className={`flex h-11 w-11 items-center justify-center rounded-xl text-xl transition-all ${
                  avatar === a.emoji
                    ? `${a.bg} scale-110 ring-2 ring-accent ring-offset-1 ring-offset-surface`
                    : "bg-elevated hover:bg-subtle"
                }`}
              >
                {a.emoji}
              </button>
            ))}
          </div>
        </div>
      )}

      {error && (
        <motion.p
          className="mt-3 text-center text-xs font-medium text-rose-400"
          initial={{ opacity: 0, y: -4 }}
          animate={{ opacity: 1, y: 0 }}
        >
          {error}
        </motion.p>
      )}

      <Button
        onClick={handleSubmit}
        size="lg"
        fullWidth
        loading={loading}
        loadingText={tab === "login" ? "登录中..." : "注册中..."}
        className="mt-5"
      >
        {tab === "login" ? "登录" : "注册"}
      </Button>
    </Modal>
  );
}
