'use client'

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

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

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

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

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

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

    try {
      const genRes = await fetch('/api/generate-cartype-content', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ key, label }),
      })
      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.whyRent?.length) patch.whyRent      = gen.whyRent
      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/car-types/${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 to database. The save button is inactive because there are no pending changes - your content is already stored. 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 key and label above to activate.'
              : 'Click to generate intro, why-rent, 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>
  )
}
