// SPDX-License-Identifier: Apache-2.0
import React, { useRef, useEffect, useState } from 'react';
import { Sparkles, X } from 'lucide-react';
import { HRDocument, HREmployee, HRSigner, ReferenceDatabase } from '../types';
import EditorToolbar from './EditorToolbar';
import VariablesSidebar from './VariablesSidebar';
import EditorModals from './EditorModals';

// Import modular hooks and sub-components
import { useEditorHistory } from './editor/useEditorHistory';
import { useEditorStats } from './editor/useEditorStats';
import { useFormatPainter } from './editor/useFormatPainter';
import { useFindReplace } from './editor/useFindReplace';
import { useEditorCommands } from './editor/useEditorCommands';
import { useEditorSelection } from './editor/useEditorSelection';
import { useDocumentSettings } from './editor/useDocumentSettings';
import RichEditorHeader from './editor/RichEditorHeader';
import RichEditorStatusbar from './editor/RichEditorStatusbar';
import { HorizontalRuler, VerticalRuler } from './editor/RichEditorRulers';
import RichEditorContent from './editor/RichEditorContent';
import RichEditorFindReplace from './editor/RichEditorFindReplace';
import { getReferenceOptionsForKey } from '../utils/documentUtils';

interface RichEditorProps {
  documentData: HRDocument;
  employees?: HREmployee[];
  signers?: HRSigner[];
  databases?: ReferenceDatabase[];
  onSave: (updatedDoc: HRDocument) => void;
  onAutosave?: (updatedDoc: HRDocument) => void;
  onBack: () => void;
}

