// BACKUP - OLD RICH TEXT EDITOR IMPLEMENTATION
// This was the previous implementation before the advanced Tiptap-based version
// Kept for reference and potential markdown editor features

"use client"

import React from 'react'
import { useSubscription } from '../../hooks/use-subscription'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './card'
import { Button } from './button'
import { 
  Bold, 
  Italic, 
  Underline, 
  AlignLeft, 
  AlignCenter, 
  AlignRight,
  List,
  ListOrdered,
  Quote,
  Link,
  Image,
  Code,
  Undo,
  Redo,
  Type,
  Lock,
  Sparkles
} from 'lucide-react'
import { cn } from '../../lib/utils'

interface OldRichTextEditorProps {
  value?: string
  onChange?: (value: string) => void
  placeholder?: string
  className?: string
  disabled?: boolean
  minHeight?: number
  maxHeight?: number
  showToolbar?: boolean
  readonly?: boolean
  autoFocus?: boolean
  features?: {
    bold?: boolean
    italic?: boolean
    underline?: boolean
    heading?: boolean
    lists?: boolean
    link?: boolean
    image?: boolean
    quote?: boolean
    code?: boolean
    undo?: boolean
    redo?: boolean
    ai?: boolean
  }
  height?: number
}

export function OldRichTextEditor({
  value = '',
  onChange,
  placeholder = 'Start typing...',
  className,
  disabled = false,
  minHeight = 200,
  maxHeight = 600,
  showToolbar = true,
  readonly = false,
  autoFocus = false,
  features = {},
  height
}: OldRichTextEditorProps) {
  const { hasProAccess, isLoading } = useSubscription()
  
  // If no pro access, show upgrade prompt
  if (!isLoading && !hasProAccess) {
    return (
      <Card className={cn("w-full", className)}>
        <CardContent className="py-12 text-center">
          <div className="max-w-md mx-auto space-y-4">
            <div className="rounded-full bg-purple-100 dark:bg-purple-900/30 p-3 w-fit mx-auto">
              <Lock className="h-6 w-6 text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <h3 className="font-semibold text-lg mb-2">Pro Feature</h3>
              <p className="text-muted-foreground text-sm mb-4">
                Rich Text Editor is available exclusively to MoonUI Pro subscribers.
              </p>
              <div className="flex gap-3 justify-center">
                <a href="/pricing">
                  <Button size="sm">
                    <Sparkles className="mr-2 h-4 w-4" />
                    Upgrade to Pro
                  </Button>
                </a>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }
  const [content, setContent] = React.useState(value)
  const [isFormatting, setIsFormatting] = React.useState({
    bold: false,
    italic: false,
    underline: false,
    align: 'left' as 'left' | 'center' | 'right'
  })
  const editorRef = React.useRef<HTMLDivElement>(null)

  React.useEffect(() => {
    setContent(value)
  }, [value])

  React.useEffect(() => {
    if (autoFocus && editorRef.current) {
      editorRef.current.focus()
    }
  }, [autoFocus])

  const handleContentChange = () => {
    if (editorRef.current) {
      const newContent = editorRef.current.innerHTML
      setContent(newContent)
      onChange?.(newContent)
    }
  }

  const execCommand = (command: string, value: string = '') => {
    document.execCommand(command, false, value)
    editorRef.current?.focus()
    handleContentChange()
    updateFormattingState()
  }

  const updateFormattingState = () => {
    setIsFormatting({
      bold: document.queryCommandState('bold'),
      italic: document.queryCommandState('italic'),
      underline: document.queryCommandState('underline'),
      align: document.queryCommandValue('justifyLeft') ? 'left' : 
             document.queryCommandValue('justifyCenter') ? 'center' : 
             document.queryCommandValue('justifyRight') ? 'right' : 'left'
    })
  }

  const handleSelectionChange = () => {
    updateFormattingState()
  }

  React.useEffect(() => {
    document.addEventListener('selectionchange', handleSelectionChange)
    return () => {
      document.removeEventListener('selectionchange', handleSelectionChange)
    }
  }, [])

  const insertLink = () => {
    const url = prompt('Enter URL:')
    if (url) {
      execCommand('createLink', url)
    }
  }

  const insertImage = () => {
    const url = prompt('Enter image URL:')
    if (url) {
      execCommand('insertImage', url)
    }
  }

  const formatText = (command: string) => {
    execCommand(command)
  }

  const alignText = (alignment: 'left' | 'center' | 'right') => {
    const commands = {
      left: 'justifyLeft',
      center: 'justifyCenter',
      right: 'justifyRight'
    }
    execCommand(commands[alignment])
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.ctrlKey || e.metaKey) {
      switch (e.key) {
        case 'b':
          e.preventDefault()
          formatText('bold')
          break
        case 'i':
          e.preventDefault()
          formatText('italic')
          break
        case 'u':
          e.preventDefault()
          formatText('underline')
          break
        case 'z':
          e.preventDefault()
          if (e.shiftKey) {
            execCommand('redo')
          } else {
            execCommand('undo')
          }
          break
      }
    }
  }

  return (
    <Card className={cn("w-full", className)}>
      <CardHeader className="pb-3">
        <CardTitle className="flex items-center gap-2">
          <Type className="h-5 w-5" />
          Rich Text Editor (Old Version)
        </CardTitle>
        <CardDescription>
          Create and edit rich text content with formatting options
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Toolbar */}
        {showToolbar && (
          <div className="flex flex-wrap items-center gap-1 p-2 border rounded-lg bg-muted/50">
            {/* Text Formatting */}
            <div className="flex items-center gap-1">
              {features.bold !== false && (
                <Button
                  variant={isFormatting.bold ? "default" : "ghost"}
                  size="sm"
                  onClick={() => formatText('bold')}
                  disabled={disabled || readonly}
                >
                  <Bold className="h-4 w-4" />
                </Button>
              )}
              {features.italic !== false && (
                <Button
                  variant={isFormatting.italic ? "default" : "ghost"}
                  size="sm"
                  onClick={() => formatText('italic')}
                  disabled={disabled || readonly}
                >
                  <Italic className="h-4 w-4" />
                </Button>
              )}
              {features.underline !== false && (
                <Button
                  variant={isFormatting.underline ? "default" : "ghost"}
                  size="sm"
                  onClick={() => formatText('underline')}
                  disabled={disabled || readonly}
                >
                  <Underline className="h-4 w-4" />
                </Button>
              )}
            </div>

            <div className="h-4 w-px bg-border mx-1" />

            {/* Alignment */}
            <div className="flex items-center gap-1">
              <Button
                variant={isFormatting.align === 'left' ? "default" : "ghost"}
                size="sm"
                onClick={() => alignText('left')}
                disabled={disabled || readonly}
              >
                <AlignLeft className="h-4 w-4" />
              </Button>
              <Button
                variant={isFormatting.align === 'center' ? "default" : "ghost"}
                size="sm"
                onClick={() => alignText('center')}
                disabled={disabled || readonly}
              >
                <AlignCenter className="h-4 w-4" />
              </Button>
              <Button
                variant={isFormatting.align === 'right' ? "default" : "ghost"}
                size="sm"
                onClick={() => alignText('right')}
                disabled={disabled || readonly}
              >
                <AlignRight className="h-4 w-4" />
              </Button>
            </div>

            <div className="h-4 w-px bg-border mx-1" />

            {/* Lists */}
            {features.lists !== false && (
              <div className="flex items-center gap-1">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => execCommand('insertUnorderedList')}
                  disabled={disabled || readonly}
                >
                  <List className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => execCommand('insertOrderedList')}
                  disabled={disabled || readonly}
                >
                  <ListOrdered className="h-4 w-4" />
                </Button>
              </div>
            )}

            <div className="h-4 w-px bg-border mx-1" />

            {/* Quote and Code */}
            <div className="flex items-center gap-1">
              {features.quote !== false && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => execCommand('formatBlock', 'blockquote')}
                  disabled={disabled || readonly}
                >
                  <Quote className="h-4 w-4" />
                </Button>
              )}
              {features.code !== false && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => execCommand('formatBlock', 'pre')}
                  disabled={disabled || readonly}
                >
                  <Code className="h-4 w-4" />
                </Button>
              )}
            </div>

            <div className="h-4 w-px bg-border mx-1" />

            {/* Insert */}
            <div className="flex items-center gap-1">
              {features.link !== false && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={insertLink}
                  disabled={disabled || readonly}
                >
                  <Link className="h-4 w-4" />
                </Button>
              )}
              {features.image !== false && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={insertImage}
                  disabled={disabled || readonly}
                >
                  <Image className="h-4 w-4" />
                </Button>
              )}
            </div>

            <div className="h-4 w-px bg-border mx-1" />

            {/* Undo/Redo */}
            {(features.undo !== false || features.redo !== false) && (
              <div className="flex items-center gap-1">
                {features.undo !== false && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => execCommand('undo')}
                    disabled={disabled || readonly}
                  >
                    <Undo className="h-4 w-4" />
                  </Button>
                )}
                {features.redo !== false && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => execCommand('redo')}
                    disabled={disabled || readonly}
                  >
                    <Redo className="h-4 w-4" />
                  </Button>
                )}
              </div>
            )}
          </div>
        )}

        {/* Editor */}
        <div className="border rounded-lg">
          <div
            ref={editorRef}
            contentEditable={!disabled && !readonly}
            onInput={handleContentChange}
            onKeyDown={handleKeyDown}
            className={cn(
              "w-full p-4 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-lg",
              "prose prose-sm max-w-none",
              disabled && "cursor-not-allowed opacity-50",
              readonly && "cursor-default"
            )}
            style={{
              minHeight: height ? `${height}px` : `${minHeight}px`,
              maxHeight: height ? `${height}px` : `${maxHeight}px`,
              overflowY: 'auto'
            }}
            dangerouslySetInnerHTML={{ __html: content }}
            data-placeholder={placeholder}
            suppressContentEditableWarning={true}
          />
        </div>

        {/* Status */}
        <div className="flex items-center justify-between text-xs text-muted-foreground">
          <span>
            {content.replace(/<[^>]*>/g, '').length} characters
          </span>
          <span>
            Press Ctrl+B for bold, Ctrl+I for italic, Ctrl+U for underline
          </span>
        </div>
      </CardContent>
    </Card>
  )
}

export default OldRichTextEditor