'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { X, FolderOpen } from 'lucide-react'
import { useNotebooks } from '@/context/notebooks-context'
import { cn } from '@/lib/utils'
import { useLanguage } from '@/lib/i18n'

interface NotebookSuggestionToastProps {
  noteId: string
  noteContent: string
  onDismiss: () => void
  onMoveToNotebook?: (notebookId: string) => void
}

export function NotebookSuggestionToast({
  noteId,
  noteContent,
  onDismiss,
  onMoveToNotebook
}: NotebookSuggestionToastProps) {
  const { t } = useLanguage()
  const [suggestion, setSuggestion] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [visible, setVisible] = useState(true)
  const [timeLeft, setTimeLeft] = useState(30) // 30 second countdown
  const router = useRouter()
  const { moveNoteToNotebookOptimistic } = useNotebooks()

  // Auto-dismiss after 30 seconds
  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft(prev => {
        if (prev <= 1) {
          handleDismiss()
          return 0
        }
        return prev - 1
      })
    }, 1000)

    return () => clearInterval(timer)
  }, [])

  // Fetch suggestion when component mounts
  useEffect(() => {
    const fetchSuggestion = async () => {
      // Only suggest if content is long enough (> 20 words)
      const wordCount = noteContent.trim().split(/\s+/).length
      if (wordCount < 20) {
        return
      }

      setIsLoading(true)
      try {
        const response = await fetch('/api/ai/suggest-notebook', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ noteContent })
        })

        const data = await response.json()
        if (response.ok) {
          if (data.suggestion && data.confidence > 0.7) {
            setSuggestion(data.suggestion)
          }
        }
      } catch (error) {
        // Error fetching notebook suggestion
      } finally {
        setIsLoading(false)
      }
    }

    fetchSuggestion()
  }, [noteContent])

  const handleDismiss = () => {
    setVisible(false)
    setTimeout(() => onDismiss(), 300) // Wait for animation
  }

  const handleMoveToNotebook = async () => {
    if (!suggestion) return

    try {
      // Move note to suggested notebook
      await moveNoteToNotebookOptimistic(noteId, suggestion.id)
      // No need for router.refresh() - triggerRefresh() is already called in moveNoteToNotebookOptimistic
      handleDismiss()
    } catch (error) {
      console.error('Failed to move note to notebook:', error)
    }
  }

  // Don't render if no suggestion or loading or dismissed
  if (!visible || isLoading || !suggestion) {
    return null
  }

  return (
    <div
      className={cn(
        'fixed bottom-4 right-4 z-50 max-w-md bg-white dark:bg-zinc-800',
        'border border-border dark:border-border rounded-lg shadow-lg',
        'p-4 animate-in slide-in-from-bottom-4 fade-in duration-300',
        'transition-all duration-300'
      )}
    >
      <div className="flex items-start gap-3">
        {/* Icon */}
        <div className="flex-shrink-0">
          <div className="w-10 h-10 rounded-full bg-primary/10 dark:bg-primary/20 flex items-center justify-center">
            <FolderOpen className="w-5 h-5 text-primary dark:text-primary-foreground" />
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-gray-900 dark:text-gray-100">
            {t('notebookSuggestion.title', { icon: suggestion.icon, name: suggestion.name })}
          </p>
          <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
            {t('notebookSuggestion.description')}
          </p>
        </div>

        {/* Actions */}
        <div className="flex items-center gap-2">
          {/* Move button */}
          <button
            onClick={handleMoveToNotebook}
            className="px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
          >
            {t('notebookSuggestion.move')}
          </button>

          {/* Dismiss button */}
          <button
            onClick={handleDismiss}
            className="flex-shrink-0 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-zinc-700 transition-colors"
            title={t('notebookSuggestion.dismissIn', { timeLeft })}
          >
            <X className="w-4 h-4 text-gray-400" />
          </button>
        </div>
      </div>
    </div>
  )
}
