/**
 * 로그인 모달 — AppPopup(tam-) 스타일
 */
import React, { useEffect, useState } from 'react';
import { loginUser, type LoginResponse } from '../utils/backendApi';
import AppPopup from './AppPopup';

const DEFAULT_USERNAME = 'admin';
const DEFAULT_PASSWORD = 'admin';

interface Props {
  open: boolean;
  onClose: () => void;
  onSuccess: (session: LoginResponse) => void;
}

const LoginModal: React.FC<Props> = ({ open, onClose, onSuccess }) => {
  const [username, setUsername] = useState(DEFAULT_USERNAME);
  const [password, setPassword] = useState(DEFAULT_PASSWORD);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!open) return;
    setUsername(DEFAULT_USERNAME);
    setPassword(DEFAULT_PASSWORD);
    setError(null);
    setLoading(false);
  }, [open]);

  if (!open) return null;

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await loginUser(username.trim(), password);
      if (!res) {
        setError('로그인에 실패했습니다. 아이디와 비밀번호를 확인하세요.');
        return;
      }
      onSuccess(res);
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : '로그인에 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <AppPopup
      onClose={onClose}
      title="LOGIN"
      titleKo="로그인"
      badge="AUTH"
      width={380}
      backdrop
      shellClassName="login-modal"
      bodyClassName="app-popup-body login-modal-body"
    >
      <p className="login-modal-hint app-popup-disclaimer" style={{ textAlign: 'left', marginBottom: 8 }}>
        로그인 시 동일 계정의 설정이 모든 기기에서 공유됩니다. 로그인하지 않으면 이 브라우저(기기)별로 설정이 저장됩니다.
      </p>
      <form className="login-modal-form" onSubmit={submit}>
        <label className="login-modal-field app-popup-field-row">
          <span className="app-popup-field-label">아이디</span>
          <input
            className="app-popup-input"
            type="text"
            autoComplete="username"
            value={username}
            onChange={e => setUsername(e.target.value)}
            disabled={loading}
          />
        </label>
        <label className="login-modal-field app-popup-field-row" style={{ marginTop: 8 }}>
          <span className="app-popup-field-label">비밀번호</span>
          <input
            className="app-popup-input login-modal-field--visible"
            type="text"
            autoComplete="off"
            value={password}
            onChange={e => setPassword(e.target.value)}
            disabled={loading}
          />
        </label>
        {error && <p className="login-modal-error">{error}</p>}
        <div className="login-modal-actions" style={{ marginTop: 12, display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button type="button" className="app-popup-btn" onClick={onClose} disabled={loading}>
            취소
          </button>
          <button type="submit" className="app-popup-btn app-popup-btn--primary" style={{ width: 'auto', padding: '8px 20px' }} disabled={loading}>
            {loading ? '로그인 중…' : '로그인'}
          </button>
        </div>
      </form>
    </AppPopup>
  );
};

export default LoginModal;
