'use client';

import { 
  MDXEditor, 
  headingsPlugin, 
  listsPlugin, 
  quotePlugin, 
  thematicBreakPlugin, 
  markdownShortcutPlugin, 
  linkPlugin, 
  linkDialogPlugin, 
  imagePlugin,
  tablePlugin,
  codeBlockPlugin,
  UndoRedo,
  BoldItalicUnderlineToggles,
  toolbarPlugin,
  BlockTypeSelect,
  CreateLink,
  ListsToggle,
  Separator,
  InsertTable,
  InsertThematicBreak,
  CodeToggle,
  InsertImage,
  InsertCodeBlock,
  linkPlugin as linkDialog,
  imagePlugin as imageDialog,
  ConditionalContents,
  InsertFrontmatter,
  ChangeCodeMirrorLanguage,
  codeBlockPlugin as codeBlock,
  ChangeCodeTheme,
  InsertTableWithHeaders,
  markdownSourcePlugin,
  MarkdownSourceToggle,
  DiffSourceToggle,
  SaveButton
} from '@mdxeditor/editor'
import '@mdxeditor/editor/style.css'

interface EnhancedMDXEditorProps {
  value: string;
  onChange: (value: string) => void;
  height?: number;
  placeholder?: string;
}

export function EnhancedMDXEditor({ 
  value, 
  onChange, 
  height = 500, 
  placeholder = "Start typing..." 
}: EnhancedMDXEditorProps) {
  return (
    <div className="border rounded-lg overflow-hidden">
      <MDXEditor
        markdown={value}
        onChange={onChange}
        placeholder={placeholder}
        plugins={[
          headingsPlugin({ 
            allowedHeadingLevels: [1, 2, 3, 4, 5, 6] 
          }),
          listsPlugin(),
          quotePlugin(),
          thematicBreakPlugin(),
          markdownShortcutPlugin(),
          linkPlugin(),
          linkDialogPlugin(),
          imagePlugin({
            imageUploadHandler: async (file) => {
              // Upload file to our API
              const formData = new FormData();
              formData.append('file', file);
              
              try {
                const response = await fetch('/api/upload', {
                  method: 'POST',
                  body: formData,
                });
                
                if (response.ok) {
                  const result = await response.json();
                  return Promise.resolve(result.url);
                } else {
                  console.error('Upload failed:', response.statusText);
                  return Promise.resolve('https://via.placeholder.com/300x200?text=Upload+Failed');
                }
              } catch (error) {
                console.error('Upload error:', error);
                return Promise.resolve('https://via.placeholder.com/300x200?text=Upload+Error');
              }
            }
          }),
          tablePlugin(),
          codeBlockPlugin({ 
            defaultCodeBlockLanguage: 'text' 
          }),
          markdownSourcePlugin({
            diffSource: {
              viewMode: 'rich-text',
              readOnlyDiff: false
            }
          }),
          toolbarPlugin({
            toolbarContents: () => (
              <div className="flex flex-wrap items-center gap-1 p-2 border-b bg-gray-50">
                {/* Undo/Redo */}
                <UndoRedo />
                
                <Separator />
                
                {/* Markdown Source Toggle */}
                <MarkdownSourceToggle />
                <DiffSourceToggle />
                
                <Separator />
                
                {/* Block Type Select */}
                <BlockTypeSelect />
                
                <Separator />
                
                {/* Text Formatting */}
                <BoldItalicUnderlineToggles />
                
                <Separator />
                
                {/* Lists */}
                <ListsToggle />
                
                <Separator />
                
                {/* Link */}
                <CreateLink />
                
                <Separator />
                
                {/* Image */}
                <InsertImage />
                
                <Separator />
                
                {/* Table */}
                <InsertTable />
                <InsertTableWithHeaders />
                
                <Separator />
                
                {/* Code */}
                <CodeToggle />
                <InsertCodeBlock />
                <ChangeCodeMirrorLanguage />
                <ChangeCodeTheme />
                
                <Separator />
                
                {/* Thematic Break */}
                <InsertThematicBreak />
                
                <Separator />
                
                {/* Frontmatter */}
                <InsertFrontmatter />
                
                <Separator />
                
                {/* Save Button */}
                <SaveButton />
              </div>
            )
          })
        ]}
        contentEditableClassName="prose prose-sm max-w-none p-4 min-h-[400px] focus:outline-none font-sans"
        style={{ 
          height: `${height}px`,
          minHeight: '400px'
        }}
      />
    </div>
  );
}