"use client";

import React, { useEffect, useState } from 'react';
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Placeholder from '@tiptap/extension-placeholder';
import Link from '@tiptap/extension-link';
import Image from '@tiptap/extension-image';
import Mention from '@tiptap/extension-mention';
import {
  Bold,
  Italic,
  Underline,
  Strikethrough,
  Code,
  Heading1,
  Heading2,
  Heading3,
  List,
  ListOrdered,
  Quote,
  Undo,
  Redo,
  Link as LinkIcon,
  Image as ImageIcon,
  AtSign
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { LinkModal } from '@/components/ui/link-modal';
import { ImageModal } from '@/components/ui/image-modal';
import { cn } from '@/lib/utils';

interface RichTextEditorProps {
  content?: string;
  onChange: (content: string) => void;
  placeholder?: string;
  className?: string;
  editable?: boolean;
  minimal?: boolean;
  members?: Array<{
    id: string;
    name: string;
    email?: string;
    image?: string;
  }>;
  workspaceId?: string;
}

interface MentionSuggestion {
  id: string;
  name: string;
  email?: string;
  image?: string;
}

export const RichTextEditor = ({
  content,
  onChange,
  placeholder = "Start typing...",
  className,
  editable = true,
  minimal = false,
  members = []
}: RichTextEditorProps) => {
  const [showLinkModal, setShowLinkModal] = useState(false);
  const [showImageModal, setShowImageModal] = useState(false);
  const [mentionSuggestions, setMentionSuggestions] = useState<MentionSuggestion[]>([]);
  const [mentionPosition, setMentionPosition] = useState<{ top: number; left: number } | null>(null);
  const [selectedMentionIndex, setSelectedMentionIndex] = useState(0);
  const [mentionCommand, setMentionCommand] = useState<((props: { id: string; label: string }) => void) | null>(null);

  const editor = useEditor({
    extensions: [
      StarterKit.configure({
        bulletList: {
          keepMarks: true,
          keepAttributes: false,
        },
        orderedList: {
          keepMarks: true,
          keepAttributes: false,
        },
      }),
      Placeholder.configure({
        placeholder,
      }),
      Link.configure({
        openOnClick: false,
        HTMLAttributes: {
          class: 'text-blue-500 underline',
        },
      }),
      Image.configure({
        HTMLAttributes: {
          class: 'max-w-full h-auto rounded-lg',
        },
      }),
      Mention.configure({
        HTMLAttributes: {
          class: 'mention bg-blue-100 text-blue-800 px-1 py-0.5 rounded text-sm font-medium cursor-pointer',
        },
        renderHTML({ options, node }) {
          return [
            'span',
            {
              ...options.HTMLAttributes,
              'data-id': node.attrs.id,
              'data-label': node.attrs.label,
            },
            `@${node.attrs.label}`,
          ];
        },
        suggestion: {
          items: ({ query }: { query: string }) => {
            return members
              .filter(member =>
                member.name.toLowerCase().includes(query.toLowerCase()) ||
                (member.email && member.email.toLowerCase().includes(query.toLowerCase()))
              )
              .slice(0, 10);
          },
          render: () => {
            return {
              onStart: (props: any) => {
                setMentionSuggestions(props.items);
                setSelectedMentionIndex(0);
                setMentionCommand(() => props.command);

                // Get cursor position relative to editor
                if (props.clientRect) {
                  const rect = props.clientRect();
                  if (rect) {
                    const editorElement = document.querySelector('.ProseMirror');
                    if (editorElement) {
                      const editorRect = editorElement.getBoundingClientRect();
                      setMentionPosition({
                        top: rect.bottom - editorRect.top + 5,
                        left: rect.left - editorRect.left,
                      });
                    }
                  }
                }
              },

              onUpdate: (props: any) => {
                setMentionSuggestions(props.items);
                setSelectedMentionIndex(0);
                setMentionCommand(() => props.command);

                if (props.clientRect) {
                  const rect = props.clientRect();
                  if (rect) {
                    const editorElement = document.querySelector('.ProseMirror');
                    if (editorElement) {
                      const editorRect = editorElement.getBoundingClientRect();
                      setMentionPosition({
                        top: rect.bottom - editorRect.top + 5,
                        left: rect.left - editorRect.left,
                      });
                    }
                  }
                }
              },

              onKeyDown: (props: any) => {
                if (props.event.key === 'Escape') {
                  setMentionSuggestions([]);
                  setMentionPosition(null);
                  return true;
                }

                if (props.event.key === 'ArrowUp') {
                  setSelectedMentionIndex(prev =>
                    prev <= 0 ? mentionSuggestions.length - 1 : prev - 1
                  );
                  return true;
                }

                if (props.event.key === 'ArrowDown') {
                  setSelectedMentionIndex(prev =>
                    prev >= mentionSuggestions.length - 1 ? 0 : prev + 1
                  );
                  return true;
                }

                if (props.event.key === 'Enter') {
                  const selected = mentionSuggestions[selectedMentionIndex];
                  if (selected && mentionCommand) {
                    mentionCommand({ id: selected.id, label: selected.name });
                  }
                  return true;
                }

                return false;
              },

              onExit: () => {
                setMentionSuggestions([]);
                setMentionPosition(null);
                setMentionCommand(null);
              },
            };
          },
        },
      }),
    ],
    content,
    editable,
    onUpdate: ({ editor }) => {
      onChange(editor.getHTML());
    },
    editorProps: {
      attributes: {
        class: cn(
          'prose prose-sm max-w-none focus:outline-none min-h-[100px] p-3 cursor-text',
          editable ? 'prose-headings:cursor-text prose-p:cursor-text prose-li:cursor-text' : '',
          className
        ),
        spellcheck: 'false',
      },
    },
  });

  // Sync content when prop changes
  useEffect(() => {
    if (editor && content !== editor.getHTML()) {
      editor.commands.setContent(content || '', false);
    }
  }, [editor, content]);

  // Auto-focus when editable (only for new/empty editors)
  useEffect(() => {
    if (editor && editable && !content && !editor.isFocused) {
      const timer = setTimeout(() => {
        try {
          editor.commands.focus('end');
        } catch (error) {
          console.debug('Editor focus failed:', error);
        }
      }, 200);
      return () => clearTimeout(timer);
    }
  }, [editor, editable, content]);

  // Update mention extension when members change
  useEffect(() => {
    if (editor && members.length > 0) {
      // Force update the mention extension with new members
      const mentionExtension = editor.extensionManager.extensions.find(
        (ext) => ext.name === 'mention'
      );
      
      if (mentionExtension) {
        // Update the mention suggestion items function
        mentionExtension.options.suggestion.items = ({ query }: { query: string }) => {
          return members
            .filter(member =>
              member.name.toLowerCase().includes(query.toLowerCase()) ||
              (member.email && member.email.toLowerCase().includes(query.toLowerCase()))
            )
            .slice(0, 10);
        };
      }
    }
  }, [editor, members]);

  const handleMentionSelect = (member: MentionSuggestion, index: number) => {
    if (mentionCommand) {
      mentionCommand({ id: member.id, label: member.name });
    }
  };

  if (!editor) {
    return null;
  }

  const MenuButton = ({
    onClick,
    isActive = false,
    children,
    title
  }: {
    onClick: () => void;
    isActive?: boolean;
    children: React.ReactNode;
    title: string;
  }) => (
    <Button
      variant={isActive ? "secondary" : "ghost"}
      size="sm"
      onClick={onClick}
      title={title}
      className="h-8 w-8 p-1"
    >
      {children}
    </Button>
  );

  const handleAddLink = (url: string, text?: string) => {
    if (text) {
      editor.chain().focus().insertContent(`<a href="${url}">${text}</a>`).run();
    } else {
      editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
    }
  };

  const handleAddImage = (url: string, alt?: string) => {
    editor.chain().focus().setImage({ src: url, alt: alt || '' }).run();
  };

  const handleInsertMention = () => {
    editor.chain().focus().insertContent('@').run();
  };

  if (!editable) {
    return (
      <div className={cn("prose prose-sm max-w-none [&_.ProseMirror]:p-0 [&_.ProseMirror]:m-0 [&_.ProseMirror]:min-h-0 [&_.mention]:no-underline [&_.mention]:hover:bg-blue-200", className)}>
        <EditorContent editor={editor} />
      </div>
    );
  }

  return (
    <div className={cn("border rounded-lg overflow-hidden relative", className)}>
      {!minimal && (
        <div className="border-b bg-gray-50 p-2">
          <div className="flex items-center gap-1 flex-wrap">
            <MenuButton
              onClick={() => editor.chain().focus().toggleBold().run()}
              isActive={editor.isActive('bold')}
              title="Bold"
            >
              <Bold className="h-4 w-4" />
            </MenuButton>

            <MenuButton
              onClick={() => editor.chain().focus().toggleItalic().run()}
              isActive={editor.isActive('italic')}
              title="Italic"
            >
              <Italic className="h-4 w-4" />
            </MenuButton>

            <MenuButton
              onClick={() => editor.chain().focus().toggleStrike().run()}
              isActive={editor.isActive('strike')}
              title="Strikethrough"
            >
              <Strikethrough className="h-4 w-4" />
            </MenuButton>

            <MenuButton
              onClick={() => editor.chain().focus().toggleCode().run()}
              isActive={editor.isActive('code')}
              title="Inline Code"
            >
              <Code className="h-4 w-4" />
            </MenuButton>

            <Separator orientation="vertical" className="h-6" />

            <MenuButton
              onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
              isActive={editor.isActive('heading', { level: 1 })}
              title="Heading 1"
            >
              <Heading1 className="h-4 w-4" />
            </MenuButton>

            <MenuButton
              onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
              isActive={editor.isActive('heading', { level: 2 })}
              title="Heading 2"
            >
              <Heading2 className="h-4 w-4" />
            </MenuButton>

            <MenuButton
              onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
              isActive={editor.isActive('heading', { level: 3 })}
              title="Heading 3"
            >
              <Heading3 className="h-4 w-4" />
            </MenuButton>

            <Separator orientation="vertical" className="h-6" />

            <MenuButton
              onClick={() => editor.chain().focus().toggleBulletList().run()}
              isActive={editor.isActive('bulletList')}
              title="Bullet List"
            >
              <List className="h-4 w-4" />
            </MenuButton>

            <MenuButton
              onClick={() => editor.chain().focus().toggleOrderedList().run()}
              isActive={editor.isActive('orderedList')}
              title="Numbered List"
            >
              <ListOrdered className="h-4 w-4" />
            </MenuButton>

            <MenuButton
              onClick={() => editor.chain().focus().toggleBlockquote().run()}
              isActive={editor.isActive('blockquote')}
              title="Quote"
            >
              <Quote className="h-4 w-4" />
            </MenuButton>

            <Separator orientation="vertical" className="h-6" />

            <MenuButton
              onClick={() => setShowLinkModal(true)}
              isActive={editor.isActive('link')}
              title="Add Link"
            >
              <LinkIcon className="h-4 w-4" />
            </MenuButton>

            <MenuButton
              onClick={() => setShowImageModal(true)}
              title="Add Image"
            >
              <ImageIcon className="h-4 w-4" />
            </MenuButton>

            {members.length > 0 && (
              <MenuButton
                onClick={handleInsertMention}
                title="Mention Someone (@)"
              >
                <AtSign className="h-4 w-4" />
              </MenuButton>
            )}

            <Separator orientation="vertical" className="h-6" />

            <MenuButton
              onClick={() => editor.chain().focus().undo().run()}
              title="Undo"
            >
              <Undo className="h-4 w-4" />
            </MenuButton>

            <MenuButton
              onClick={() => editor.chain().focus().redo().run()}
              title="Redo"
            >
              <Redo className="h-4 w-4" />
            </MenuButton>
          </div>
        </div>
      )}

      <div
        onClick={() => {
          if (editable) {
            editor?.commands.focus();
          }
        }}
        className={cn(
          "min-h-[100px] relative",
          editable ? "cursor-text" : "cursor-default"
        )}
      >
        <EditorContent editor={editor} />

        {members.length > 0 && (
          <div className="absolute bottom-2 right-2 text-xs text-gray-400 pointer-events-none">
            Type @ to mention someone
          </div>
        )}
      </div>

      {/* Mention Suggestions Dropdown */}
      {mentionSuggestions.length > 0 && mentionPosition && (
        <div
          className="absolute z-[100] bg-white border border-gray-200 rounded-lg shadow-xl overflow-hidden max-h-60 overflow-y-auto min-w-[240px] max-w-[320px]"
          style={{
            top: `${mentionPosition.top}px`,
            left: `${mentionPosition.left}px`,
          }}
        >
          {mentionSuggestions.map((member, index) => (
            <button
              key={member.id}
              onClick={() => handleMentionSelect(member, index)}
              className={cn(
                "flex items-center gap-3 w-full px-3 py-2 text-left hover:bg-gray-50 transition-colors border-none bg-transparent",
                index === selectedMentionIndex && "bg-blue-50 border-l-2 border-blue-500"
              )}
            >
              <div className="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-sm font-medium text-blue-700 flex-shrink-0">
                {member.name.charAt(0).toUpperCase()}
              </div>
              <div className="flex flex-col min-w-0 flex-1">
                <span className="text-sm font-medium text-gray-900 truncate">
                  {member.name}
                </span>
                {member.email && (
                  <span className="text-xs text-gray-500 truncate">{member.email}</span>
                )}
              </div>
            </button>
          ))}
        </div>
      )}

      <LinkModal
        isOpen={showLinkModal}
        onClose={() => setShowLinkModal(false)}
        onConfirm={handleAddLink}
      />

      <ImageModal
        isOpen={showImageModal}
        onClose={() => setShowImageModal(false)}
        onConfirm={handleAddImage}
      />
    </div>
  );
};