'use client';

import { Puck, usePuck, type Data } from "@puckeditor/core";
import "@puckeditor/core/puck.css";
import { puckConfig } from "@/lib/puck/config";
import { useState, useCallback, useRef, useEffect } from "react";
import { useRouter } from 'next/navigation';
import { CreatePageModal } from '@/components/editor/CreatePageModal';
import { PageSettingsModal } from '@/components/editor/PageSettingsModal';
import { DeletePageModal } from '@/components/editor/DeletePageModal';
import { NavigationManagerModal } from '@/components/editor/NavigationManagerModal';
import { SubscribersModal } from '@/components/modals/SubscribersModal';

interface EditorClientProps {
  initialData: any;
  categories: { name: string; slug: string }[];
  navigationItems: any[];
  pages: any[];
  currentPath: string;
}

// ─── Save Status Badge ────────────────────────────────────────────────────────
function StatusBadge({ status }: { status: string }) {
  if (status === 'idle') return null;

  const configs: Record<string, { color: string; icon: string; text: string }> = {
    saving: { color: '#94a3b8', icon: '⟳', text: 'Saving...' },
    saved: { color: '#22c55e', icon: '✓', text: 'Published' },
    'draft-saving': { color: '#94a3b8', icon: '⟳', text: 'Saving draft...' },
    'draft-saved': { color: '#f59e0b', icon: '✓', text: 'Draft saved' },
    'auto-saving': { color: '#64748b', icon: '⟳', text: 'Auto-saving...' },
    'auto-saved': { color: '#64748b', icon: '✓', text: 'Auto-saved' },
    error: { color: '#ef4444', icon: '✗', text: 'Save failed' },
  };

  const c = configs[status] || configs.saving;

  return (
    <span style={{
      color: c.color,
      fontSize: '12px',
      fontWeight: 500,
      display: 'flex',
      alignItems: 'center',
      gap: '4px',
      transition: 'opacity 0.3s',
    }}>
      {status === 'saving' || status === 'draft-saving' || status === 'auto-saving' ? (
        <svg style={{ animation: 'spin 1s linear infinite' }} width="13" height="13" viewBox="0 0 24 24" fill="none">
          <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="3" opacity="0.3" />
          <path d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" fill="currentColor" />
        </svg>
      ) : (
        <span style={{ fontSize: '13px' }}>{c.icon}</span>
      )}
      {c.text}
    </span>
  );
}

