import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import type { CBNode } from '../types';
import type { EditorStore } from '../store/editorStore';
import { useApi } from '../hooks/useApi';

// ── Shared categories list ────────────────────────────────────────────────────

export const TEMPLATE_CATEGORIES = [
  { slug: 'hero-sections',  label: 'Hero Sections' },
  { slug: 'cta-blocks',     label: 'CTA Blocks' },
  { slug: 'features',       label: 'Features' },
  { slug: 'testimonials',   label: 'Testimonials' },
  { slug: 'pricing-tables', label: 'Pricing Tables' },
  { slug: 'headers',        label: 'Headers' },
  { slug: 'footers',        label: 'Footers' },
  { slug: 'landing-pages',  label: 'Landing Pages' },
];

// ── Node wireframe preview ────────────────────────────────────────────────────

const NODE_COLORS: Record<string, [string, string]> = {
  section:   ['#f0f0f0', '#1a1a1a'],
  container: ['#f2f2f2', '#333333'],
  column:    ['#f5f5f5', '#444444'],
  heading:   ['#fef9c3', '#92400e'],
  text:      ['#f0fdf4', '#166534'],
  button:    ['#eff6ff', '#1e40af'],
  image:     ['#ecfdf5', '#065f46'],
  spacer:    ['#f9fafb', '#9ca3af'],
  divider:   ['#f9fafb', '#9ca3af'],
  icon:      ['#f5f5f5', '#1a1a1a'],
  video:     ['#fff7ed', '#9a3412'],
};

export function NodeWire({ node, depth = 0 }: { node: CBNode; depth?: number }) {
  const [bg, fg] = NODE_COLORS[node.type] ?? ['#f5f5f5', '#1a1a1a'];

  const preview = (() => {
    if (!node.content) return '';
    const c = node.content as Record<string, unknown>;
    const raw = String(c.text ?? c.html ?? '').replace(/<[^>]*>/g, '');
    return raw.slice(0, 50);
  })();

  const SHOW_CHILDREN_LIMIT = 8;

  return (
    <div style={{ marginLeft: depth * 12, marginBottom: 3 }}>
      <div className="jalpi-nodewire" style={{ background: bg, borderColor: bg }}>
        <span className="jalpi-nodewire__type" style={{ color: fg }}>{node.type}</span>
        {preview && <span className="jalpi-nodewire__text">{preview}</span>}
      </div>
      {node.children?.slice(0, SHOW_CHILDREN_LIMIT).map((child) => (
        <NodeWire key={child.id} node={child} depth={depth + 1} />
      ))}
      {(node.children?.length ?? 0) > SHOW_CHILDREN_LIMIT && (
        <div className="jalpi-nodewire__more" style={{ marginLeft: (depth + 1) * 12 }}>
          +{(node.children?.length ?? 0) - SHOW_CHILDREN_LIMIT} more…
        </div>
      )}
    </div>
  );
}

// ── Props ─────────────────────────────────────────────────────────────────────

interface Props {
  /** The node to save. Null = save full page. */
  node: CBNode | null;
  store: EditorStore;
  onClose: () => void;
  onSaved?: () => void;
}

// ── Component ─────────────────────────────────────────────────────────────────

