'use client';

import { useState, useCallback, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useRouter } from 'next/navigation';
import SettingsDrawer from './settings-drawer.jsx';

// Workflows page definition card. Kept visually aligned with Projects and
// Marketplace: quiet white card, small tile, minimal metadata, direct actions.
//
// Start calls /api/processes/start-and-route to create the case immediately,
// then routes to the branded interactive intake artifact page (the only intake
// path as of v2.14.0).
//
// Configure opens a right-edge drawer (`SettingsDrawer`) for the
// per-(definition, project) settings. Share mints + copies a share token
// URL.
export default function DefinitionCard({
  definition,
  projects,
  defaultProjectId,
  usage = 0,
}) {
  const router = useRouter();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [shareUrl, setShareUrl] = useState(null);

  useEffect(() => { setMounted(true); }, []);
  const [shareError, setShareError] = useState(null);
  const [starting, setStarting] = useState(false);
  const [error, setError] = useState(null);
  const initialProjectId = defaultProjectId || projects?.[0]?.id || 'personal';

  const onStart = useCallback(async () => {
    setError(null);
    setStarting(true);
    try {
      const res = await fetch('/api/processes/start-and-route', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ definition_slug: definition.slug, project_id: initialProjectId }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || 'start_failed');
      router.push(json.redirect_url || `/workflows/${json.case_id}`);
    } catch (err) {
      setError(String(err?.message || err));
      setStarting(false);
    }
  }, [definition.slug, initialProjectId, router]);

  const onShare = useCallback(async () => {
    setShareError(null);
    setShareUrl(null);
    try {
      const startRes = await fetch('/api/processes/start-and-route', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ definition_slug: definition.slug, project_id: initialProjectId }),
      });
      const startJson = await startRes.json();
      if (!startRes.ok) throw new Error(startJson.error || 'start_failed');
      const mintRes = await fetch(`/api/processes/${startJson.case_id}/share-link`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: '{}',
      });
      const mintJson = await mintRes.json();
      if (!mintRes.ok) throw new Error(mintJson.error || 'mint_failed');
      setShareUrl(mintJson.link);
      try { await navigator.clipboard.writeText(mintJson.link); } catch { /* clipboard optional */ }
    } catch (err) {
      setShareError(String(err?.message || err));
    }
  }, [definition.slug, initialProjectId]);

  // Initials chip — first 2 chars of name uppercased.
  const initials = (definition.name || '??').replace(/[^a-zA-Z]/g, '').slice(0, 2).toUpperCase() || '??';

  return (
    <li className="mkt-card wf-defcard">
      <div className="mkt-card-head wf-defcard-top">
        <div className="wf-defcard-cover" aria-hidden>
        <span className="wf-defcard-initials">{initials}</span>
        </div>
        <span className="wf-defcard-version">v{definition.version}</span>
      </div>
      <div className="mkt-card-body wf-defcard-body">
        <header className="wf-defcard-head">
          <div>
            <span className="wf-defcard-kicker">{definition.category || 'process'}</span>
            <h3 className="mkt-card-title">{definition.name}</h3>
          </div>
          <span className="wf-defcard-usage" title={`${usage} cases started`}>
            {usage} {usage === 1 ? 'case' : 'cases'}
          </span>
        </header>
        <p className="mkt-card-desc wf-defcard-desc">{definition.description || 'No description.'}</p>

        {error ? <p className="wf-defcard-error">{error}</p> : null}
        {shareError ? <p className="wf-defcard-error">Share: {shareError}</p> : null}
        {shareUrl ? (
          <p className="wf-defcard-share">
            <span>Link copied:</span>
            <a href={shareUrl} target="_blank" rel="noreferrer">{shareUrl}</a>
          </p>
        ) : null}

        <div className="wf-defcard-actions">
          <button type="button" className="wf-defcard-btn wf-defcard-btn--primary" onClick={onStart} disabled={starting}>
            {starting ? 'Starting…' : 'Start case'}
          </button>
          <button type="button" className="wf-defcard-btn" onClick={() => setDrawerOpen(true)}>
            Configure
          </button>
          <button type="button" className="wf-defcard-btn" onClick={onShare}>
            Share
          </button>
        </div>
      </div>

      {drawerOpen && mounted
        ? createPortal(
            <SettingsDrawer
              definition={definition}
              projects={projects}
              initialProjectId={initialProjectId}
              onClose={() => setDrawerOpen(false)}
            />,
            document.body,
          )
        : null}
    </li>
  );
}
