'use client'

import { useState, useCallback } from 'react'
import { Sparkles, Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { cmsApi } from '../../lib/api.js'
import type { BlockNode } from '@actuate-media/cms-core'

export interface AIBlockAssistProps {
  block: BlockNode
  pageTitle?: string
  businessName?: string
  onUpdateData: (data: Record<string, unknown>) => void
}

export function AIBlockAssist({
  block,
  pageTitle,
  businessName,
  onUpdateData,
}: AIBlockAssistProps) {
  const [generating, setGenerating] = useState(false)

  const handleGenerate = useCallback(async () => {
    setGenerating(true)

    try {
      const res = await cmsApi<Record<string, unknown>>('/page-builder/generate-block', {
        method: 'POST',
        body: JSON.stringify({
          blockType: block.settings.blockType,
          variant: block.settings.variant,
          pageContext: {
            pageTitle,
            businessName,
          },
        }),
      })

      if (res.error) {
        toast.error(res.error)
      } else if (res.data) {
        onUpdateData(res.data)
        toast.success('Content generated')
      }
    } catch {
      toast.error('Failed to generate content')
    } finally {
      setGenerating(false)
    }
  }, [block, pageTitle, businessName, onUpdateData])

  return (
    <button
      onClick={handleGenerate}
      disabled={generating}
      className="text-primary hover:bg-primary/10 flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs transition-colors disabled:opacity-50"
      title="Generate content with AI"
    >
      {generating ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
      {generating ? 'Generating...' : 'AI Fill'}
    </button>
  )
}
