'use client';

import { useEffect, useState, useCallback, useRef, ReactNode } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import dynamic from 'next/dynamic';
import type { Data } from '@measured/puck';
import { puckConfig } from '@/lib/cms/puck-config';
import '@measured/puck/puck.css';

// Dynamically import Puck to avoid SSR issues
const Puck = dynamic(() => import('@measured/puck').then((mod) => mod.Puck), {
  ssr: false,
  loading: () => (
    <div style={{ padding: '2rem', textAlign: 'center' }}>
      <p>Loading editor...</p>
      <p style={{ fontSize: '0.875rem', color: '#64748b', marginTop: '0.5rem' }}>
        This may take a moment on first load
      </p>
    </div>
  ),
});

interface ResourceGuide {
  id: string;
  title: string;
  slug: string;
  status: 'draft' | 'published';
  puckData: Data | null;
  category: {
    id: string;
    name: string;
    slug: string;
  };
}

interface ResourceCategory {
  id: string;
  name: string;
  slug: string;
}

export default function ResourceGuideEditorPage() {
  const params = useParams();
  const guideId = params.id as string;

  const [guide, setGuide] = useState<ResourceGuide | null>(null);
  const [categories, setCategories] = useState<ResourceCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [showSettings, setShowSettings] = useState(false);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const currentPuckDataRef = useRef<Data | null>(null);

  // Settings form state
  const [title, setTitle] = useState('');
  const [slug, setSlug] = useState('');
  const [categoryId, setCategoryId] = useState('');

  // Warn about unsaved changes when leaving page
  useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (hasUnsavedChanges) {
        e.preventDefault();
        e.returnValue = 'You have unsaved changes. Are you sure you want to leave?';
        return e.returnValue;
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [hasUnsavedChanges]);

  // Fix space key not working in Puck input fields
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      const target = e.target as HTMLElement;
      if (
        target.tagName === 'INPUT' ||
        target.tagName === 'TEXTAREA' ||
        target.isContentEditable ||
        target.closest('.lexical-editor-root') ||
        target.closest('.lexical-content-editable')
      ) {
        e.stopPropagation();
      }
    };

    document.addEventListener('keydown', handleKeyDown, true);
    return () => document.removeEventListener('keydown', handleKeyDown, true);
  }, []);

  const fetchGuide = useCallback(async () => {
    try {
      const response = await fetch(`/api/admin/resource-guides/${guideId}`);
      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || 'Failed to fetch guide');
      }
      const data = await response.json();
      setGuide(data.guide);
      setTitle(data.guide.title);
      setSlug(data.guide.slug);
      setCategoryId(data.guide.category.id);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load guide');
    } finally {
      setLoading(false);
    }
  }, [guideId]);

  const fetchCategories = useCallback(async () => {
    try {
      const response = await fetch('/api/admin/resource-categories');
      if (response.ok) {
        const data = await response.json();
        setCategories(data.categories);
      }
    } catch {
      // Categories are optional for display purposes
    }
  }, []);

  useEffect(() => {
    fetchGuide();
    fetchCategories();
  }, [fetchGuide, fetchCategories]);

  const handleSettingChange = <T,>(setter: (value: T) => void, value: T) => {
    setter(value);
    setHasUnsavedChanges(true);
  };

  const handleSave = async (puckData: Data) => {
    if (!guide) return;

    setSaving(true);
    setError(null);
    setSuccessMessage(null);

    try {
      const response = await fetch(`/api/admin/resource-guides/${guideId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: title.trim(),
          slug: slug.trim(),
          categoryId,
          puckData,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to save guide');
      }

      setGuide(data.guide);
      setHasUnsavedChanges(false);
      setSuccessMessage('Guide saved successfully!');
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save guide');
    } finally {
      setSaving(false);
    }
  };

  const handlePublish = async () => {
    if (!guide || saving) return;

    setSaving(true);
    setError(null);
    setSuccessMessage(null);

    try {
      const puckData = currentPuckDataRef.current || guide.puckData;
      const response = await fetch(`/api/admin/resource-guides/${guideId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: title.trim(),
          slug: slug.trim(),
          categoryId,
          puckData,
          status: 'published',
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to publish guide');
      }

      setGuide(data.guide);
      setHasUnsavedChanges(false);
      setSuccessMessage('Guide published successfully!');
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to publish guide');
    } finally {
      setSaving(false);
    }
  };

  const handleUnpublish = async () => {
    if (!guide || saving) return;

    setSaving(true);
    setError(null);
    setSuccessMessage(null);

    try {
      const response = await fetch(`/api/admin/resource-guides/${guideId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          status: 'draft',
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to unpublish guide');
      }

      setGuide(data.guide);
      setSuccessMessage('Guide unpublished (now draft)');
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to unpublish guide');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div style={{ padding: '2rem', textAlign: 'center' }}>
        <p>Loading guide...</p>
      </div>
    );
  }

  if (error || !guide) {
    return (
      <div style={{ padding: '2rem', textAlign: 'center' }}>
        <h2 style={{ color: '#dc2626', marginBottom: '1rem' }}>Error</h2>
        <p style={{ marginBottom: '1rem' }}>{error || 'Guide not found'}</p>
        <Link href="/admin/resource-guides" style={{ color: '#38bdf8', textDecoration: 'none' }}>
          &larr; Back to Resource Guides
        </Link>
      </div>
    );
  }

  const initialData: Data = guide.puckData || {
    content: [],
    root: { props: { title: guide.title } },
  };

  return (
    <div
      style={{
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        minHeight: 0,
      }}
    >
      {/* Top Bar */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          padding: '0.75rem 1rem',
          borderBottom: '1px solid rgba(148, 163, 184, 0.25)',
          backgroundColor: '#1e293b',
        }}
      >
        <Link
          href="/admin/resource-guides"
          style={{ color: '#38bdf8', textDecoration: 'none', fontSize: '0.875rem' }}
        >
          &larr; Back to Resource Guides
        </Link>

        <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
          <span
            style={{
              fontSize: '0.75rem',
              padding: '2px 8px',
              borderRadius: '4px',
              background: guide.status === 'published' ? '#d1fae5' : '#fef3c7',
              color: guide.status === 'published' ? '#065f46' : '#92400e',
              textTransform: 'uppercase',
              fontWeight: 500,
            }}
          >
            {guide.status}
          </span>
          {guide.status === 'published' && (
            <a
              href={`/resources/${guide.slug}`}
              target="_blank"
              rel="noopener noreferrer"
              style={{
                color: '#38bdf8',
                textDecoration: 'none',
                fontSize: '0.875rem',
              }}
            >
              View Guide &rarr;
            </a>
          )}
          <button
            onClick={() => setShowSettings(!showSettings)}
            style={{
              padding: '6px 12px',
              background: 'transparent',
              color: '#94a3b8',
              border: '1px solid #475569',
              borderRadius: '4px',
              fontSize: '0.875rem',
              cursor: 'pointer',
            }}
          >
            Settings
          </button>
          {guide.status === 'published' && (
            <button
              onClick={handleUnpublish}
              disabled={saving}
              style={{
                padding: '6px 12px',
                background: 'transparent',
                color: '#f59e0b',
                border: '1px solid #f59e0b',
                borderRadius: '4px',
                fontSize: '0.875rem',
                cursor: saving ? 'not-allowed' : 'pointer',
                opacity: saving ? 0.5 : 1,
              }}
            >
              Unpublish
            </button>
          )}
          <button
            onClick={handlePublish}
            disabled={saving}
            style={{
              padding: '6px 12px',
              background: '#38bdf8',
              color: '#0f172a',
              border: 'none',
              borderRadius: '4px',
              fontSize: '0.875rem',
              fontWeight: 500,
              cursor: saving ? 'not-allowed' : 'pointer',
              opacity: saving ? 0.5 : 1,
            }}
          >
            {saving ? 'Saving...' : guide.status === 'published' ? 'Save & Publish' : 'Publish'}
          </button>
        </div>
      </div>

      {/* Settings Panel */}
      {showSettings && (
        <div
          style={{
            padding: '1rem',
            borderBottom: '1px solid #e5e7eb',
            backgroundColor: '#f9fafb',
          }}
        >
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
              gap: '1rem',
            }}
          >
            <div>
              <label
                style={{
                  display: 'block',
                  fontWeight: 500,
                  marginBottom: '0.25rem',
                  fontSize: '0.875rem',
                  color: '#000',
                }}
              >
                Title
              </label>
              <input
                type="text"
                value={title}
                onChange={(e) => handleSettingChange(setTitle, e.target.value)}
                style={{
                  width: '100%',
                  padding: '0.5rem',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '0.875rem',
                  color: '#000',
                  backgroundColor: '#fff',
                }}
              />
            </div>
            <div>
              <label
                style={{
                  display: 'block',
                  fontWeight: 500,
                  marginBottom: '0.25rem',
                  fontSize: '0.875rem',
                  color: '#000',
                }}
              >
                Slug
              </label>
              <input
                type="text"
                value={slug}
                onChange={(e) => {
                  const sanitizedSlug = e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '');
                  handleSettingChange(setSlug, sanitizedSlug);
                }}
                style={{
                  width: '100%',
                  padding: '0.5rem',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '0.875rem',
                  color: '#000',
                  backgroundColor: '#fff',
                }}
              />
            </div>
            <div>
              <label
                style={{
                  display: 'block',
                  fontWeight: 500,
                  marginBottom: '0.25rem',
                  fontSize: '0.875rem',
                  color: '#000',
                }}
              >
                Category
              </label>
              <select
                value={categoryId}
                onChange={(e) => handleSettingChange(setCategoryId, e.target.value)}
                style={{
                  width: '100%',
                  padding: '0.5rem',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '0.875rem',
                  color: '#000',
                  backgroundColor: '#fff',
                }}
              >
                {categories.map((cat) => (
                  <option key={cat.id} value={cat.id}>
                    {cat.name}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>
      )}

      {/* Success Banner */}
      {successMessage && (
        <div
          style={{
            padding: '0.75rem 1rem',
            backgroundColor: 'rgba(52, 211, 153, 0.1)',
            borderBottom: '1px solid rgba(52, 211, 153, 0.35)',
            borderLeft: '4px solid #34d399',
            color: '#d1fae5',
            fontSize: '0.875rem',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          {successMessage}
          <button
            onClick={() => setSuccessMessage(null)}
            style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#34d399' }}
          >
            x
          </button>
        </div>
      )}

      {/* Error Banner */}
      {error && (
        <div
          style={{
            padding: '0.75rem 1rem',
            backgroundColor: 'rgba(248, 113, 113, 0.1)',
            borderBottom: '1px solid rgba(248, 113, 113, 0.35)',
            borderLeft: '4px solid #f87171',
            color: '#fee2e2',
            fontSize: '0.875rem',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          {error}
          <button
            onClick={() => setError(null)}
            style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#f87171' }}
          >
            x
          </button>
        </div>
      )}

      {/* Puck Editor */}
      <style>{`
        /* Preview canvas - dark background to match dashboard */
        [class*="Puck-canvas"],
        [class*="PuckCanvas"],
        [class*="_Puck-canvas"],
        [class*="_PuckCanvas"] {
          background-color: #0f172a !important;
        }
        /* Remove padding from root dropzone */
        [data-puck-dropzone="root:default-zone"] {
          padding: 0;
          background-color: transparent;
        }
        /* Fix white-on-white inputs and labels in Puck sidebar */
        [class*="Puck"] input,
        [class*="Puck"] textarea,
        [class*="Puck"] select {
          color: #000 !important;
          background-color: #fff !important;
        }
        [class*="Puck"] input::placeholder,
        [class*="Puck"] textarea::placeholder {
          color: #6b7280 !important;
        }
        [class*="Puck"] label {
          color: #000 !important;
        }
        /* Fix viewport controls */
        [class*="ViewportButton"]:not([class*="--isActive"]) svg {
          stroke: #6b7280 !important;
          color: #6b7280 !important;
        }
        [class*="--isActive"] svg {
          stroke: #000 !important;
          color: #000 !important;
        }
        /* Two-column dropzone styling - adjusted for dark theme */
        .cms-two-column [data-puck-dropzone] {
          min-height: 100px;
          border: 1px dashed rgba(148, 163, 184, 0.4);
          border-radius: 8px;
          padding: 0.75rem;
          background-color: rgba(30, 41, 59, 0.5);
        }
        /* Spacer visual indicator in editor */
        .cms-spacer {
          border: 1px dotted rgba(148, 163, 184, 0.4);
          border-radius: 4px;
          background-color: rgba(30, 41, 59, 0.5);
        }
        /* ViewportControls padding */
        [class*="ViewportControls_"] {
          padding-top: 8px !important;
          padding-bottom: 8px !important;
        }
        /* PuckCanvas padding */
        [class*="PuckCanvas_"] {
          padding: 0 !important;
          overflow: hidden !important;
        }
        /* Preview iframe - fill available space minus custom header (60px) */
        [class*="PuckPreview"] iframe {
          height: calc(100% - 60px) !important;
        }
        /* Sidebars - account for our custom header (60px) */
        [class*="_Sidebar"][class*="--left"],
        [class*="_Sidebar"][class*="--right"] {
          height: calc(100% - 60px) !important;
        }
        /* Rich text links - adjusted for dark theme */
        .cms-rich-text a {
          color: #38bdf8;
          text-decoration: underline;
        }
        .cms-rich-text a:hover {
          color: #7dd3fc;
        }
      `}</style>
      <div style={{ flex: 1, overflow: 'hidden', minHeight: 0 }}>
        <Puck
          config={puckConfig}
          data={initialData}
          headerTitle={guide.title}
          onChange={(data) => {
            currentPuckDataRef.current = data;
            if (!hasUnsavedChanges) setHasUnsavedChanges(true);
          }}
          onPublish={handleSave}
          overrides={{
            headerActions: () => <></>,
            iframe: function IframeWrapper({
              children,
              document: iframeDoc,
            }: {
              children: ReactNode;
              document?: Document;
            }) {
              useEffect(() => {
                // Apply dark theme styles to iframe document
                if (iframeDoc?.documentElement && iframeDoc?.body) {
                  try {
                    iframeDoc.documentElement.style.cssText = 'margin: 0; background: #0f172a;';
                    iframeDoc.body.style.cssText =
                      'margin: 0; padding: 0; background: #0f172a; min-height: 100vh;';
                  } catch {
                    // Silently handle edge cases
                  }
                }
              }, [iframeDoc]);

              return (
                <div
                  style={{
                    minHeight: '100vh',
                    background: '#0f172a',
                    padding: '24px',
                  }}
                >
                  {/* Dark theme overrides for Puck components */}
                  <style>{`
                    /* Override Heading component inline colors */
                    .cms-heading {
                      color: #f8fafc !important;
                    }

                    /* Override RichText component inline colors */
                    .cms-rich-text,
                    .cms-rich-text * {
                      color: #f8fafc !important;
                    }
                    .cms-rich-text a {
                      color: #38bdf8 !important;
                    }

                    /* Override Accordion component colors */
                    .cms-accordion button {
                      background: #1e293b !important;
                      color: #f8fafc !important;
                    }
                    .cms-accordion button span {
                      color: #38bdf8 !important;
                    }
                    .cms-accordion > div {
                      border-color: rgba(148, 163, 184, 0.25) !important;
                    }
                    .cms-accordion > div > div:last-child {
                      background: #0f172a !important;
                      color: #f8fafc !important;
                      border-color: rgba(148, 163, 184, 0.25) !important;
                    }

                    /* Override Tabs component colors */
                    .cms-tabs > div:first-child {
                      border-color: rgba(148, 163, 184, 0.25) !important;
                    }
                    .cms-tabs button {
                      color: #94a3b8 !important;
                    }
                    .cms-tabs > div:last-child {
                      color: #f8fafc !important;
                    }

                    /* Override Divider colors */
                    hr {
                      border-color: rgba(148, 163, 184, 0.25) !important;
                    }

                    /* Override Image caption and placeholder colors */
                    figcaption {
                      color: #94a3b8 !important;
                    }
                  `}</style>

                  {/* Preview Header */}
                  <div
                    style={{
                      maxWidth: '900px',
                      margin: '0 auto 32px',
                    }}
                  >
                    <div
                      style={{
                        display: 'inline-block',
                        padding: '4px 12px',
                        background: 'rgba(56, 189, 248, 0.15)',
                        color: '#38bdf8',
                        borderRadius: '16px',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '12px',
                      }}
                    >
                      {guide?.category?.name || 'Category'}
                    </div>
                    <h1
                      style={{
                        fontSize: '2rem',
                        fontWeight: 700,
                        color: '#f8fafc',
                        margin: 0,
                        lineHeight: 1.3,
                      }}
                    >
                      {title || guide?.title || 'Guide Title'}
                    </h1>
                  </div>

                  {/* Content Card */}
                  <div
                    style={{
                      maxWidth: '900px',
                      margin: '0 auto',
                      background: '#1e293b',
                      border: '1px solid rgba(148, 163, 184, 0.25)',
                      borderRadius: '12px',
                      padding: '32px',
                      color: '#f8fafc',
                      lineHeight: 1.7,
                    }}
                  >
                    {children}
                  </div>
                </div>
              );
            },
          }}
        />
      </div>
    </div>
  );
}
