import { useState } from 'react';
import { useNavigate } from 'react-router-dom';

const token = () => localStorage.getItem('admin_token');

export default function AdminSettings() {
  const navigate = useNavigate();
  const user = JSON.parse(localStorage.getItem('admin_user') || '{}');
  const [form, setForm] = useState({ currentPassword: '', newPassword: '', confirmPassword: '' });
  const [msg, setMsg] = useState(null);
  const [saving, setSaving] = useState(false);

  const handleChange = async () => {
    if (form.newPassword !== form.confirmPassword) {
      setMsg({ text: '새 비밀번호가 일치하지 않습니다.', type: 'error' }); return;
    }
    if (form.newPassword.length < 8) {
      setMsg({ text: '비밀번호는 8자 이상이어야 합니다.', type: 'error' }); return;
    }
    setSaving(true);
    const res = await fetch('/api/admin/password', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token()}` },
      body: JSON.stringify({ currentPassword: form.currentPassword, newPassword: form.newPassword }),
    });
    const data = await res.json();
    setSaving(false);
    if (res.ok) {
      setMsg({ text: '비밀번호가 변경되었습니다. 다시 로그인해주세요.', type: 'success' });
      setForm({ currentPassword: '', newPassword: '', confirmPassword: '' });
      setTimeout(() => {
        localStorage.removeItem('admin_token');
        navigate('/admin/login');
      }, 2000);
    } else {
      setMsg({ text: data.message || '변경 실패', type: 'error' });
    }
  };

  return (
    <div style={{ maxWidth: 520 }}>
      {/* 계정 정보 */}
      <div className="admin-card" style={{ marginBottom: 20 }}>
        <div className="admin-card-header"><h3>👤 계정 정보</h3></div>
        <div style={{ display: 'grid', gap: 12 }}>
          {[['아이디', user.username], ['표시 이름', user.displayName || '-']].map(([l, v]) => (
            <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ fontSize: 12, fontWeight: 600, color: '#64748b', width: 80 }}>{l}</span>
              <span style={{ fontSize: 14 }}>{v}</span>
            </div>
          ))}
        </div>
      </div>

      {/* 비밀번호 변경 */}
      <div className="admin-card">
        <div className="admin-card-header"><h3>🔒 비밀번호 변경</h3></div>
        {msg && (
          <div style={{
            padding: '10px 14px', borderRadius: 7, marginBottom: 16, fontSize: 13,
            background: msg.type === 'error' ? '#fff1f2' : '#f0fdf4',
            color: msg.type === 'error' ? '#dc2626' : '#16a34a',
            border: `1px solid ${msg.type === 'error' ? '#fecaca' : '#bbf7d0'}`,
          }}>
            {msg.text}
          </div>
        )}
        <div className="form-group">
          <label>현재 비밀번호</label>
          <input type="password" className="form-control" value={form.currentPassword}
            onChange={e => setForm(p => ({ ...p, currentPassword: e.target.value }))} />
        </div>
        <div className="form-group">
          <label>새 비밀번호</label>
          <input type="password" className="form-control" value={form.newPassword}
            placeholder="8자 이상"
            onChange={e => setForm(p => ({ ...p, newPassword: e.target.value }))} />
        </div>
        <div className="form-group">
          <label>새 비밀번호 확인</label>
          <input type="password" className="form-control" value={form.confirmPassword}
            onChange={e => setForm(p => ({ ...p, confirmPassword: e.target.value }))} />
        </div>
        <button className="btn btn-primary" onClick={handleChange}
          disabled={saving || !form.currentPassword || !form.newPassword}>
          {saving ? '변경 중...' : '비밀번호 변경'}
        </button>
      </div>
    </div>
  );
}