export function SaveTemplateModal({ node, store, onClose, onSaved }: Props) {
  const api = useApi();
  const nameRef = useRef<HTMLInputElement>(null);

  // Auto-detect sensible default type
  const defaultType = (): 'element' | 'section' | 'page' => {
    if (!node) return 'page';
    if (node.type === 'section') return 'section';
    return 'element';
  };

  const [type,        setType]        = useState<'element' | 'section' | 'page'>(defaultType);
  const [name,        setName]        = useState(() => {
    if (!node) return 'Page Template';
    const c = node.content as Record<string, unknown> | undefined;
    const txt = String(c?.text ?? c?.html ?? '').replace(/<[^>]*>/g, '').slice(0, 50).trim();
    return txt || `${node.type.charAt(0).toUpperCase()}${node.type.slice(1)} Template`;
  });
  const [description, setDescription] = useState('');
  const [category,    setCategory]    = useState('');
  const [busy,        setBusy]        = useState(false);
  const [error,       setError]       = useState('');
  const [saved,       setSaved]       = useState(false);

  // Focus name on mount
  useEffect(() => { nameRef.current?.focus(); }, []);

  // Close on Escape
  useEffect(() => {
    const h = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [onClose]);

  // Preview node: for page type show first section
  const previewNode = type === 'page'
    ? (store.state.pageData.sections[0] ?? null)
    : node;

  // Save handler
  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    if (!name.trim()) { setError('A template name is required.'); return; }

    let data: unknown;
    if (type === 'page') {
      data = store.state.pageData;
    } else {
      if (!node) { setError('No element selected in the canvas.'); return; }
      data = node;
    }

    setBusy(true);
    try {
      await api.createTemplate({ name: name.trim(), description, category, type, data });
      setSaved(true);
      onSaved?.();
      setTimeout(onClose, 1100);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Save failed — please try again.');
    } finally {
      setBusy(false);
    }
  };

  const TYPE_OPTIONS: { id: 'element' | 'section' | 'page'; label: string; desc: string; icon: React.ReactElement }[] = [
    {
      id: 'element', label: 'Element', desc: 'Single block',
      icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="8" width="18" height="8" rx="2"/></svg>,
    },
    {
      id: 'section', label: 'Section', desc: 'Full section',
      icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="18" rx="2"/><line x1="2" y1="9" x2="22" y2="9"/></svg>,
    },
    {
      id: 'page', label: 'Page', desc: 'Entire page',
      icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>,
    },
  ];

  return createPortal(
    <div className="jalpi-stm-backdrop" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="jalpi-stm" role="dialog" aria-modal="true" aria-label="Save as Template">

        {/* Header */}
        <div className="jalpi-stm__head">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1a1a1a" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/>
            <polyline points="17 21 17 13 7 13 7 21"/>
            <polyline points="7 3 7 8 15 8"/>
          </svg>
          <span className="jalpi-stm__head-title">Save as Template</span>
          <button className="jalpi-stm__close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
              <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>

        {/* Body: form + preview */}
        <div className="jalpi-stm__body">

          {/* ── Form ── */}
          <form className="jalpi-stm__form" onSubmit={handleSave}>

            {/* Type selector */}
            <div className="jalpi-stm__field">
              <span className="jalpi-stm__label">Template type</span>
              <div className="jalpi-stm__types">
                {TYPE_OPTIONS.map((opt) => (
                  <button
                    key={opt.id}
                    type="button"
                    className={`jalpi-stm__type-btn${type === opt.id ? ' is-active' : ''}`}
                    onClick={() => setType(opt.id)}
                  >
                    <span className="jalpi-stm__type-icon">{opt.icon}</span>
                    <span className="jalpi-stm__type-label">{opt.label}</span>
                    <span className="jalpi-stm__type-desc">{opt.desc}</span>
                  </button>
                ))}
              </div>
              {type !== 'page' && !node && (
                <p className="jalpi-stm__hint">⚠ Select an element in the canvas first.</p>
              )}
            </div>

            {/* Name */}
            <div className="jalpi-stm__field">
              <label className="jalpi-stm__label" htmlFor="jalpi-stm-name">
                Name <span className="jalpi-stm__req">*</span>
              </label>
              <input
                id="jalpi-stm-name"
                ref={nameRef}
                className="jalpi-stm__input"
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Template name…"
                maxLength={100}
              />
            </div>

            {/* Description */}
            <div className="jalpi-stm__field">
              <label className="jalpi-stm__label" htmlFor="jalpi-stm-desc">Description</label>
              <textarea
                id="jalpi-stm-desc"
                className="jalpi-stm__textarea"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Optional — describe what this template is for…"
                rows={2}
              />
            </div>

            {/* Category */}
            <div className="jalpi-stm__field">
              <label className="jalpi-stm__label" htmlFor="jalpi-stm-cat">Category</label>
              <select
                id="jalpi-stm-cat"
                className="jalpi-stm__select"
                value={category}
                onChange={(e) => setCategory(e.target.value)}
              >
                <option value="">Uncategorised</option>
                {TEMPLATE_CATEGORIES.map((c) => (
                  <option key={c.slug} value={c.slug}>{c.label}</option>
                ))}
              </select>
            </div>

            {error && <div className="jalpi-stm__error" role="alert">{error}</div>}

            {/* Actions */}
            <div className="jalpi-stm__actions">
              <button type="button" className="jalpi-stm__cancel" onClick={onClose}>Cancel</button>
              <button
                type="submit"
                className={`jalpi-stm__save${saved ? ' is-saved' : ''}`}
                disabled={busy || saved || (type !== 'page' && !node)}
              >
                {saved ? '✓ Saved!' : busy ? 'Saving…' : 'Save Template'}
              </button>
            </div>
          </form>

          {/* ── Preview ── */}
          <div className="jalpi-stm__preview">
            <div className="jalpi-stm__preview-label">Structure preview</div>
            <div className="jalpi-stm__preview-scroll">
              {previewNode ? (
                <NodeWire node={previewNode} />
              ) : (
                <div className="jalpi-stm__preview-empty">
                  {type === 'page'
                    ? 'Current page has no sections'
                    : 'Nothing selected'}
                </div>
              )}
            </div>
          </div>

        </div>
      </div>
    </div>,
    document.body
  );
}
