'use client';

import * as React from 'react';
import { useRouter } from 'next/navigation';
import AdminModal from '@/app/components/admin/admin-modal.jsx';

export default function UploadArtifactModal({ projectId }) {
  const router = useRouter();
  const [open, setOpen] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const formRef = React.useRef(null);

  function reset() {
    setError(null);
    setBusy(false);
    if (formRef.current) formRef.current.reset();
  }

  function close() {
    if (busy) return;
    reset();
    setOpen(false);
  }

  async function handleSubmit(e) {
    e.preventDefault();
    if (busy) return;
    setError(null);
    const form = e.currentTarget;
    const data = new FormData(form);
    const file = data.get('file');
    if (!file || (typeof file === 'object' && !file.size)) {
      setError('Pick an HTML file first.');
      return;
    }
    setBusy(true);
    try {
      const res = await fetch('/api/artifacts/upload', { method: 'POST', body: data });
      const json = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(json?.error || `Upload failed (${res.status})`);
        setBusy(false);
        return;
      }
      reset();
      setOpen(false);
      router.refresh();
    } catch (err) {
      setError(err?.message || 'Upload failed');
      setBusy(false);
    }
  }

  return (
    <>
      <button type="button" className="admin-button agents-new-cta" onClick={() => setOpen(true)}>
        <span aria-hidden className="agents-new-cta-glyph">+</span>
        Upload HTML
      </button>

      <AdminModal open={open} onClose={close} eyebrow="Upload" title="Add HTML artifact">
        <form ref={formRef} className="agents-modal-form" onSubmit={handleSubmit}>
          <input type="hidden" name="project_id" value={projectId} />

          <section className="agents-modal-section">
            <label className="agents-modal-field wide">
              <span>HTML file</span>
              <input type="file" name="file" accept=".html,.htm,text/html" required aria-label="Choose HTML file" disabled={busy} />
            </label>
            <label className="agents-modal-field wide">
              <span>Title (optional)</span>
              <input type="text" name="title" placeholder="Defaults to filename" disabled={busy} />
            </label>
          </section>

          {error ? (
            <p className="agents-modal-help" role="alert" style={{ color: 'var(--mars-red, #c2452a)' }}>
              {error}
            </p>
          ) : (
            <p className="agents-modal-help">
              Stored as a project artifact (renders in Library, supports protect/share). Max 5 MB.
            </p>
          )}

          <footer className="agents-modal-foot">
            <button type="button" className="admin-button secondary" onClick={close} disabled={busy}>
              Cancel
            </button>
            <button type="submit" className="admin-button" disabled={busy}>
              {busy ? 'Uploading…' : 'Upload'}
            </button>
          </footer>
        </form>
      </AdminModal>
    </>
  );
}
