import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import './Common.css';
import './MemberAuth.css';

const API = '/api/members';

export default function MemberLogin() {
  const navigate = useNavigate();
  const [tab,    setTab]    = useState('login');  // login | register
  const [form,   setForm]   = useState({ name:'', email:'', password:'', phone:'', company:'' });
  const [error,  setError]  = useState('');
  const [loading,setLoading] = useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleLogin = async e => {
    e.preventDefault(); setError(''); setLoading(true);
    try {
      const res = await fetch(`${API}/login`, {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ email: form.email, password: form.password }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.message || '로그인 실패'); return; }
      localStorage.setItem('member_token', data.token);
      localStorage.setItem('member_user',  JSON.stringify(data));
      navigate('/');
    } catch { setError('서버 연결 오류'); }
    finally { setLoading(false); }
  };

  const handleRegister = async e => {
    e.preventDefault(); setError(''); setLoading(true);
    if (form.password.length < 8) { setError('비밀번호는 8자 이상이어야 합니다.'); setLoading(false); return; }
    try {
      const res = await fetch(`${API}/register`, {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.message || '가입 실패'); return; }
      localStorage.setItem('member_token', data.token);
      localStorage.setItem('member_user',  JSON.stringify(data));
      navigate('/');
    } catch { setError('서버 연결 오류'); }
    finally { setLoading(false); }
  };

  // SNS 로그인 핸들러 (SDK 연동 후 콜백)
  const handleSnsLogin = async (provider, profile) => {
    setError(''); setLoading(true);
    try {
      const res = await fetch(`${API}/social-login`, {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ provider, email: profile.email, name: profile.name, id: profile.id }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.message || 'SNS 로그인 실패'); return; }
      localStorage.setItem('member_token', data.token);
      localStorage.setItem('member_user',  JSON.stringify(data));
      navigate('/');
    } catch { setError('SNS 로그인 오류'); }
    finally { setLoading(false); }
  };

  // 카카오 로그인 (kakao SDK 필요: https://developers.kakao.com)
  const loginKakao = () => {
    if (!window.Kakao?.Auth) { alert('카카오 SDK를 불러오는 중입니다. 잠시 후 시도해 주세요.'); return; }
    window.Kakao.Auth.login({
      success: authObj => {
        window.Kakao.API.request({
          url: '/v2/user/me',
          success: res => {
            const profile = {
              id:    String(res.id),
              name:  res.kakao_account?.profile?.nickname || '카카오회원',
              email: res.kakao_account?.email || `kakao_${res.id}@kakao.user`,
            };
            handleSnsLogin('kakao', profile);
          },
        });
      },
      fail: () => setError('카카오 로그인에 실패했습니다.'),
    });
  };

  // 네이버 로그인 (naver SDK 필요: https://developers.naver.com)
  const loginNaver = () => {
    const naverLogin = window.naver_id_login;
    if (!naverLogin) { alert('네이버 SDK를 불러오는 중입니다.'); return; }
    naverLogin.getLoginStatus(status => {
      if (status) {
        const profile = {
          id:    naverLogin.getProfileData('id'),
          name:  naverLogin.getProfileData('name'),
          email: naverLogin.getProfileData('email'),
        };
        handleSnsLogin('naver', profile);
      } else {
        naverLogin.authorize();
      }
    });
  };

  // 구글 로그인 (Google Identity Services 필요)
  const loginGoogle = () => {
    if (!window.google?.accounts) { alert('구글 SDK를 불러오는 중입니다.'); return; }
    window.google.accounts.id.prompt(notification => {
      if (notification.isNotDisplayed()) setError('구글 로그인 팝업이 차단됐습니다.');
    });
  };

  return (
    <main className="auth-page">
      <div className="auth-box">
        {/* 로고 */}
        <Link to="/" className="auth-logo">
          <img src="/logo.png" alt="지오정보기술" height="24"
               onError={e => { e.target.style.display='none'; }} />
        </Link>

        {/* 탭 */}
        <div className="auth-tabs">
          <button className={`auth-tab ${tab==='login' ? 'active' : ''}`} onClick={() => { setTab('login'); setError(''); }}>
            로그인
          </button>
          <button className={`auth-tab ${tab==='register' ? 'active' : ''}`} onClick={() => { setTab('register'); setError(''); }}>
            회원가입
          </button>
        </div>

        {error && <div className="auth-error">{error}</div>}

        {/* ── 로그인 폼 ── */}
        {tab === 'login' && (
          <form onSubmit={handleLogin} className="auth-form">
            <div className="form-group">
              <label>이메일</label>
              <input type="email" value={form.email} onChange={e => set('email', e.target.value)}
                     placeholder="이메일 주소" required />
            </div>
            <div className="form-group">
              <label>비밀번호</label>
              <input type="password" value={form.password} onChange={e => set('password', e.target.value)}
                     placeholder="비밀번호" required />
            </div>
            <button type="submit" className="btn btn-primary btn-full" disabled={loading}>
              {loading ? '로그인 중...' : '로그인'}
            </button>

            {/* SNS 로그인 */}
            <div className="sns-divider"><span>또는 SNS 로그인</span></div>
            <div className="sns-buttons">
              <button type="button" className="sns-btn sns-kakao" onClick={loginKakao}>
                <span className="sns-icon" style={{background:'#FAE100',borderRadius:'50%',width:20,height:20,display:'inline-flex',alignItems:'center',justifyContent:'center'}}><svg width="12" height="12" viewBox="0 0 24 24" fill="#3C1E1E"><path d="M12 4C7 4 3 7.1 3 11c0 2.5 1.5 4.7 3.8 6l-.8 3 3.4-2.2c.8.2 1.7.2 2.6.2 5 0 9-3.1 9-7S17 4 12 4z"/></svg></span> 카카오로 로그인
              </button>
              <button type="button" className="sns-btn sns-naver" onClick={loginNaver}>
                <span className="sns-icon">N</span> 네이버로 로그인
              </button>
              <button type="button" className="sns-btn sns-google" onClick={loginGoogle}>
                <span className="sns-icon">G</span> 구글로 로그인
              </button>
            </div>

            <p className="auth-switch">
              계정이 없으신가요?{' '}
              <button type="button" className="link-btn" onClick={() => setTab('register')}>
                회원가입
              </button>
            </p>
          </form>
        )}

        {/* ── 회원가입 폼 ── */}
        {tab === 'register' && (
          <form onSubmit={handleRegister} className="auth-form">
            <div className="form-group">
              <label>이름 <span className="required">*</span></label>
              <input type="text" value={form.name} onChange={e => set('name', e.target.value)}
                     placeholder="실명을 입력해 주세요" required />
            </div>
            <div className="form-group">
              <label>이메일 <span className="required">*</span></label>
              <input type="email" value={form.email} onChange={e => set('email', e.target.value)}
                     placeholder="이메일 주소" required />
            </div>
            <div className="form-group">
              <label>비밀번호 <span className="required">*</span></label>
              <input type="password" value={form.password} onChange={e => set('password', e.target.value)}
                     placeholder="8자 이상" required minLength={8} />
            </div>
            <div className="form-group">
              <label>연락처</label>
              <input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)}
                     placeholder="010-0000-0000" />
            </div>
            <div className="form-group">
              <label>소속 기관/회사</label>
              <input type="text" value={form.company} onChange={e => set('company', e.target.value)}
                     placeholder="소속 기관이나 회사명 (선택)" />
            </div>

            <button type="submit" className="btn btn-primary btn-full" disabled={loading}>
              {loading ? '가입 중...' : '회원가입'}
            </button>

            {/* SNS 회원가입 */}
            <div className="sns-divider"><span>또는 SNS로 간편 가입</span></div>
            <div className="sns-buttons">
              <button type="button" className="sns-btn sns-kakao" onClick={loginKakao}>
                <span className="sns-icon" style={{background:'#FAE100',borderRadius:'50%',width:20,height:20,display:'inline-flex',alignItems:'center',justifyContent:'center'}}><svg width="12" height="12" viewBox="0 0 24 24" fill="#3C1E1E"><path d="M12 4C7 4 3 7.1 3 11c0 2.5 1.5 4.7 3.8 6l-.8 3 3.4-2.2c.8.2 1.7.2 2.6.2 5 0 9-3.1 9-7S17 4 12 4z"/></svg></span> 카카오로 시작
              </button>
              <button type="button" className="sns-btn sns-naver" onClick={loginNaver}>
                <span className="sns-icon">N</span> 네이버로 시작
              </button>
              <button type="button" className="sns-btn sns-google" onClick={loginGoogle}>
                <span className="sns-icon">G</span> 구글로 시작
              </button>
            </div>

            <p className="auth-switch">
              이미 계정이 있으신가요?{' '}
              <button type="button" className="link-btn" onClick={() => setTab('login')}>
                로그인
              </button>
            </p>
          </form>
        )}

        <p className="auth-terms">
          회원가입 시 <Link to="/terms">이용약관</Link> 및{' '}
          <Link to="/privacy">개인정보처리방침</Link>에 동의하는 것으로 간주됩니다.
        </p>
      </div>
    </main>
  );
}