// ─── Header Actions (inside Puck context) ─────────────────────────────────────
function HeaderActions({
  saveStatus,
  onSave,
  onDraft,
  pages,
  currentPath,
  onPageChange,
}: {
  saveStatus: string;
  onSave: (data: Data) => void;
  onDraft: (data: Data) => void;
  pages: any[];
  currentPath: string;
  onPageChange: (path: string) => void;
}) {
  const { appState } = usePuck();
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showSettingsModal, setShowSettingsModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showNavManager, setShowNavManager] = useState(false);
  const [showSubscribersModal, setShowSubscribersModal] = useState(false);
  const router = useRouter();

  const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    if (e.target.value === '__create__') {
      setShowCreateModal(true);
      // reset the select back to current path visually
      e.target.value = currentPath;
    } else {
      onPageChange(e.target.value);
    }
  };

  const defaultPages = pages.filter(p => !p.isCustom);
  const customPages = pages.filter(p => p.isCustom);
  const currentPageObj = pages.find(p => p.path === currentPath);

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
      <select 
        value={currentPath} 
        onChange={handleSelectChange}
        style={{
          padding: '6px 12px',
          borderRadius: '6px',
          border: '1px solid #d1d5db',
          background: '#fff',
          fontSize: '13px',
          outline: 'none',
          cursor: 'pointer'
        }}
      >
        <optgroup label="Default Pages">
          {defaultPages.map(p => (
            <option key={p.path} value={p.path}>{p.title}</option>
          ))}
        </optgroup>
        {customPages.length > 0 && (
          <optgroup label="Custom Pages">
            {customPages.map(p => (
              <option key={p.path} value={p.path}>{p.title}</option>
            ))}
          </optgroup>
        )}
        <optgroup label="Actions">
          <option value="__create__">➕ Create New Page...</option>
        </optgroup>
      </select>

      {currentPageObj?.isCustom && (
        <div style={{ display: 'flex', gap: '8px' }}>
          <button 
            onClick={() => setShowSettingsModal(true)}
            style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '4px', color: '#4b5563' }}
            title="Page Settings"
          >
            ⚙️
          </button>
          <button 
            onClick={() => setShowDeleteModal(true)}
            style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '4px', color: '#dc2626' }}
            title="Delete Page"
          >
            🗑️
          </button>
        </div>
      )}

      {/* Globally visible Navigation Manager button */}
      <button
        onClick={() => setShowNavManager(true)}
        style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '4px', color: '#4b5563', marginLeft: currentPageObj?.isCustom ? '0' : '8px' }}
        title="Navigation Manager"
      >
        🧭
      </button>

      {/* NEW: Subscribers Viewer button */}
      <button
        onClick={() => setShowSubscribersModal(true)}
        style={{ 
          background: '#f0fdf4', 
          border: '1px solid #bbf7d0', 
          cursor: 'pointer', 
          padding: '4px', 
          color: '#15803d', 
          marginLeft: '4px',
          width: '32px',
          height: '32px',
          borderRadius: '6px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: '18px'
        }}
        title="Subscribers Viewer"
      >
        📧
      </button>

      {showCreateModal && (
        <CreatePageModal 
          onClose={() => setShowCreateModal(false)} 
          onSuccess={(slug) => {
            setShowCreateModal(false);
            window.location.href = `/page_editor_admin?path=/${slug}`;
          }} 
        />
      )}

      {showSettingsModal && currentPageObj?.isCustom && (
        <PageSettingsModal
          pageId={currentPageObj.id}
          initialTitle={currentPageObj.title}
          initialMetaTitle={currentPageObj.metaTitle}
          initialMetaDescription={currentPageObj.metaDescription}
          onClose={() => setShowSettingsModal(false)}
          onSuccess={() => {
            setShowSettingsModal(false);
            router.refresh();
          }}
        />
      )}

      {showDeleteModal && currentPageObj?.isCustom && (
        <DeletePageModal
          pageId={currentPageObj.id}
          slug={currentPageObj.path.replace(/^\//, '')}
          pageTitle={currentPageObj.title}
          onClose={() => setShowDeleteModal(false)}
          onSuccess={() => {
            setShowDeleteModal(false);
            window.location.href = '/page_editor_admin?path=/';
          }}
        />
      )}

      {showNavManager && (
        <NavigationManagerModal onClose={() => setShowNavManager(false)} />
      )}

      {showSubscribersModal && (
        <SubscribersModal isOpen={showSubscribersModal} onClose={() => setShowSubscribersModal(false)} />
      )}

      <div style={{ width: '1px', height: '24px', background: '#d1d5db' }} />

      <StatusBadge status={saveStatus} />

      {/* Save Draft Button */}
      <button
        onClick={() => onDraft(appState.data)}
        disabled={saveStatus === 'saving' || saveStatus === 'draft-saving'}
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: '5px',
          padding: '6px 14px',
          fontSize: '13px',
          fontWeight: 600,
          color: '#374151',
          background: '#f3f4f6',
          border: '1px solid #d1d5db',
          borderRadius: '8px',
          cursor: 'pointer',
          transition: 'all 0.15s',
          opacity: saveStatus === 'saving' || saveStatus === 'draft-saving' ? 0.5 : 1,
        }}
        onMouseEnter={(e) => { e.currentTarget.style.background = '#e5e7eb'; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = '#f3f4f6'; }}
        title="Save as draft (not published)"
      >
        {/* Draft icon */}
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
          <polyline points="14 2 14 8 20 8" />
        </svg>
        Draft
      </button>

      {/* Save / Publish Button */}
      <button
        onClick={() => onSave(appState.data)}
        disabled={saveStatus === 'saving' || saveStatus === 'draft-saving'}
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: '5px',
          padding: '6px 14px',
          fontSize: '13px',
          fontWeight: 600,
          color: '#fff',
          background: '#2563eb',
          border: 'none',
          borderRadius: '8px',
          cursor: 'pointer',
          transition: 'all 0.15s',
          opacity: saveStatus === 'saving' ? 0.5 : 1,
        }}
        onMouseEnter={(e) => { e.currentTarget.style.background = '#1d4ed8'; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = '#2563eb'; }}
        title="Publish changes live"
      >
        {/* Save icon */}
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" 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>
        Publish
      </button>
    </div>
  );
}


