'use client'

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

interface CarDoc      { slug: string; title: string }
interface CarTypeDoc  { urlSlug: string; label: string }
interface BrandDoc    { urlSlug: string; name: string }
interface LocationDoc { slug: string; name: string }
interface ListResult<T> { docs: T[] }

type Status = 'idle' | 'loading' | 'success' | 'error'

const AUTHORS = [
  {
    name:  'Riyas',
    role:  'Owner & General Manager',
    bio:   'Riyas founded NCK Car Rental in Dubai after spending years watching tourists struggle with overpriced, impersonal rental counters. He personally curates every car that joins the fleet, knows each model inside-out, and still takes WhatsApp messages from customers himself.',
  },
  {
    name:  'Muhammed',
    role:  'Marketing & Customer Experience',
    bio:   'Muhammed looks after marketing and content at NCK Car Rental. A long-time Dubai resident and self-confessed car enthusiast, he road-tests the fleet regularly and writes from behind the wheel - not from a brochure.',
  },
]

function pickAuthor() {
  return AUTHORS[Math.floor(Math.random() * AUTHORS.length)]
}

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

export function GenerateBlogContentButton() {
  const { id } = useDocumentInfo()

  const [topic,    setTopic]    = useState('')
  const [keywords, setKeywords] = useState('')
  const [notes,    setNotes]    = useState('')
  const [status,   setStatus]   = useState<Status>('idle')
  const [message,  setMessage]  = useState('')

  const canGenerate = topic.trim().length > 5 && keywords.trim().length > 2

  async function handleGenerate() {
    if (!canGenerate) return
    setStatus('loading')
    setMessage('Fetching site data…')

    try {
      // 1. Load all linkable pages in parallel
      const [carsRes, typesRes, brandsRes, locsRes] = await Promise.all([
        fetch('/api/cars?limit=500&depth=0'),
        fetch('/api/car-types?limit=100&depth=0'),
        fetch('/api/brands?limit=100&depth=0'),
        fetch('/api/locations?limit=100&depth=0'),
      ])

      const cars:      CarDoc[]      = ((await carsRes.json())   as ListResult<CarDoc>).docs      ?? []
      const carTypes:  CarTypeDoc[]  = ((await typesRes.json())  as ListResult<CarTypeDoc>).docs  ?? []
      const brands:    BrandDoc[]    = ((await brandsRes.json()) as ListResult<BrandDoc>).docs    ?? []
      const locations: LocationDoc[] = ((await locsRes.json())   as ListResult<LocationDoc>).docs ?? []

      // 2. Pick author + call AI
      const author = pickAuthor()
      setMessage(`Generating article as ${author.name} with GPT-4o… (15–25 seconds)`)
      const genRes = await fetch('/api/generate-blog-content', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          topic, keywords, notes,
          authorName: author.name,
          authorRole: author.role,
          authorBio:  author.bio,
          cars, carTypes, brands, locations,
        }),
      })

      if (!genRes.ok) {
        const err = await genRes.json().catch(() => ({}))
        throw new Error((err as { error?: string }).error ?? `Generation failed (${genRes.status})`)
      }

      const gen = await genRes.json() as {
        title: string; slug: string; excerpt: string; category: string
        tags: { tag: string }[]; readTime: number; seoTitle: string; seoDesc: string
        content: unknown
      }

      // 3. Determine publishedAt (today)
      const today = new Date().toISOString().split('T')[0]

      // 4. Build payload
      const patch: Record<string, unknown> = {
        title:       gen.title,
        slug:        gen.slug,
        excerpt:     gen.excerpt,
        category:    gen.category,
        tags:        gen.tags,
        readTime:    gen.readTime,
        seoTitle:    gen.seoTitle,
        seoDesc:     gen.seoDesc,
        content:     gen.content,
        author:      author.name,
        status:      'draft',
        publishedAt: today,
      }

      // 5. Save - create new doc if no id yet
      setMessage('Saving to CMS…')
      let docId: string | number | null | undefined = id

      if (!docId) {
        const createRes = await fetch('/api/blogs', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            title:       gen.title || topic,
            slug:        gen.slug || tempSlug(topic),
            status:      'draft',
            publishedAt: today,
          }),
        })
        if (!createRes.ok) throw new Error('Failed to create blog record')
        const created = await createRes.json() as { doc?: { id: number } }
        docId = created.doc?.id
        if (!docId) throw new Error('No ID returned from blog creation')
      }

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

      setStatus('success')
      setMessage('Article generated and saved as Draft. Loading…')
      setTimeout(() => {
        window.location.href = id ? window.location.href : `/admin/collections/blogs/${docId}`
        if (id) window.location.reload()
      }, 1000)

    } catch (e) {
      setStatus('error')
      setMessage(e instanceof Error ? e.message : 'Something went wrong')
    }
  }

  const color = {
    idle:    { bg: '#f0f9ff', border: '#bae6fd', btn: '#0369a1' },
    loading: { bg: '#fefce8', border: '#fde68a', btn: '#92400e' },
    success: { bg: '#f0fdf4', border: '#bbf7d0', btn: '#15803d' },
    error:   { bg: '#fef2f2', border: '#fecaca', btn: '#b91c1c' },
  }[status]

  return (
    <div style={{ border: `1px solid ${color.border}`, borderRadius: 8, padding: '14px 16px', background: color.bg, transition: 'all 0.2s' }}>

      {/* Header */}
      <p style={{ margin: '0 0 10px', fontWeight: 700, fontSize: 13, color: '#0f172a' }}>
        ✦ AI Blog Generator
      </p>

      {/* Topic */}
      <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: '#475569', marginBottom: 3 }}>
        Topic / Angle *
      </label>
      <input
        type="text"
        value={topic}
        onChange={e => setTopic(e.target.value)}
        placeholder="e.g. Best cars to rent for Dubai desert safari"
        disabled={status === 'loading'}
        style={{
          width: '100%', boxSizing: 'border-box', padding: '7px 10px',
          border: '1px solid #cbd5e1', borderRadius: 6, fontSize: 12,
          marginBottom: 8, background: '#fff', color: '#0f172a',
          outline: 'none', opacity: status === 'loading' ? 0.6 : 1,
        }}
      />

      {/* Keywords */}
      <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: '#475569', marginBottom: 3 }}>
        Target Keywords * <span style={{ fontWeight: 400, color: '#94a3b8' }}>(comma-separated)</span>
      </label>
      <input
        type="text"
        value={keywords}
        onChange={e => setKeywords(e.target.value)}
        placeholder="e.g. desert safari car rental, best SUV Dubai, 4x4 rental dubai"
        disabled={status === 'loading'}
        style={{
          width: '100%', boxSizing: 'border-box', padding: '7px 10px',
          border: '1px solid #cbd5e1', borderRadius: 6, fontSize: 12,
          marginBottom: 8, background: '#fff', color: '#0f172a',
          outline: 'none', opacity: status === 'loading' ? 0.6 : 1,
        }}
      />

      {/* Notes (optional) */}
      <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: '#475569', marginBottom: 3 }}>
        Notes / Angle <span style={{ fontWeight: 400, color: '#94a3b8' }}>(optional)</span>
      </label>
      <textarea
        value={notes}
        onChange={e => setNotes(e.target.value)}
        placeholder="e.g. Focus on families. Mention Hatta mountain road. Compare Range Rover vs Nissan Patrol."
        disabled={status === 'loading'}
        rows={2}
        style={{
          width: '100%', boxSizing: 'border-box', padding: '7px 10px',
          border: '1px solid #cbd5e1', borderRadius: 6, fontSize: 12,
          marginBottom: 10, background: '#fff', color: '#0f172a',
          resize: 'vertical', outline: 'none', fontFamily: 'inherit',
          opacity: status === 'loading' ? 0.6 : 1,
        }}
      />

      {/* Hint */}
      <p style={{ margin: '0 0 10px', fontSize: 11, color: '#64748b', lineHeight: 1.5 }}>
        Generates 800–1,200 word article with H2 sections, internal links to car/brand/type pages, SEO title, meta desc, tags, and slug. Saved as <strong>Draft</strong> - review before publishing.
      </p>

      {/* Button */}
      <button
        type="button"
        onClick={handleGenerate}
        disabled={!canGenerate || status === 'loading'}
        style={{
          width: '100%', padding: '9px 16px',
          background: (!canGenerate || status === 'loading') ? '#94a3b8' : color.btn,
          color: '#fff', border: 'none', borderRadius: 6,
          fontSize: 12, fontWeight: 700, cursor: !canGenerate || status === 'loading' ? 'not-allowed' : 'pointer',
          letterSpacing: '0.01em', transition: 'background 0.15s',
        }}
      >
        {status === 'loading' ? '⏳ Generating…' : '✦ Generate Article'}
      </button>

      {/* Status message */}
      {message && (
        <div style={{
          marginTop: 8, padding: '7px 10px', borderRadius: 5, fontSize: 11,
          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'}`,
          lineHeight: 1.5,
        }}>
          {message}
        </div>
      )}
    </div>
  )
}
