import React from 'react';
import { useRichTextEditor } from './use-rich-text-editor';
import { cn } from '../../shared/utils';
import { Button } from '../button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../dropdown-menu';
import { Popover, PopoverContent, PopoverTrigger } from '../popover';
import {
  Bold,
  Italic,
  Underline,
  AlignLeft,
  AlignCenter,
  AlignRight,
  List,
  ListOrdered,
  Type,
  Heading1,
  Heading2,
  Heading3,
  ChevronDown,
  Undo,
  Redo,
  Search,
  ChevronUp,
  X,
  Link as LinkIcon,
} from 'lucide-react';
import { Input } from '../input';

export interface RichTextEditorProps {
  value: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  className?: string;
  actionButton?: React.ReactNode;
  allowSearch?: boolean;
  allowLinks?: boolean;
  allowUndoRedo?: boolean;
  allowHeadings?: boolean;
  allowFormatting?: boolean;
  allowAlignment?: boolean;
  allowLists?: boolean;
  showWordCount?: boolean;
  showCharacterCount?: boolean;
  /** Disables all editing and applies opacity-50. Hides the toolbar. */
  disabled?: boolean;
  /** Makes the editor non-editable while keeping full visual fidelity. Hides the toolbar. */
  readOnly?: boolean;
  /** Called when the editor area receives focus. */
  onFocus?: () => void;
  /** Called when the editor area loses focus. */
  onBlur?: () => void;
  /** Minimum height of the editable area (CSS value, e.g. "200px"). */
  minHeight?: string;
  /** Maximum height of the editable area (CSS value, e.g. "600px"). */
  maxHeight?: string;
}

