import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { useCustomPages } from '../../lib/customPagesStore';
import { DocHtml } from '../../components/DocHtml';
import { CustomPageEditor } from '../../components/CustomPageEditor';

/**
 * Renders a single user-created documentation page at /docs/custom/:slug.
 *
 * Loads the page from the custom-pages store, renders its HTML body via
 * <DocHtml> (which also renders any Mermaid diagrams), and exposes an inline
 * editor + "Beautify with AI" action. Supports create-new (no slug) and
 * delete.
 */
export function CustomPageView({ mode }: { mode: 'view' | 'create' }) {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const { pages, loading, error, getBySlug, refresh, refreshing } = useCustomPages();

  const [editing, setEditing] = useState(mode === 'create');
  const [notFound, setNotFound] = useState(false);

  const page = slug ? getBySlug(slug) : undefined;

  // If we are viewing a slug that isn't in the store yet (e.g. directly
  // navigating to a URL or the store is mid-refresh), try refreshing once.
  useEffect(() => {
    if (mode === 'view' && slug && !page && !loading && !notFound) {
      void refresh().then(() => {
        if (!getBySlug(slug)) setNotFound(true);
      });
    }
  }, [mode, slug, page, loading, notFound, refresh, getBySlug]);

  if (mode === 'view' && notFound && !loading) {
    return (
      <div className="mx-auto max-w-content">
        <h1 className="mb-2">Page not found</h1>
        <p className="text-fg-dim">
          No custom page exists at <code className="font-mono text-accent">/docs/custom/{slug}</code>.
        </p>
        <div className="mt-6">
          <Link className="text-cyan underline" to="/docs/custom">
            ← Back to custom pages
          </Link>
        </div>
      </div>
    );
  }

  if (mode === 'view' && !page) {
    return (
      <div className="mx-auto max-w-content font-mono text-sm text-muted">
        Loading…
      </div>
    );
  }

  if (mode === 'view' && page) {
    return (
      <div className="mx-auto max-w-content">
        <div className="mb-6 flex flex-wrap items-center gap-3 border-b border-border pb-4">
          <span className="text-2xl">{page.icon}</span>
          <h1 className="m-0">{page.title}</h1>
          <span className="ml-auto flex items-center gap-2">
            {page.beautified && (
              <span className="rounded-full border border-purple/25 bg-purple/8 px-2.5 py-0.5 font-mono text-[0.7rem] text-purple">
                ✦ AI-Beautified
              </span>
            )}
            <button
              className="cursor-pointer rounded-lg border border-border bg-surface px-3 py-1.5 font-mono text-[0.75rem] text-fg-dim transition-colors hover:border-border-light hover:text-fg"
              onClick={() => setEditing(true)}
            >
              ✎ Edit
            </button>
          </span>
        </div>

        {page.blurb && (
          <p className="mb-6 max-w-[680px] text-[0.95rem] text-fg-dim">{page.blurb}</p>
        )}

        <DocHtml html={page.html} />

        {editing && (
          <CustomPageEditor
            page={page}
            onClose={() => setEditing(false)}
            onDeleted={() => navigate('/docs/custom')}
          />
        )}
      </div>
    );
  }

  // mode === 'create'
  return (
    <div className="mx-auto max-w-content">
      <div className="mb-6 flex items-center gap-3 border-b border-border pb-4">
        <h1 className="m-0">New Custom Page</h1>
      </div>
      <CustomPageEditor
        page={null}
        onClose={() => navigate('/docs/custom')}
        onSaved={(saved) => navigate(`/docs/custom/${saved.slug}`)}
      />
      {error && (
        <p className="mt-4 font-mono text-[0.8rem] text-red">{error}</p>
      )}
      {refreshing && (
        <p className="mt-4 font-mono text-[0.8rem] text-muted">Refreshing…</p>
      )}
    </div>
  );
}
