import { useState, useEffect } from 'react';
import { getDownloadInfo } from '../../api/download';
import { apiFetch } from '../../api/client';
import './AdminCommon.css';

export default function DownloadAdmin() {
  const [form, setForm] = useState({ url: '', version: '', fileName: '', fileSize: '' });
  const [loading, setLoading] = useState(false);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    getDownloadInfo()
      .then((data) => setForm({
        url: data.url,
        version: data.version,
        fileName: data.fileName,
        fileSize: data.fileSize,
      }))
      .catch(() => {});
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      await apiFetch('/api/download/info', {
        method: 'PUT',
        body: JSON.stringify(form),
      });
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    } finally {
      setLoading(false);
    }
  };

  const field = (label, key, placeholder) => (
    <div className="admin-field">
      <label className="admin-label">{label}</label>
      <input
        className="admin-input"
        placeholder={placeholder}
        value={form[key]}
        onChange={(e) => setForm({ ...form, [key]: e.target.value })}
      />
    </div>
  );

  return (
    <div className="admin-section">
      <h2 className="admin-section-title">다운로드 정보 관리</h2>
      <form className="admin-form" onSubmit={handleSubmit}>
        {field('다운로드 URL', 'url', 'https://...')}
        {field('버전', 'version', 'v1.0.0')}
        {field('파일명', 'fileName', 'A301_Launcher.exe')}
        {field('파일 크기', 'fileSize', '1.2 GB')}
        <div className="admin-form-actions">
          <button className="btn-admin-primary" type="submit" disabled={loading}>
            {saved ? '저장됨 ✓' : '저장'}
          </button>
        </div>
      </form>
    </div>
  );
}