// ─── Main Editor ──────────────────────────────────────────────────────────────

export default function EditorClient({ initialData, categories, navigationItems, pages, currentPath }: EditorClientProps) {
  const router = useRouter();
  const [saveStatus, setSaveStatus] = useState('idle');
  const autoSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const latestDataRef = useRef<Data | null>(null);
  const isSavingRef = useRef(false);

  // Shared save function
  const saveToDB = useCallback(async (data: Data, mode: 'publish' | 'draft' | 'auto') => {
    if (isSavingRef.current) return; // Prevent overlapping saves
    isSavingRef.current = true;

    const statusPrefix = mode === 'publish' ? 'saving' : mode === 'draft' ? 'draft-saving' : 'auto-saving';
    setSaveStatus(statusPrefix);

    try {
      const res = await fetch('/api/homepage-content', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          content: data,
          mode, // 'publish' | 'draft' | 'auto'
          path: currentPath,
        }),
      });

      if (!res.ok) throw new Error('Save failed');

      const doneStatus = mode === 'publish' ? 'saved' : mode === 'draft' ? 'draft-saved' : 'auto-saved';
      setSaveStatus(doneStatus);
      router.refresh();
      setTimeout(() => setSaveStatus('idle'), mode === 'auto' ? 2000 : 3000);
    } catch {
      setSaveStatus('error');
      setTimeout(() => setSaveStatus('idle'), 4000);
    } finally {
      isSavingRef.current = false;
    }
  }, []);

  // Publish handler
  const handlePublish = useCallback((data: Data) => {
    // Cancel any pending auto-save
    if (autoSaveTimerRef.current) {
      clearTimeout(autoSaveTimerRef.current);
      autoSaveTimerRef.current = null;
    }
    saveToDB(data, 'publish');
  }, [saveToDB]);

  // Draft handler
  const handleDraft = useCallback((data: Data) => {
    if (autoSaveTimerRef.current) {
      clearTimeout(autoSaveTimerRef.current);
      autoSaveTimerRef.current = null;
    }
    saveToDB(data, 'draft');
  }, [saveToDB]);

  // Track if user has actually interacted
  const hasUserEditedRef = useRef(false);
  const changeCountRef = useRef(0);

  // Auto-save on change (1 second debounce) — skip the first change (initial load)
  const handleChange = useCallback((data: Data) => {
    changeCountRef.current += 1;
    latestDataRef.current = data;

    // Skip auto-save for the first 2 change events (Puck fires onChange on mount)
    if (changeCountRef.current <= 2) return;
    hasUserEditedRef.current = true;

    // Clear previous timer
    if (autoSaveTimerRef.current) {
      clearTimeout(autoSaveTimerRef.current);
    }

    // Set new 1-second debounce timer
    autoSaveTimerRef.current = setTimeout(() => {
      if (latestDataRef.current && !isSavingRef.current && hasUserEditedRef.current) {
        saveToDB(latestDataRef.current, 'auto');
      }
    }, 1000);
  }, [saveToDB]);

  // Cleanup timer on unmount
  useEffect(() => {
    return () => {
      if (autoSaveTimerRef.current) {
        clearTimeout(autoSaveTimerRef.current);
      }
    };
  }, []);

  // Convert initial data to Puck format safely
  const puckData: Partial<Data> = initialData?.puckData ? JSON.parse(JSON.stringify(initialData.puckData)) : {
    content: [],
    root: { props: {} },
    zones: {},
  };

  if (puckData.content) {
    if (!puckData.content.some((b: any) => b.type === 'SiteHeader')) {
      puckData.content.unshift({
        type: 'SiteHeader',
        props: { id: 'SiteHeader-default', logo: '/logo.png', favicon: '/favicon.png' },
      });
    }

    if (currentPath !== '/' && puckData.content.length === 1) {
      puckData.content.push({
        type: 'Spacer',
        props: { id: 'Spacer-blank-placeholder', height: 500 },
      });
    }

    if (!puckData.content.some((b: any) => b.type === 'SiteFooter')) {
      puckData.content.push({
        type: 'SiteFooter',
        props: {
          id: 'SiteFooter-default',
          leftDescription: '日本発のゲーム攻略メディア「ten-sura-game.com」。メギド72の攻略情報、キャラクター評価、リセマラ情報など、プレイヤーに役立つ情報を分かりやすくお届けします。',
          copyrightText: '© 2026 ten-sura-game.com. All rights reserved.',
        },
      });
    }
  }

  // Inject categories into root props for CanvasHeader/Footer
  puckData.root = {
    ...puckData.root,
    props: {
      ...puckData.root?.props,
      _categories: categories,
      _navigationItems: navigationItems,
      isEditor: true,
    } as any
  };

  return (
    <>
      {/* Inject spin animation and hide site header/footer, fix editor text visibility */}
      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
        body > header, body > footer {
          display: none !important;
        }
        div[data-puck-node-type="SiteHeader"],
        div[data-puck-node-type="SiteFooter"] {
          display: none !important;
        }
        div:has(> .hidden-global-block) {
          display: none !important;
        }
        /* Reset body styles for the editor UI */
        body {
          color: #ffffff !important;
          background: #0F0F12 !important;
        }
        /* Puck sidebar and panels need dark text */
        [class*="Puck-"] , [class*="puck-"] {
          color: #1f2937;
        }
        /* Keep the preview iframe/area with dark background for the site theme */
        [class*="PuckPreview"], [class*="puck-preview"] {
          color: inherit;
        }
      `}</style>

      <div className="puck-editor-wrapper" style={{ height: '100vh' }}>
        <Puck
          config={puckConfig}
          data={puckData}
          onChange={handleChange}
          onPublish={handlePublish}
          headerTitle="Homepage Editor"
          iframe={{ enabled: true }}
          overrides={{
            iframe: ({ children }) => (
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                {/* REQUIRED: Inject prose-article styles into the blank iframe document */}
                <style>{`
                  .prose-article h1 { font-size: 2.25rem !important; font-weight: 700 !important; line-height: 1.3; margin-top: 2.5rem; margin-bottom: 1.25rem; }
                  .prose-article h2 { font-size: 1.875rem !important; font-weight: 700 !important; line-height: 1.3; margin-top: 2rem; margin-bottom: 1rem; }
                  .prose-article h3 { font-size: 1.5rem !important; font-weight: 600 !important; line-height: 1.4; margin-top: 1.5rem; margin-bottom: 0.75rem; }
                  .prose-article h4 { font-size: 1.25rem !important; font-weight: 600 !important; line-height: 1.4; margin-top: 1.25rem; margin-bottom: 0.5rem; }
                  .prose-article p { margin-bottom: 1.25rem; line-height: 1.8; }
                  .prose-article strong, .prose-article b { font-weight: 700 !important; }
                  .prose-article ul { list-style-type: disc; padding-left: 1.5rem; margin-bottom: 1rem; }
                  .prose-article ol { list-style-type: decimal; padding-left: 1.5rem; margin-bottom: 1rem; }
                  .prose-article li { margin-bottom: 0.25rem; line-height: 1.7; }
                  .prose-article a { color: #3B82F6; text-decoration: underline; }
                  .prose-article code { background: #f3f4f6; padding: 0.125rem 0.375rem; border-radius: 4px; font-size: 0.875em; }
                  .prose-article pre { background: #1f2937; color: #f9fafb; padding: 1rem; border-radius: 8px; overflow-x: auto; margin-bottom: 1rem; }
                  
                  /* Hide SiteHeader and SiteFooter blocks in the iframe */
                  div[data-puck-node-type="SiteHeader"],
                  div[data-puck-node-type="SiteFooter"] {
                    display: none !important;
                  }
                  div:has(> .hidden-global-block) {
                    display: none !important;
                  }
                `}</style>
                {children}
              </div>
            ),
            headerActions: () => (
              <HeaderActions
                saveStatus={saveStatus}
                onSave={handlePublish}
                onDraft={handleDraft}
                pages={pages}
                currentPath={currentPath}
                onPageChange={(newPath) => {
                  window.location.href = `/page_editor_admin?path=${newPath}`;
                }}
              />
            ),
          }}
        />
      </div>
    </>
  );
}