export default function RichEditor({ 
  documentData, 
  employees = [], 
  signers = [], 
  databases = [],
  onSave, 
  onAutosave,
  onBack 
}: RichEditorProps) {
  const editorRef = useRef<HTMLDivElement>(null);
  
  // 0. Document Settings Hook
  const {
    fontFamily, setFontFamily, fontSize, setFontSize, lineHeight, setLineHeight,
    marginPreset, setMarginPreset, marginTop, setMarginTop, marginBottom, setMarginBottom,
    marginLeft, setMarginLeft, marginRight, setMarginRight, isLetterheadMode, setIsLetterheadMode,
    letterheadHeight, setLetterheadHeight, isIkiLetterhead, setIsIkiLetterhead, showMarginModal, setShowMarginModal,
    paperSize, setPaperSize, textColor, setTextColor, isHtmlMode, setIsHtmlMode,
    showFormattingMarks, setShowFormattingMarks,
    customKopAtas, setCustomKopAtas,
    customKopBawah, setCustomKopBawah,
    showKopModal, setShowKopModal,
    paperWidthCm, leftMarginPercent,
    rightMarginPercent, effectiveTopMargin, effectiveBottomMargin, topMarginPercent, bottomMarginPercent
  } = useDocumentSettings(documentData);

  const [showPreviewMode, setShowPreviewMode] = useState(false);
  const [isRightPaneOpen, setIsRightPaneOpen] = useState(true);

  // 1. History & Autosave Hook
  const {
    title, setTitle, content, setContent, autosaveStatus, setAutosaveStatus,
    editorToast, triggerToast, pushHistory, handleUndo, handleRedo, history, historyIndex
  } = useEditorHistory({ 
    documentData, editorRef, onAutosave, marginPreset, marginTop, marginBottom,
    marginLeft, marginRight, paperSize, fontFamily, fontSize, lineHeight, isLetterheadMode, letterheadHeight, isIkiLetterhead
  });

  // 2. Statistics Hook
  const { stats, updateStats } = useEditorStats({ content, paperSize, editorRef });

  // 3. Commands Hook
  const {
    lastRange, setLastRange, execCommand, cleanEmptyParagraphs, insertHTMLAtCursor,
    showTableModal, setShowTableModal, tableRows, setTableRows, tableCols, setTableCols,
    insertTable, showVariableModal, setShowVariableModal, newVarName, setNewVarName,
    insertVariable, handleInput
  } = useEditorCommands({
    editorRef, content, setContent, pushHistory, handleUndo, handleRedo, history, historyIndex,
    fontFamily, fontSize, setFontSize, lineHeight, setLineHeight, textColor, triggerToast
  });

  // 4. Selection & Shortcuts Hook
  const {
    activeFormats, saveSelection, updateActiveFormats
  } = useEditorSelection({
    editorRef, fontFamily, fontSize, setFontSize, lineHeight, setLineHeight, textColor,
    execCommand, handleUndo, handleRedo, historyIndex, history, lastRange, setLastRange
  });

  // 4. Format Painter Hook
  const {
    copiedFormat,
    isFormatPainterActive,
    setIsFormatPainterActive,
    setCopiedFormat,
    handleCopyFormat,
    applyCopiedFormat
  } = useFormatPainter({
    editorRef,
    execCommand,
    triggerToast
  });

  // 5. Find & Replace Hook
  const {
    showFindReplace,
    setShowFindReplace,
    findQuery,
    setFindQuery,
    replaceQuery,
    setReplaceQuery,
    matchCount,
    handleFindNext,
    handleReplace,
    handleReplaceAll
  } = useFindReplace({ editorRef, triggerToast, setContent, pushHistory });

  // Active formatting state under selection caret




  // Populate editor container initially and when returning from HTML mode, and tag Kop Surat
  useEffect(() => {
    if (!isHtmlMode && editorRef.current) {
      if (editorRef.current.innerHTML !== content) {
        editorRef.current.innerHTML = content;
      }
      const contentRoot = editorRef.current.children[0];
      if (contentRoot && contentRoot.tagName === 'DIV') {
        const firstChild = contentRoot.children[0];
        if (firstChild && firstChild.tagName === 'DIV') {
          if (!firstChild.classList.contains('digital-kop-surat')) {
            firstChild.classList.add('digital-kop-surat');
          }
        }
      }
    }
  }, [isHtmlMode, content]);

  const toggleHtmlMode = () => {
    if (isHtmlMode) {
      setIsHtmlMode(false);
    } else {
      setIsHtmlMode(true);
      setShowPreviewMode(false);
    }
  };

  const getReferenceOptions = (key: string) => {
    return getReferenceOptionsForKey(key, databases, employees, signers);
  };



  return (
    <div className="flex flex-col h-screen overflow-hidden bg-slate-100 flex-1 print:bg-white print:h-auto">


      {editorToast && (
        <div className="fixed top-6 left-1/2 -translate-x-1/2 bg-slate-900 border border-slate-800 text-white px-5 py-2.5 rounded-xl shadow-2xl flex items-center space-x-2.5 transition-all z-50 select-none animate-in fade-in slide-in-from-top-3 duration-200">
          <Sparkles className="w-4 h-4 text-emerald-400 shrink-0 animate-pulse" />
          <p className="text-xs font-bold">{editorToast}</p>
        </div>
      )}

      {/* WINDOW HEADER */}
      <RichEditorHeader
        title={title}
        setTitle={setTitle}
        autosaveStatus={autosaveStatus}
        showPreviewMode={showPreviewMode}
        setShowPreviewMode={setShowPreviewMode}
        isHtmlMode={isHtmlMode}
        toggleHtmlMode={toggleHtmlMode}
        handlePrint={() => window.print()}
        handleSave={() => {
          setAutosaveStatus('saved');
          onSave({ 
            ...documentData, 
            title: title.trim() || 'Surat Tanpa Judul', 
            content, 
            updatedAt: new Date().toISOString(),
            marginPreset,
            marginTop,
            marginBottom,
            marginLeft,
            marginRight,
            paperSize,
            fontFamily,
            fontSize,
            lineHeight,
            isLetterheadMode,
            letterheadHeight,
            isIkiLetterhead
          });
        }}
        onBack={onBack}
      />

      {/* WYSIWYG FORMATTING TOOLBAR */}
      <EditorToolbar 
        showPreviewMode={showPreviewMode}
        isHtmlMode={isHtmlMode}
        fontFamily={fontFamily}
        setFontFamily={setFontFamily}
        fontSize={fontSize}
        setFontSize={setFontSize}
        lineHeight={lineHeight}
        setLineHeight={setLineHeight}
        marginPreset={marginPreset}
        setMarginPreset={setMarginPreset}
        paperSize={paperSize}
        setPaperSize={setPaperSize}
        textColor={textColor}
        setTextColor={setTextColor}
        isRightPaneOpen={isRightPaneOpen}
        setIsRightPaneOpen={setIsRightPaneOpen}
        execCommand={execCommand}
        setShowTableModal={setShowTableModal}
        editorRef={editorRef}
        showFormattingMarks={showFormattingMarks}
        setShowFormattingMarks={setShowFormattingMarks}
        onCleanEmptyParagraphs={cleanEmptyParagraphs}
        activeFormats={activeFormats}
        isFormatPainterActive={isFormatPainterActive}
        onCopyFormat={handleCopyFormat}
        showFindReplace={showFindReplace}
        setShowFindReplace={setShowFindReplace}
        isLetterheadMode={isLetterheadMode}
        setIsLetterheadMode={setIsLetterheadMode}
        isIkiLetterhead={isIkiLetterhead}
        setIsIkiLetterhead={setIsIkiLetterhead}
        setShowMarginModal={setShowMarginModal}
        setShowKopModal={setShowKopModal}
      />

      {/* FIND & REPLACE PANEL */}
      <RichEditorFindReplace
        showFindReplace={showFindReplace}
        showPreviewMode={showPreviewMode}
        isHtmlMode={isHtmlMode}
        findQuery={findQuery}
        setFindQuery={setFindQuery}
        replaceQuery={replaceQuery}
        setReplaceQuery={setReplaceQuery}
        matchCount={matchCount}
        handleFindNext={handleFindNext}
        handleReplace={handleReplace}
        handleReplaceAll={handleReplaceAll}
        setShowFindReplace={setShowFindReplace}
      />

      {/* MAIN DOCUMENT CANVAS AREA */}
      <div className="flex-1 flex flex-row overflow-hidden relative print:overflow-visible print:h-auto">
        <div className="flex-1 overflow-y-auto bg-slate-100 flex flex-col items-center py-6 px-10 print:bg-white print:overflow-visible print:p-0 print:py-0 w-full relative">
          <div 
            className="flex flex-col items-stretch justify-start w-full print:w-full select-none"
            style={{ 
              maxWidth: paperSize === 'A4' ? '210mm' : '215mm',
              boxSizing: 'border-box'
            }}
          >
            {/* DOCUMENT RULER */}
            <HorizontalRuler
              paperSize={paperSize}
              paperWidthCm={paperWidthCm}
              leftMarginPercent={leftMarginPercent}
              rightMarginPercent={rightMarginPercent}
              marginLeft={marginLeft}
              marginRight={marginRight}
              showFindReplace={showFindReplace}
              onDoubleClick={() => setShowMarginModal(true)}
            />

            <div className="relative w-full flex flex-row">
              {/* LEFT VERTICAL RULER */}
              <VerticalRuler
                paperSize={paperSize}
                topMarginPercent={topMarginPercent}
                bottomMarginPercent={bottomMarginPercent}
                effectiveTopMargin={effectiveTopMargin}
                marginBottom={effectiveBottomMargin}
                onDoubleClick={() => setShowMarginModal(true)}
              />
              
              {/* THE PAPER SHEET EDITABLE AREA */}
              <RichEditorContent
                editorRef={editorRef}
                isHtmlMode={isHtmlMode}
                showPreviewMode={showPreviewMode}
                content={content}
                setContent={setContent}
                handleInput={handleInput}
                saveSelection={saveSelection}
                applyCopiedFormat={applyCopiedFormat}
                isLetterheadMode={isLetterheadMode}
                letterheadHeight={letterheadHeight}
                isIkiLetterhead={isIkiLetterhead}
                showFormattingMarks={showFormattingMarks}
                paperSize={paperSize}
                effectiveTopMargin={effectiveTopMargin}
                effectiveBottomMargin={effectiveBottomMargin}
                marginTop={marginTop}
                marginBottom={marginBottom}
                marginLeft={marginLeft}
                marginRight={marginRight}
                fontFamily={fontFamily}
                fontSize={fontSize}
                lineHeight={lineHeight}
                isFormatPainterActive={isFormatPainterActive}
                customKopAtas={customKopAtas}
                customKopBawah={customKopBawah}
                documentData={documentData}
              />
            </div>
          </div>
        </div>

        {/* COMPANION SIDEBAR */}
        <VariablesSidebar 
          isOpen={isRightPaneOpen}
          onClose={() => setIsRightPaneOpen(false)}
          insertHTMLAtCursor={insertHTMLAtCursor}
          getReferenceOptionsForKey={getReferenceOptions}
          databases={databases}
          editorRef={editorRef}
        />
      </div>

      {/* STATUS BAR */}
      <RichEditorStatusbar
        stats={stats}
        isFormatPainterActive={isFormatPainterActive}
      />

      {/* POPUP ACTION MODALS */}
      <EditorModals 
        showTableModal={showTableModal} setShowTableModal={setShowTableModal}
        tableRows={tableRows} setTableRows={setTableRows}
        tableCols={tableCols} setTableCols={setTableCols}
        onInsertTable={insertTable}
        showVariableModal={showVariableModal} setShowVariableModal={setShowVariableModal}
        newVarName={newVarName} setNewVarName={setNewVarName}
        onInsertVariable={insertVariable}
        showMarginModal={showMarginModal} setShowMarginModal={setShowMarginModal}
        marginTop={marginTop} setMarginTop={setMarginTop}
        marginBottom={marginBottom} setMarginBottom={setMarginBottom}
        marginLeft={marginLeft} setMarginLeft={setMarginLeft}
        marginRight={marginRight} setMarginRight={setMarginRight}
        letterheadHeight={letterheadHeight} setLetterheadHeight={setLetterheadHeight}
        onApplyMargins={(top, bottom, left, right, lh) => {
          setMarginTop(top); setMarginBottom(bottom); setMarginLeft(left); setMarginRight(right);
          setLetterheadHeight(lh); setMarginPreset('custom'); setShowMarginModal(false);
        }}
        showKopModal={showKopModal} setShowKopModal={setShowKopModal}
        customKopAtas={customKopAtas} setCustomKopAtas={setCustomKopAtas}
        customKopBawah={customKopBawah} setCustomKopBawah={setCustomKopBawah}
      />
    </div>
  );
}
