'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';

interface EditorClientProps {
  initialData: any;
}

// ─── 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,
}: {
  saveStatus: string;
  onSave: (data: Data) => void;
  onDraft: (data: Data) => void;
}) {
  const { appState } = usePuck();

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
      <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 }: 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'
        }),
      });

      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]);

  // Auto-save on change (1 second debounce)
  const handleChange = useCallback((data: Data) => {
    latestDataRef.current = data;

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

    // Set new 1-second debounce timer
    autoSaveTimerRef.current = setTimeout(() => {
      if (latestDataRef.current && !isSavingRef.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
  const puckData: Partial<Data> = initialData?.puckData || {
    content: [],
    root: { props: {} },
    zones: {},
  };

  return (
    <>
      {/* Inject spin animation and hide site header/footer */}
      <style>{`
        @keyframes spin { to { transform: rotate(360deg); } }
        body > header, body > footer {
          display: none !important;
        }
      `}</style>

      <div className="puck-editor-wrapper" style={{ height: '100vh' }}>
        <Puck
          config={puckConfig}
          data={puckData}
          onChange={handleChange}
          onPublish={handlePublish}
          headerTitle="Homepage Editor"
          overrides={{
            headerActions: () => (
              <HeaderActions
                saveStatus={saveStatus}
                onSave={handlePublish}
                onDraft={handleDraft}
              />
            ),
          }}
        />
      </div>
    </>
  );
}
