'use client'

import { useState } from 'react'
import { useFormFields, useDocumentInfo } from '@payloadcms/ui'

interface Generated {
  heroSubtitle?: string
  intro?: string
  highlights?: Array<{ title: string; body: string }>
  modelRange?: Array<{ tier: string; description: string }>
  dubaiContext?: string
  whoRents?: string
  requirements?: string
  faqs?: Array<{ question: string; answer: string }>
  seoText?: string
  seoTitle?: string
  seoDesc?: string
}

export function GenerateBrandButton() {
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle')
  const [message, setMessage] = useState('')

  const { id } = useDocumentInfo()
  const fields = useFormFields(([f]) => f)

  const name  = String(fields.name?.value ?? '').trim()
  const ready = name.length > 0 && Boolean(id)

  async function handleGenerate() {
    if (!ready) return
    setStatus('loading')
    setMessage('Generating content for this brand...')

    try {
      const genRes = await fetch('/api/generate-brand-content', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name }),
      })
      if (!genRes.ok) {
        const err = await genRes.json().catch(() => ({ error: genRes.statusText }))
        throw new Error((err as { error?: string }).error ?? 'Generation failed')
      }
      const gen = (await genRes.json()) as Generated

      const patch: Record<string, unknown> = {}
      if (gen.heroSubtitle)        patch.heroSubtitle = gen.heroSubtitle
      if (gen.intro)               patch.intro        = gen.intro
      if (gen.highlights?.length)  patch.highlights   = gen.highlights
      if (gen.modelRange?.length)  patch.modelRange   = gen.modelRange
      if (gen.dubaiContext)        patch.dubaiContext  = gen.dubaiContext
      if (gen.whoRents)            patch.whoRents      = gen.whoRents
      if (gen.requirements)        patch.requirements  = gen.requirements
      if (gen.faqs?.length)        patch.faqs          = gen.faqs
      if (gen.seoText)             patch.seoText       = gen.seoText
      if (gen.seoTitle)            patch.seoTitle      = gen.seoTitle
      if (gen.seoDesc)             patch.seoDesc       = gen.seoDesc

      const patchRes = await fetch(`/api/brands/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(patch),
      })
      if (!patchRes.ok) {
        const errBody = await patchRes.json().catch(() => ({}))
        throw new Error(`Save failed: ${JSON.stringify(errBody)}`)
      }

      setStatus('success')
      setMessage('Content saved. The save button is inactive because there are no pending changes. Reloading...')
      setTimeout(() => window.location.reload(), 1500)
    } catch (e) {
      setStatus('error')
      setMessage(e instanceof Error ? e.message : 'Something went wrong')
    }
  }

  return (
    <div
      style={{
        border: `1px solid ${ready ? '#cbd5e1' : '#e2e8f0'}`,
        borderRadius: '8px',
        padding: '14px 18px',
        marginBottom: '4px',
        background: ready ? '#f0f9ff' : '#f8fafc',
        transition: 'background 0.2s, border-color 0.2s',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '16px', flexWrap: 'wrap' }}>
        <div>
          <p style={{ margin: 0, fontWeight: 700, fontSize: '13px', color: '#0f172a' }}>
            ✦ AI Content Generator
          </p>
          <p style={{ margin: '3px 0 0', fontSize: '11px', color: '#64748b', lineHeight: 1.5 }}>
            {!id
              ? 'Save the document first to enable generation.'
              : !ready
              ? 'Fill in the brand name above to activate.'
              : 'Click to generate intro, highlights, Dubai context, FAQs, SEO, and more.'}
          </p>
        </div>
        <button
          type="button"
          onClick={handleGenerate}
          disabled={!ready || status === 'loading'}
          style={{
            background: !ready ? '#e2e8f0' : status === 'loading' ? '#94a3b8' : '#0369a1',
            color: !ready ? '#94a3b8' : '#fff',
            border: 'none',
            borderRadius: '6px',
            padding: '8px 16px',
            fontSize: '12px',
            fontWeight: 700,
            cursor: !ready || status === 'loading' ? 'not-allowed' : 'pointer',
            whiteSpace: 'nowrap',
            flexShrink: 0,
          }}
        >
          {status === 'loading' ? 'Generating…' : 'Generate Content'}
        </button>
      </div>
      {message && (
        <div
          style={{
            marginTop: '10px',
            padding: '7px 11px',
            borderRadius: '5px',
            fontSize: '12px',
            background: status === 'success' ? '#dcfce7' : status === 'error' ? '#fee2e2' : '#e0f2fe',
            color: status === 'success' ? '#166534' : status === 'error' ? '#991b1b' : '#0369a1',
            border: `1px solid ${status === 'success' ? '#bbf7d0' : status === 'error' ? '#fecaca' : '#bae6fd'}`,
          }}
        >
          {message}
        </div>
      )}
    </div>
  )
}
