'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'
import { useTranslation } from '@/lib/hooks/use-translation'

interface MessageActionsProps {
  content: string
  notebookId?: string
}

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

  const handleSaveToNote = () => {
    if (!notebookId) {
      toast.error(t.sources.cannotSaveNoteNoNotebook)
      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(t.common.copyToClipboard)
        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(t.common.copyToClipboard)
          setCopySuccess(true)
          setTimeout(() => setCopySuccess(false), 2000)
        } catch {
          toast.error(t.common.error)
        }

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

  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>{t.common.saveToNote}</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>{t.common.copyToClipboard}</p>
          </TooltipContent>
        </Tooltip>
      </div>
    </TooltipProvider>
  )
}