// ─────────────────────────────────────────────────────────────────────────────
// Component
// ─────────────────────────────────────────────────────────────────────────────
export function RichTextEditor({
  value,
  onChange,
  placeholder,
  className,
  actionButton,
  allowSearch = true,
  allowLinks = true,
  allowUndoRedo = true,
  allowHeadings = true,
  allowFormatting = true,
  allowAlignment = true,
  allowLists = true,
  showWordCount = true,
  showCharacterCount = true,
  disabled = false,
  readOnly = false,
  onFocus,
  onBlur,
  minHeight,
  maxHeight,
}: RichTextEditorProps) {
  const isEditable = !disabled && !readOnly;
  const showToolbar = isEditable;

  const {
    editorRef,
    searchInputRef,
    linkInputRef,
    activeFormats,
    isSearchOpen,
    setIsSearchOpen,
    searchQuery,
    setSearchQuery,
    linkUrl,
    setLinkUrl,
    isLinkOpen,
    hasSavedSelection,
    wordCount,
    characterCount,
    updateActiveFormats,
    execCommand,
    handleInput,
    performSearch,
    handleCreateLink,
    handleUnlink,
    onLinkPopoverOpenChange,
  } = useRichTextEditor({ value, onChange });

  const getCurrentBlockLabel = () => {
    if (activeFormats.h1)
      return (
        <>
          <Heading1 className="w-4 h-4 mr-1 shrink-0" />
          <span className="truncate">Título 1</span>
        </>
      );
    if (activeFormats.h2)
      return (
        <>
          <Heading2 className="w-4 h-4 mr-1 shrink-0" />
          <span className="truncate">Título 2</span>
        </>
      );
    if (activeFormats.h3)
      return (
        <>
          <Heading3 className="w-4 h-4 mr-1 shrink-0" />
          <span className="truncate">Título 3</span>
        </>
      );
    return (
      <>
        <Type className="w-4 h-4 mr-1 shrink-0" />
        <span className="truncate">Parágrafo</span>
      </>
    );
  };

  return (
    <div
      className={cn(
        'flex flex-col h-full w-full bg-background sm:border border-border sm:shadow-sm sm:rounded-lg overflow-hidden',
        disabled && 'opacity-50 pointer-events-none',
        className
      )}
    >
      <style>{`
        [contenteditable]:empty:before {
          content: attr(data-placeholder);
          color: hsl(var(--muted-foreground));
          pointer-events: none;
          display: block;
        }
        .prose-editor ul {
          list-style-type: disc !important;
          padding-left: 1.5rem !important;
          margin-top: 0.5rem !important;
          margin-bottom: 0.5rem !important;
        }
        .prose-editor ol {
          list-style-type: decimal !important;
          padding-left: 1.5rem !important;
          margin-top: 0.5rem !important;
          margin-bottom: 0.5rem !important;
        }
        .prose-editor b, .prose-editor strong {
          font-weight: 600 !important;
        }
        .prose-editor i, .prose-editor em {
          font-style: italic !important;
        }
        .prose-editor u {
          text-decoration: underline !important;
        }
        .prose-editor h1 {
          font-size: 2.25rem !important;
          font-weight: 700 !important;
          margin-bottom: 1.25rem !important;
          line-height: 1.2 !important;
          margin-top: 2rem !important;
          color: hsl(var(--foreground));
        }
        .prose-editor h2 {
          font-size: 1.75rem !important;
          font-weight: 600 !important;
          margin-bottom: 1rem !important;
          margin-top: 1.5rem !important;
          color: hsl(var(--foreground));
        }
        .prose-editor h3 {
          font-size: 1.35rem !important;
          font-weight: 600 !important;
          margin-bottom: 0.75rem !important;
          margin-top: 1.25rem !important;
          color: hsl(var(--foreground));
        }
        .prose-editor p {
          margin-bottom: 1rem !important;
          line-height: 1.6 !important;
        }
        .prose-editor a {
          color: var(--info) !important;
          text-decoration: underline !important;
          cursor: pointer !important;
        }
        .prose-editor h1:first-child, .prose-editor h2:first-child, .prose-editor h3:first-child, .prose-editor p:first-child {
          margin-top: 0 !important;
        }
        .prose-editor {
          outline: none !important;
        }
      `}</style>

      {/* Toolbar — hidden in disabled/readOnly mode */}
      {showToolbar && (
        <div className="px-3 py-2 border-b border-border bg-muted/30 flex items-center gap-1 flex-wrap shrink-0">
          {allowUndoRedo && (
            <>
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-muted-foreground"
                onClick={() => execCommand('undo')}
                title="Desfazer"
                aria-label="Desfazer"
              >
                <Undo className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-muted-foreground"
                onClick={() => execCommand('redo')}
                title="Refazer"
                aria-label="Refazer"
              >
                <Redo className="w-4 h-4" />
              </Button>
              <div className="w-px h-6 bg-border mx-1 hidden sm:block"></div>
            </>
          )}

          {allowHeadings && (
            <>
              <DropdownMenu modal={false}>
                <DropdownMenuTrigger asChild>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-8 gap-0 text-muted-foreground w-[120px] justify-start px-2"
                  >
                    {getCurrentBlockLabel()}
                    <ChevronDown className="w-3 h-3 ml-auto opacity-50 shrink-0" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="start" className="w-[160px]" style={{ zIndex: 9999 }}>
                  <DropdownMenuItem
                    onPointerDown={e => e.preventDefault()}
                    onClick={() => execCommand('formatBlock', 'P')}
                    className="gap-2"
                  >
                    <Type className="w-4 h-4 text-muted-foreground" /> Parágrafo
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onPointerDown={e => e.preventDefault()}
                    onClick={() => execCommand('formatBlock', 'H1')}
                    className="gap-2"
                  >
                    <Heading1 className="w-4 h-4 text-muted-foreground" /> Título 1
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onPointerDown={e => e.preventDefault()}
                    onClick={() => execCommand('formatBlock', 'H2')}
                    className="gap-2"
                  >
                    <Heading2 className="w-4 h-4 text-muted-foreground" /> Título 2
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onPointerDown={e => e.preventDefault()}
                    onClick={() => execCommand('formatBlock', 'H3')}
                    className="gap-2"
                  >
                    <Heading3 className="w-4 h-4 text-muted-foreground" /> Título 3
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
              <div className="w-px h-6 bg-border mx-1 hidden sm:block"></div>
            </>
          )}

          {allowFormatting && (
            <>
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'h-8 w-8 text-muted-foreground',
                  activeFormats.bold && 'bg-muted text-foreground'
                )}
                onClick={() => execCommand('bold')}
                title="Negrito"
                aria-label="Negrito"
              >
                <Bold className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'h-8 w-8 text-muted-foreground',
                  activeFormats.italic && 'bg-muted text-foreground'
                )}
                onClick={() => execCommand('italic')}
                title="Itálico"
                aria-label="Itálico"
              >
                <Italic className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'h-8 w-8 text-muted-foreground',
                  activeFormats.underline && 'bg-muted text-foreground'
                )}
                onClick={() => execCommand('underline')}
                title="Sublinhado"
                aria-label="Sublinhado"
              >
                <Underline className="w-4 h-4" />
              </Button>
              <div className="w-px h-6 bg-border mx-1 hidden sm:block"></div>
            </>
          )}

          {allowAlignment && (
            <>
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'h-8 w-8 text-muted-foreground',
                  activeFormats.justifyLeft && 'bg-muted text-foreground'
                )}
                onClick={() => execCommand('justifyLeft')}
                title="Alinhar à esquerda"
                aria-label="Alinhar à esquerda"
              >
                <AlignLeft className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'h-8 w-8 text-muted-foreground',
                  activeFormats.justifyCenter && 'bg-muted text-foreground'
                )}
                onClick={() => execCommand('justifyCenter')}
                title="Centralizar"
                aria-label="Centralizar"
              >
                <AlignCenter className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'h-8 w-8 text-muted-foreground',
                  activeFormats.justifyRight && 'bg-muted text-foreground'
                )}
                onClick={() => execCommand('justifyRight')}
                title="Alinhar à direita"
                aria-label="Alinhar à direita"
              >
                <AlignRight className="w-4 h-4" />
              </Button>
              <div className="w-px h-6 bg-border mx-1 hidden sm:block"></div>
            </>
          )}

          {allowLists && (
            <>
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'h-8 w-8 text-muted-foreground',
                  activeFormats.insertUnorderedList && 'bg-muted text-foreground'
                )}
                onClick={() => execCommand('insertUnorderedList')}
                title="Lista com marcadores"
                aria-label="Lista com marcadores"
              >
                <List className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className={cn(
                  'h-8 w-8 text-muted-foreground',
                  activeFormats.insertOrderedList && 'bg-muted text-foreground'
                )}
                onClick={() => execCommand('insertOrderedList')}
                title="Lista numerada"
                aria-label="Lista numerada"
              >
                <ListOrdered className="w-4 h-4" />
              </Button>
              <div className="w-px h-6 bg-border mx-1 hidden sm:block"></div>
            </>
          )}

          {allowLinks && (
            <>
              <Popover open={isLinkOpen} onOpenChange={onLinkPopoverOpenChange} modal={false}>
                <PopoverTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    className={cn(
                      'h-8 w-8 text-muted-foreground',
                      (activeFormats.link || isLinkOpen) && 'bg-muted text-foreground'
                    )}
                    title="Inserir link"
                    aria-label="Inserir link"
                  >
                    <LinkIcon className="w-4 h-4" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-80 p-3" align="start" style={{ zIndex: 9999 }}>
                  {!activeFormats.link && !hasSavedSelection ? (
                    <p className="text-xs text-muted-foreground py-1">
                      Selecione um texto para criar um link.
                    </p>
                  ) : (
                    <div className="flex flex-col gap-2">
                      <div className="text-xs font-medium">
                        {activeFormats.link ? 'Editar Link' : 'Inserir Link'}
                      </div>
                      <div className="flex gap-2">
                        <Input
                          ref={linkInputRef}
                          placeholder="https://..."
                          value={linkUrl}
                          onChange={e => setLinkUrl(e.target.value)}
                          onKeyDown={e => {
                            if (e.key === 'Enter') {
                              e.preventDefault();
                              e.stopPropagation();
                              handleCreateLink();
                            }
                          }}
                          className="h-8 text-xs"
                        />
                        <Button size="sm" className="h-8" onClick={handleCreateLink}>
                          Aplicar
                        </Button>
                      </div>
                    </div>
                  )}
                </PopoverContent>
              </Popover>

              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-muted-foreground"
                onClick={handleUnlink}
                title="Remover link"
                aria-label="Remover link"
              >
                <X className="w-4 h-4" />
              </Button>

              <div className="w-px h-6 bg-border mx-1 hidden sm:block"></div>
            </>
          )}

          {(allowFormatting || allowHeadings || allowAlignment || allowLists || allowLinks) && (
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 text-muted-foreground"
              onClick={() => execCommand('removeFormat')}
              title="Limpar formatação"
              aria-label="Limpar formatação"
            >
              <Type className="w-4 h-4" />
            </Button>
          )}

          {allowSearch && (
            <Button
              variant="ghost"
              size="icon"
              className={cn(
                'h-8 w-8 text-muted-foreground',
                isSearchOpen && 'bg-muted text-foreground'
              )}
              onClick={() => {
                setIsSearchOpen(!isSearchOpen);
                if (!isSearchOpen) setTimeout(() => searchInputRef.current?.focus(), 100);
              }}
              title="Buscar"
              aria-label="Buscar"
            >
              <Search className="w-4 h-4" />
            </Button>
          )}

          {actionButton && (
            <>
              <div className="flex-1"></div>
              {actionButton}
            </>
          )}
        </div>
      )}

      {/* Search Bar */}
      {isSearchOpen && (
        <div className="px-3 py-1.5 border-b border-border bg-muted/20 flex items-center gap-2">
          <div className="relative flex-1 max-w-sm">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
            <Input
              ref={searchInputRef}
              placeholder="Buscar no texto..."
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              onKeyDown={e => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  performSearch(searchQuery, e.shiftKey);
                }
                if (e.key === 'Escape') {
                  setIsSearchOpen(false);
                }
              }}
              className="h-8 pl-8 text-xs bg-background"
            />
          </div>
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="icon"
              className="h-7 w-7"
              onMouseDown={e => e.preventDefault()}
              onClick={() => performSearch(searchQuery, true)}
              title="Anterior"
            >
              <ChevronUp className="w-4 h-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              className="h-7 w-7"
              onMouseDown={e => e.preventDefault()}
              onClick={() => performSearch(searchQuery, false)}
              title="Próximo"
            >
              <ChevronDown className="w-4 h-4" />
            </Button>
            <div className="w-px h-4 bg-border mx-1"></div>
            <Button
              variant="ghost"
              size="icon"
              className="h-7 w-7 text-muted-foreground hover:text-foreground"
              onClick={() => setIsSearchOpen(false)}
              title="Fechar busca"
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
          <div className="hidden sm:block text-[10px] text-muted-foreground ml-auto uppercase tracking-wider font-medium">
            Pressione Enter para buscar
          </div>
        </div>
      )}

      {/* Editable Area */}
      <div
        className="flex-1 overflow-y-auto p-4 sm:p-8 bg-background scrollbar-thin"
        style={{ minHeight, maxHeight }}
      >
        <div
          ref={editorRef}
          contentEditable={isEditable}
          role="textbox"
          aria-multiline="true"
          aria-label={placeholder || 'Editor de texto'}
          aria-readonly={readOnly}
          aria-disabled={disabled}
          onInput={handleInput}
          onSelect={isEditable ? updateActiveFormats : undefined}
          onFocus={() => {
            updateActiveFormats();
            onFocus?.();
          }}
          onBlur={onBlur}
          className="prose-editor min-h-full max-w-none focus:outline-none"
          data-placeholder={placeholder}
        />
      </div>

      {/* Footer / Status Bar */}
      {(showWordCount || showCharacterCount) && (
        <div className="px-4 py-2 border-t border-border bg-muted/20 flex items-center justify-between">
          <div className="text-[10px] sm:text-xs text-muted-foreground font-medium uppercase tracking-wider flex items-center gap-2">
            {showWordCount && (
              <span>
                {wordCount} {wordCount === 1 ? 'palavra' : 'palavras'}
              </span>
            )}
            {showWordCount && showCharacterCount && (
              <span className="text-muted-foreground">•</span>
            )}
            {showCharacterCount && (
              <span>
                {characterCount} {characterCount === 1 ? 'caractere' : 'caracteres'}
              </span>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
