/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React from 'react';
import { 
  Undo2, Redo2, Type, Bold, Italic, Underline, Palette, 
  Highlighter, Strikethrough, Eraser, Subscript, Superscript, Paintbrush 
} from 'lucide-react';

interface FontControlsProps {
  fontFamily: string;
  setFontFamily: (val: string) => void;
  fontSize: string;
  setFontSize: (val: string) => void;
  textColor: string;
  setTextColor: (val: string) => void;
  isFormatPainterActive: boolean;
  onCopyFormat: () => void;
  execCommand: (command: string, arg?: string) => void;
  activeFormats: any;
  editorRef: React.RefObject<HTMLDivElement | null>;
}

export default function FontControls({
  fontFamily,
  setFontFamily,
  fontSize,
  setFontSize,
  textColor,
  setTextColor,
  isFormatPainterActive,
  onCopyFormat,
  execCommand,
  activeFormats,
  editorRef
}: FontControlsProps) {
  const getActiveFontFamily = () => {
    const active = (activeFormats?.fontFamily || '').toLowerCase().replace(/['"]/g, '');
    if (active.includes('times')) return "'Times New Roman', Times, serif";
    if (active.includes('arial')) return "Arial, Helvetica, sans-serif";
    if (active.includes('georgia')) return "Georgia, serif";
    if (active.includes('courier')) return "'Courier New', Courier, monospace";
    return fontFamily;
  };

  const getActiveFontSize = () => {
    const active = activeFormats?.fontSize;
    if (!active) return fontSize;
    const pxMatch = active.match(/^([\d.]+)(px)$/);
    if (pxMatch) {
      const pxVal = parseFloat(pxMatch[1]);
      if (pxVal <= 12) return '9pt';
      if (pxVal <= 13.5) return '10pt';
      if (pxVal <= 15) return '11pt';
      if (pxVal <= 16.5) return '12pt';
      if (pxVal <= 19) return '14pt';
      if (pxVal <= 21.5) return '16pt';
      if (pxVal <= 24.5) return '18pt';
      if (pxVal <= 27) return '20pt';
      if (pxVal <= 32.5) return '24pt';
      if (pxVal <= 38) return '28pt';
      if (pxVal <= 49) return '36pt';
      return '48pt';
    }
    return active;
  };

  return (
    <>
      {/* Undo/Redo & Format Painter */}
      <div className="flex items-center space-x-1 border-r border-slate-300 pr-2">
        <button
          type="button"
          id="editor-tb-undo"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => execCommand('undo')}
          className="p-1.5 text-slate-600 hover:bg-slate-200 rounded transition-colors cursor-pointer"
          title="Batalkan (Undo)"
        >
          <Undo2 className="w-4 h-4" />
        </button>
        <button
          type="button"
          id="editor-tb-redo"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => execCommand('redo')}
          className="p-1.5 text-slate-600 hover:bg-slate-200 rounded transition-colors cursor-pointer"
          title="Ulangi (Redo)"
        >
          <Redo2 className="w-4 h-4" />
        </button>
        <button
          type="button"
          id="editor-tb-formatpainter"
          onMouseDown={(e) => e.preventDefault()}
          onClick={onCopyFormat}
          className={`p-1.5 rounded transition-colors cursor-pointer ${
            isFormatPainterActive
              ? 'bg-amber-100 text-amber-700 border border-amber-300 animate-pulse font-bold'
              : 'text-slate-700 hover:bg-slate-200 border border-transparent'
          }`}
          title="Sapu Format (Salin gaya dari teks yang dipilih lalu klik teks tujuan)"
        >
          <Paintbrush className="w-4 h-4" />
        </button>
      </div>

      {/* Font Family & Font Size */}
      <div className="flex items-center space-x-1 border-r border-slate-300 pr-2">
        <span className="text-xs text-slate-400 mr-1 flex items-center">
          <Type className="w-3.5 h-3.5 mr-0.5" /> Font
        </span>
        <select
          id="editor-tb-fontfamily"
          value={getActiveFontFamily()}
          onChange={(e) => {
            const val = e.target.value;
            const selection = window.getSelection();
            if (selection && !selection.isCollapsed && selection.toString().trim().length > 0) {
              execCommand('fontFamilyCustom', val);
            } else {
              setFontFamily(val);
              if (editorRef.current) {
                editorRef.current.style.fontFamily = val;
              }
            }
          }}
          className="text-xs text-slate-700 bg-white border border-slate-300 rounded px-2 py-1 max-w-[130px] focus:outline-none focus:border-blue-500 cursor-pointer font-medium"
        >
          <option value="'Times New Roman', Times, serif">Times New Roman</option>
          <option value="Arial, Helvetica, sans-serif">Arial (Modern)</option>
          <option value="Georgia, serif">Georgia</option>
          <option value="'Courier New', Courier, monospace">Courier (Ketik)</option>
        </select>

        <select
          id="editor-tb-fontsize"
          value={getActiveFontSize()}
          onChange={(e) => {
            const val = e.target.value;
            setFontSize(val);
            execCommand('fontSizeCustom', val);
          }}
          className="text-xs font-semibold text-slate-700 bg-white border border-slate-300 rounded px-1.5 py-1 focus:outline-none focus:border-blue-500 cursor-pointer ml-1"
          title="Ukuran Font (Default Dokumen ATAU Berlaku ke Seleksi Teks)"
        >
          <option value="9pt">9 pt</option>
          <option value="10pt">10 pt</option>
          <option value="11pt">11 pt</option>
          <option value="12pt">12 pt (Standar)</option>
          <option value="14pt">14 pt</option>
          <option value="16pt">16 pt</option>
          <option value="18pt">18 pt</option>
          <option value="20pt">20 pt</option>
          <option value="24pt">24 pt</option>
          <option value="28pt">28 pt</option>
          <option value="36pt">36 pt</option>
          <option value="48pt">48 pt</option>
        </select>
      </div>

      {/* Basic Text Formats */}
      <div className="flex items-center space-x-1.5 border-r border-slate-300 pr-2">
        <button
          type="button"
          id="editor-tb-bold"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => execCommand('bold')}
          className={`p-1.5 rounded transition-colors cursor-pointer ${
            activeFormats?.bold
              ? 'bg-blue-100 text-blue-700 border border-blue-200 font-extrabold shadow-xs'
              : 'text-slate-700 hover:bg-slate-200 border border-transparent'
          }`}
          title="Tebal (Bold) - Ctrl+B"
        >
          <Bold className="w-4 h-4" />
        </button>
        <button
          type="button"
          id="editor-tb-italic"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => execCommand('italic')}
          className={`p-1.5 rounded transition-colors cursor-pointer ${
            activeFormats?.italic
              ? 'bg-blue-100 text-blue-700 border border-blue-200 font-extrabold shadow-xs'
              : 'text-slate-700 hover:bg-slate-200 border border-transparent'
          }`}
          title="Miring (Italic) - Ctrl+I"
        >
          <Italic className="w-4 h-4" />
        </button>
        <button
          type="button"
          id="editor-tb-underline"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => execCommand('underline')}
          className={`p-1.5 rounded transition-colors cursor-pointer ${
            activeFormats?.underline
              ? 'bg-blue-100 text-blue-700 border border-blue-200 font-extrabold shadow-xs'
              : 'text-slate-700 hover:bg-slate-200 border border-transparent'
          }`}
          title="Garis Bawah (Underline) - Ctrl+U"
        >
          <Underline className="w-4 h-4" />
        </button>
        <button
          type="button"
          id="editor-tb-strikethrough"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => execCommand('strikeThrough')}
          className={`p-1.5 rounded transition-colors cursor-pointer ${
            activeFormats?.strikeThrough
              ? 'bg-blue-100 text-blue-700 border border-blue-200 shadow-xs'
              : 'text-slate-700 hover:bg-slate-200 border border-transparent'
          }`}
          title="Coret Kata (Strikethrough)"
        >
          <Strikethrough className="w-4 h-4" />
        </button>
        <button
          type="button"
          id="editor-tb-subscript"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => execCommand('subscript')}
          className={`p-1.5 rounded transition-colors cursor-pointer ${
            activeFormats?.subscript
              ? 'bg-blue-100 text-blue-700 border border-blue-200 shadow-xs'
              : 'text-slate-700 hover:bg-slate-200 border border-transparent'
          }`}
          title="Subskrip (Teks Bawah)"
        >
          <Subscript className="w-4 h-4" />
        </button>
        <button
          type="button"
          id="editor-tb-superscript"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => execCommand('superscript')}
          className={`p-1.5 rounded transition-colors cursor-pointer ${
            activeFormats?.superscript
              ? 'bg-blue-100 text-blue-700 border border-blue-200 shadow-xs'
              : 'text-slate-700 hover:bg-slate-200 border border-transparent'
          }`}
          title="Superskrip (Teks Atas)"
        >
          <Superscript className="w-4 h-4" />
        </button>
        <button
          type="button"
          id="editor-tb-clearformat"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => execCommand('removeFormat')}
          className="p-1.5 text-red-550 hover:bg-red-50 rounded border border-transparent hover:border-red-200 transition-colors cursor-pointer ml-1"
          title="Bersihkan Format Teks Terpilih (Eraser)"
        >
          <Eraser className="w-4 h-4" />
        </button>
      </div>

      {/* Colors (Text Color & Stabilo) */}
      <div className="flex items-center space-x-2 border-r border-slate-300 pr-2">
        <span className="text-xs text-slate-400 flex items-center">
          <Palette className="w-3.5 h-3.5 mr-0.5" /> Warna
        </span>
        <input
          type="color"
          id="editor-tb-color"
          value={activeFormats?.textColor && activeFormats.textColor !== 'initial' ? activeFormats.textColor : textColor}
          onChange={(e) => {
            setTextColor(e.target.value);
            execCommand('foreColor', e.target.value);
          }}
          title="Warna Teks Utama"
          className="w-5 h-5 cursor-pointer rounded border-0 border-transparent bg-transparent"
        />

        <span className="text-xs text-slate-400 flex items-center ml-2 border-l border-slate-200 pl-2">
          <Highlighter className="w-3.5 h-3.5 mr-0.5 text-slate-500" /> Stabilo
        </span>
        <input
          type="color"
          id="editor-tb-hilitecolor"
          defaultValue="#ffff00"
          onChange={(e) => {
            execCommand('hiliteColor', e.target.value);
          }}
          title="Warna Latar Belakang / Stabilo Seleksi Teks"
          className="w-5 h-5 cursor-pointer rounded border-0 border-transparent bg-transparent"
        />
        <button
          type="button"
          onClick={() => execCommand('hiliteColor', 'transparent')}
          className="p-1 px-1.5 text-slate-400 hover:text-red-500 hover:bg-slate-100 rounded text-[10px] font-bold border border-slate-200 transition-colors"
          title="Hapus Warna Stabilo"
        >
          Hapus
        </button>
      </div>
    </>
  );
}
