'use client';

// Login / Register modal — opens when user clicks the login button or
// when persistence hook reports login required.

import { useEffect, useState } from 'react';
import { useAuth } from '@/store/auth';

interface AuthModalProps {
  open: boolean;
  onClose: () => void;
}

type Mode = 'login' | 'register';

export function AuthModal({ open, onClose }: AuthModalProps) {
  const login = useAuth((s) => s.login);
  const register = useAuth((s) => s.register);
  const loading = useAuth((s) => s.loading);
  const error = useAuth((s) => s.error);
  const setError = useAuth((s) => s.setError);
  const [mode, setMode] = useState<Mode>('login');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [localError, setLocalError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) {
      // Reset on close
      setUsername('');
      setPassword('');
      setConfirm('');
      setLocalError(null);
      setError(null);
    }
  }, [open, setError]);

  if (!open) return null;

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLocalError(null);
    if (username.length < 3 || username.length > 32) {
      setLocalError('ชื่อผู้ใช้ต้อง 3-32 ตัวอักษร');
      return;
    }
    if (!/^[a-zA-Z0-9_]+$/.test(username)) {
      setLocalError('ใช้ได้เฉพาะ a-z, A-Z, 0-9, _');
      return;
    }
    if (password.length < 6) {
      setLocalError('รหัสผ่านต้องมากกว่า 6 ตัวอักษร');
      return;
    }
    if (mode === 'register' && password !== confirm) {
      setLocalError('รหัสผ่านยืนยันไม่ตรงกัน');
      return;
    }
    const ok =
      mode === 'login'
        ? await login(username, password)
        : await register(username, password);
    if (ok) onClose();
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-md animate-fade-in"
      onClick={onClose}
    >
      <div
        className="relative w-[440px] max-w-[92vw] rounded-2xl bg-[#181a20] border border-white/10 shadow-2xl animate-slide-up"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-6 pt-6 pb-4 border-b border-white/5">
          <div className="flex items-center gap-3 mb-1">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-cyan-400 flex items-center justify-center shadow-glow-blue">
              <svg
                viewBox="0 0 24 24"
                className="w-5 h-5 text-white"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="M12 2L3 7v10l9 5 9-5V7l-9-5z" />
                <path d="M3 7l9 5 9-5M12 12v10" />
              </svg>
            </div>
            <div>
              <h2 className="text-lg font-semibold text-white">
                {mode === 'login' ? 'เข้าสู่ระบบ' : 'สมัครสมาชิก'}
              </h2>
              <p className="text-xs text-slate-400 mt-0.5">
                {mode === 'login'
                  ? 'เข้าสู่ระบบเพื่อเก็บโปรเจกต์บนคลาวด์'
                  : 'สมัครฟรี · ไม่มีค่าใช้จ่าย · เก็บไฟล์ได้ไม่จำกัด'}
              </p>
            </div>
          </div>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="px-6 py-5 space-y-4">
          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1.5">
              ชื่อผู้ใช้
            </label>
            <input
              type="text"
              autoComplete="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="username"
              className="w-full px-3 py-2.5 rounded-lg bg-white/[0.03] border border-white/10 text-white placeholder:text-slate-500 focus:outline-none focus:border-blue-500 focus:bg-white/[0.06] transition-all"
            />
            <p className="text-[10px] text-slate-500 mt-1">
              3-32 ตัว · ใช้ได้เฉพาะ a-z, A-Z, 0-9, _
            </p>
          </div>

          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1.5">
              รหัสผ่าน
            </label>
            <input
              type="password"
              autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              className="w-full px-3 py-2.5 rounded-lg bg-white/[0.03] border border-white/10 text-white placeholder:text-slate-500 focus:outline-none focus:border-blue-500 focus:bg-white/[0.06] transition-all"
            />
            <p className="text-[10px] text-slate-500 mt-1">อย่างน้อย 6 ตัวอักษร</p>
          </div>

          {mode === 'register' && (
            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1.5">
                ยืนยันรหัสผ่าน
              </label>
              <input
                type="password"
                autoComplete="new-password"
                value={confirm}
                onChange={(e) => setConfirm(e.target.value)}
                placeholder="••••••••"
                className="w-full px-3 py-2.5 rounded-lg bg-white/[0.03] border border-white/10 text-white placeholder:text-slate-500 focus:outline-none focus:border-blue-500 focus:bg-white/[0.06] transition-all"
              />
            </div>
          )}

          {(localError || error) && (
            <div className="rounded-lg bg-red-500/10 border border-red-500/30 px-3 py-2 text-xs text-red-300">
              {localError || error}
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            className="w-full py-2.5 rounded-lg bg-gradient-to-r from-blue-500 to-cyan-400 text-white font-medium shadow-glow-blue hover:shadow-glow-blue/80 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading
              ? 'กำลังดำเนินการ...'
              : mode === 'login'
                ? 'เข้าสู่ระบบ'
                : 'สมัครสมาชิก'}
          </button>
        </form>

        {/* Footer */}
        <div className="px-6 py-4 border-t border-white/5 flex items-center justify-between">
          <button
            type="button"
            onClick={() => setMode(mode === 'login' ? 'register' : 'login')}
            className="text-xs text-blue-400 hover:text-blue-300 transition-colors"
          >
            {mode === 'login' ? '→ สมัครสมาชิกใหม่' : '→ ฉันมีบัญชีอยู่แล้ว'}
          </button>
          <button
            type="button"
            onClick={onClose}
            className="text-xs text-slate-500 hover:text-slate-300 transition-colors"
          >
            ปิด
          </button>
        </div>

        {/* Close X */}
        <button
          type="button"
          onClick={onClose}
          className="absolute top-4 right-4 w-7 h-7 rounded-md flex items-center justify-center text-slate-500 hover:text-white hover:bg-white/10 transition-colors"
        >
          ✕
        </button>
      </div>
    </div>
  );
}
