'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { Save, Copy, Loader2, Check } from 'lucide-react'
import { useCreateNote } from '@/lib/hooks/use-notes'
import { toast } from 'sonner'

interface MessageActionsProps {
  content: string
  notebookId?: string
}

export function MessageActions({ content, notebookId }: MessageActionsProps) {
  const [copySuccess, setCopySuccess] = useState(false)
  const createNote = useCreateNote()

  const handleSaveToNote = () => {
    if (!notebookId) {
      toast.error('Cannot save note: notebook ID not available')
      return
    }

    createNote.mutate({
      content,
      note_type: 'ai',
      notebook_id: notebookId,
      // Title will be auto-generated by the API for AI notes
    })
  }

  const handleCopyToClipboard = async () => {
    try {
      // Try modern clipboard API first
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(content)
        toast.success('Message copied to clipboard')
        setCopySuccess(true)
        setTimeout(() => setCopySuccess(false), 2000)
      } else {
        // Fallback for older browsers
        const textArea = document.createElement('textarea')
        textArea.value = content
        textArea.style.position = 'fixed'
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()

        try {
          document.execCommand('copy')
          toast.success('Message copied to clipboard')
          setCopySuccess(true)
          setTimeout(() => setCopySuccess(false), 2000)
        } catch {
          toast.error('Failed to copy message')
        }

        document.body.removeChild(textArea)
      }
    } catch (err) {
      console.error('Failed to copy to clipboard:', err)
      toast.error('Failed to copy message')
    }
  }

  return (
    <TooltipProvider>
      <div className="flex gap-1">
        {notebookId && (
          <Tooltip>
            <TooltipTrigger asChild>
              <Button
                variant="ghost"
                size="sm"
                className="h-7 px-2"
                onClick={handleSaveToNote}
                disabled={createNote.isPending}
              >
                {createNote.isPending ? (
                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                ) : (
                  <Save className="h-3.5 w-3.5" />
                )}
              </Button>
            </TooltipTrigger>
            <TooltipContent>
              <p>Save to note</p>
            </TooltipContent>
          </Tooltip>
        )}
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              variant="ghost"
              size="sm"
              className="h-7 px-2"
              onClick={handleCopyToClipboard}
              disabled={createNote.isPending}
            >
              {copySuccess ? (
                <Check className="h-3.5 w-3.5 text-green-500" />
              ) : (
                <Copy className="h-3.5 w-3.5" />
              )}
            </Button>
          </TooltipTrigger>
          <TooltipContent>
            <p>Copy to clipboard</p>
          </TooltipContent>
        </Tooltip>
      </div>
    </TooltipProvider>
  )
}
