'use client'

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

interface BrandDoc  { id: number; name: string; urlSlug: string }
interface CarTypeDoc { id: number; key: string; label: string; urlSlug: string }
interface ListResult<T> { docs: T[] }

interface Generated {
  slug?: string
  brandName?: string
  carTypeKey?: string
  passengers?: number
  doors?: number
  bags?: number
  transmission?: string
  noDeposit?: boolean
  features?: string[]
  description?: string
  seoTitle?: string
  seoDesc?: string
  faqs?: Array<{ question: string; answer: string }>
}

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

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

  const title    = String(fields.title?.value    ?? '').trim()
  const priceDay = fields.priceDay?.value  as number | undefined
  const priceOrig = fields.priceOrig?.value as number | undefined
  const hasTitle = title.length > 0

  function tempSlug(str: string): string {
    return str.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') + '-rental-dubai'
  }

  async function handleGenerate() {
    if (!hasTitle) return

    setStatus('loading')
    setMessage('Fetching data and generating content…')

    try {
      // 1. Fetch available brands and car types from Payload
      const [brandsRes, carTypesRes] = await Promise.all([
        fetch('/api/brands?limit=100'),
        fetch('/api/car-types?limit=100'),
      ])
      const brands   = ((await brandsRes.json())   as ListResult<BrandDoc>).docs   ?? []
      const carTypes = ((await carTypesRes.json()) as ListResult<CarTypeDoc>).docs ?? []

      // 2. Call OpenAI to generate all content
      setMessage('Asking AI to generate content… (this takes ~10 seconds)')
      const genRes = await fetch('/api/generate-car-content', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title, priceDay, priceOrig, availableBrands: brands, availableCarTypes: carTypes }),
      })
      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

      // 3. Match brand/carType names → document IDs
      const matchedBrand   = gen.brandName   ? brands.find(b  => b.name.toLowerCase() === gen.brandName!.toLowerCase())   : null
      const matchedCarType = gen.carTypeKey  ? carTypes.find(ct => ct.key === gen.carTypeKey)                               : null

      // 4. Build PATCH payload
      const patch: Record<string, unknown> = { title }
      if (priceDay  != null)                  patch.priceDay     = priceDay
      if (priceOrig != null)                  patch.priceOrig    = priceOrig
      if (gen.slug)                           patch.slug         = gen.slug
      if (matchedBrand)                       patch.brand        = matchedBrand.id
      if (matchedCarType)                     patch.carType      = matchedCarType.id
      if (gen.passengers != null)             patch.passengers   = gen.passengers
      if (gen.doors      != null)             patch.doors        = gen.doors
      if (gen.bags       != null)             patch.bags         = gen.bags
      if (gen.transmission)                   patch.transmission = gen.transmission
      if (typeof gen.noDeposit === 'boolean') patch.noDeposit    = gen.noDeposit
      if (gen.features?.length)               patch.features     = gen.features.map(f => ({ feature: f }))
      if (gen.description)                    patch.description  = gen.description
      if (gen.seoTitle)                       patch.seoTitle     = gen.seoTitle
      if (gen.seoDesc)                        patch.seoDesc      = gen.seoDesc
      if (gen.faqs?.length)                   patch.faqs         = gen.faqs

      // 5. Create or update the document
      let docId: string | number | null | undefined = id

      if (!docId) {
        // New document - POST to create it, then PATCH with all content
        setMessage('Saving…')
        const createRes = await fetch('/api/cars', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            title,
            slug: tempSlug(title),
            ...(priceDay  != null ? { priceDay  } : {}),
            ...(priceOrig != null ? { priceOrig } : {}),
          }),
        })
        if (!createRes.ok) throw new Error('Failed to create car record')
        const created = (await createRes.json()) as { doc?: { id: number } }
        docId = created.doc?.id
        if (!docId) throw new Error('No ID returned from car creation')
      }

      // 6. PATCH the document with all generated content
      const patchRes = await fetch(`/api/cars/${docId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(patch),
      })
      if (!patchRes.ok) {
        const patchErr = await patchRes.json().catch(() => ({}))
        throw new Error(`Save failed: ${JSON.stringify(patchErr)}`)
      }

      setStatus('success')
      setMessage('Content saved to database. The save button is inactive because there are no pending changes - your content is already stored. Loading...')

      if (!id) {
        // Navigate to the newly created car's edit page
        setTimeout(() => { window.location.href = `/admin/collections/cars/${docId}` }, 900)
      } else {
        setTimeout(() => window.location.reload(), 900)
      }
    } catch (e) {
      setStatus('error')
      setMessage(e instanceof Error ? e.message : 'Something went wrong')
    }
  }

  return (
    <div
      style={{
        border: `1px solid ${hasTitle ? '#cbd5e1' : '#e2e8f0'}`,
        borderRadius: '8px',
        padding: '14px 18px',
        marginBottom: '4px',
        background: hasTitle ? '#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 }}>
            {!hasTitle
              ? 'Enter the car title above to activate.'
              : 'Click to generate slug, brand, specs, features, description, SEO, and FAQs.'}
          </p>
        </div>
        <button
          type="button"
          onClick={handleGenerate}
          disabled={!hasTitle || status === 'loading'}
          style={{
            background: !hasTitle ? '#e2e8f0' : status === 'loading' ? '#94a3b8' : '#0369a1',
            color: !hasTitle ? '#94a3b8' : '#fff',
            border: 'none',
            borderRadius: '6px',
            padding: '8px 16px',
            fontSize: '12px',
            fontWeight: 700,
            cursor: !hasTitle || status === 'loading' ? 'not-allowed' : 'pointer',
            whiteSpace: 'nowrap',
            flexShrink: 0,
            letterSpacing: '0.01em',
          }}
        >
          {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>
  )
}
