import { useState } from 'react';
import { api } from '../api';

export default function ImageField({ value, onChange, disabled }) {
  const [uploading, setUploading] = useState(false);

  const onFile = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const data = await api.adminUpload(file);
      onChange(data.url);
    } catch (err) {
      alert(err.message);
    } finally {
      setUploading(false);
      e.target.value = '';
    }
  };

  return (
    <div className="image-field">
      {value ? (
        <div className="admin-thumb">
          <img src={value} alt="" />
        </div>
      ) : (
        <div className="admin-thumb empty">No img</div>
      )}
      <input
        placeholder="Image URL or upload"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        disabled={disabled}
      />
      <label className="btn secondary file-btn">
        {uploading ? '…' : 'Upload'}
        <input
          type="file"
          accept="image/png,image/jpeg,image/webp,image/gif,.png,.jpg,.jpeg,.webp,.gif"
          hidden
          onChange={onFile}
          disabled={disabled || uploading}
        />
      </label>
      {value ? (
        <button
          type="button"
          className="btn ghost"
          onClick={() => onChange('')}
          disabled={disabled}
        >
          Clear
        </button>
      ) : null}
    </div>
  );
}
