'use client'

import { useState, useCallback } from 'react'
import * as Dialog from '@radix-ui/react-dialog'
import {
  Sparkles,
  X,
  Loader2,
  Check,
  ChevronDown,
  ChevronUp,
  AlertTriangle,
  Wand2,
  FileText,
  Search,
  Accessibility,
  ArrowRight,
} from 'lucide-react'
import { toast } from 'sonner'
import { cmsApi } from '../../lib/api.js'
import { adminPortalContainer } from '../../lib/portal-container.js'
import type { PageNode, GenerationStep } from '@actuate-media/cms-core'

export interface AIGenerateDialogProps {
  open: boolean
  onClose: () => void
  onAccept: (tree: PageNode) => void
}

interface StepInfo {
  key: GenerationStep
  label: string
  icon: React.ReactNode
  description: string
}

const ALL_STEPS: StepInfo[] = [
  {
    key: 'structure',
    label: 'Structure',
    icon: <Wand2 size={14} />,
    description: 'Generate page layout and block placement',
  },
  {
    key: 'content',
    label: 'Content',
    icon: <FileText size={14} />,
    description: 'Write compelling copy for every block',
  },
  {
    key: 'seo',
    label: 'SEO',
    icon: <Search size={14} />,
    description: 'Optimize headings, meta tags, and keywords',
  },
  {
    key: 'accessibility',
    label: 'Accessibility',
    icon: <Accessibility size={14} />,
    description: 'Fix heading hierarchy, alt text, and ARIA',
  },
]

type Tone = 'professional' | 'casual' | 'friendly' | 'technical' | 'luxury'

const TONES: { value: Tone; label: string }[] = [
  { value: 'professional', label: 'Professional' },
  { value: 'casual', label: 'Casual' },
  { value: 'friendly', label: 'Friendly' },
  { value: 'technical', label: 'Technical' },
  { value: 'luxury', label: 'Luxury' },
]

type Phase = 'prompt' | 'generating' | 'review'

interface GenerationStepResult {
  step: string
  metadata: {
    tokensUsed: number
    durationMs: number
    changes: string[]
  }
}

interface GenerationResultData {
  tree: PageNode
  steps: GenerationStepResult[]
  totalTokensUsed: number
  totalDurationMs: number
}

export function AIGenerateDialog({ open, onClose, onAccept }: AIGenerateDialogProps) {
  const [phase, setPhase] = useState<Phase>('prompt')
  const [prompt, setPrompt] = useState('')
  const [tone, setTone] = useState<Tone>('professional')
  const [enabledSteps, setEnabledSteps] = useState<Set<GenerationStep>>(
    new Set(['structure', 'content', 'seo', 'accessibility']),
  )
  const [showContext, setShowContext] = useState(false)
  const [businessName, setBusiness] = useState('')
  const [industry, setIndustry] = useState('')
  const [phone, setPhone] = useState('')
  const [address, setAddress] = useState('')
  const [services, setServices] = useState('')

  const [currentStep, setCurrentStep] = useState<string>('')
  const [completedSteps, setCompletedSteps] = useState<string[]>([])
  const [stepMessage, setStepMessage] = useState('')

  const [result, setResult] = useState<GenerationResultData | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [expandedStep, setExpandedStep] = useState<string | null>(null)

  const toggleStep = (step: GenerationStep) => {
    const next = new Set(enabledSteps)
    if (step === 'structure') return
    if (next.has(step)) {
      next.delete(step)
    } else {
      next.add(step)
    }
    setEnabledSteps(next)
  }

  const resetState = useCallback(() => {
    setPhase('prompt')
    setPrompt('')
    setTone('professional')
    setEnabledSteps(new Set(['structure', 'content', 'seo', 'accessibility']))
    setShowContext(false)
    setBusiness('')
    setIndustry('')
    setPhone('')
    setAddress('')
    setServices('')
    setCurrentStep('')
    setCompletedSteps([])
    setStepMessage('')
    setResult(null)
    setError(null)
    setExpandedStep(null)
  }, [])

  const handleClose = useCallback(() => {
    resetState()
    onClose()
  }, [resetState, onClose])

  const handleGenerate = useCallback(async () => {
    if (!prompt.trim()) {
      toast.error('Please describe the page you want to create')
      return
    }

    setPhase('generating')
    setError(null)

    const steps = ALL_STEPS.filter((s) => enabledSteps.has(s.key)).map((s) => s.key)

    setCurrentStep(steps[0]!)
    setStepMessage('Starting generation...')

    const context: Record<string, unknown> = {}
    if (businessName) context.businessName = businessName
    if (industry) context.industry = industry
    if (phone) context.phone = phone
    if (address) context.address = address
    if (services)
      context.services = services
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean)

    try {
      const res = await cmsApi<GenerationResultData>('/page-builder/generate', {
        method: 'POST',
        body: JSON.stringify({
          prompt: prompt.trim(),
          steps,
          tone,
          context: Object.keys(context).length > 0 ? context : undefined,
        }),
      })

      if (res.error) {
        setError(res.error)
        setPhase('prompt')
        return
      }

      if (res.data) {
        setResult(res.data)
        setCompletedSteps(res.data.steps.map((s) => s.step))
        setPhase('review')
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Generation failed')
      setPhase('prompt')
    }
  }, [prompt, tone, enabledSteps, businessName, industry, phone, address, services])

  const handleAccept = useCallback(() => {
    if (result?.tree) {
      onAccept(result.tree)
      toast.success('AI-generated page applied')
      handleClose()
    }
  }, [result, onAccept, handleClose])

  return (
    <Dialog.Root open={open} onOpenChange={(next) => !next && handleClose()}>
      <Dialog.Portal container={adminPortalContainer()}>
        <Dialog.Overlay className="fixed inset-0 z-50 bg-black/50" />
        <Dialog.Content className="bg-card border-border text-card-foreground fixed top-1/2 left-1/2 z-50 flex max-h-[85vh] w-[calc(100%-2rem)] max-w-2xl -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border shadow-2xl focus:outline-none">
          {/* Header */}
          <div className="border-border flex items-center justify-between border-b px-6 py-4">
            <div className="flex items-center gap-2.5">
              <div className="bg-primary/10 rounded-lg p-1.5">
                <Sparkles size={18} className="text-primary" aria-hidden />
              </div>
              <div>
                <Dialog.Title className="text-foreground text-base font-medium">
                  AI Page Generator
                </Dialog.Title>
                <Dialog.Description className="text-muted-foreground text-xs">
                  Describe your page and let AI build it
                </Dialog.Description>
              </div>
            </div>
            <Dialog.Close asChild>
              <button
                type="button"
                className="hover:bg-muted text-muted-foreground hover:text-foreground focus-visible:ring-ring rounded-md p-1.5 transition-colors focus-visible:ring-2 focus-visible:outline-none"
                aria-label="Close AI page generator"
              >
                <X size={16} aria-hidden />
              </button>
            </Dialog.Close>
          </div>

          {/* Content */}
          <div className="flex-1 overflow-y-auto p-6">
            {phase === 'prompt' && (
              <div className="space-y-5">
                {error && (
                  <div className="bg-destructive/5 border-destructive/20 flex items-start gap-2.5 rounded-lg border p-3">
                    <AlertTriangle size={16} className="text-destructive mt-0.5 shrink-0" />
                    <p className="text-destructive text-sm">{error}</p>
                  </div>
                )}

                {/* Prompt */}
                <div>
                  <label className="text-foreground mb-1.5 block text-sm font-medium">
                    Describe your page
                  </label>
                  <textarea
                    value={prompt}
                    onChange={(e) => setPrompt(e.target.value)}
                    placeholder="e.g. A landing page for a plumbing company with a hero section, service cards, testimonials, and a contact form"
                    rows={4}
                    className="bg-background border-border focus:ring-primary/40 text-foreground placeholder:text-muted-foreground w-full resize-none rounded-lg border px-3 py-2.5 text-sm focus:ring-2 focus:outline-none"
                    autoFocus
                  />
                </div>

                {/* Tone */}
                <div>
                  <label className="text-foreground mb-1.5 block text-sm font-medium">Tone</label>
                  <div className="flex flex-wrap gap-2">
                    {TONES.map((t) => (
                      <button
                        key={t.value}
                        onClick={() => setTone(t.value)}
                        className={`rounded-full border px-3 py-1.5 text-xs transition-colors ${
                          tone === t.value
                            ? 'border-primary bg-primary/10 text-primary'
                            : 'border-border bg-background text-muted-foreground hover:border-primary/40'
                        }`}
                      >
                        {t.label}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Steps */}
                <div>
                  <label className="text-foreground mb-1.5 block text-sm font-medium">
                    Generation steps
                  </label>
                  <div className="space-y-1.5">
                    {ALL_STEPS.map((step) => (
                      <label
                        key={step.key}
                        className={`flex cursor-pointer items-center gap-3 rounded-lg border p-2.5 transition-colors ${
                          enabledSteps.has(step.key)
                            ? 'border-primary/30 bg-primary/5'
                            : 'border-border bg-background'
                        } ${step.key === 'structure' ? 'cursor-not-allowed opacity-70' : 'hover:border-primary/20'}`}
                      >
                        <input
                          type="checkbox"
                          checked={enabledSteps.has(step.key)}
                          onChange={() => toggleStep(step.key)}
                          disabled={step.key === 'structure'}
                          className="sr-only"
                        />
                        <div
                          className={`flex h-5 w-5 shrink-0 items-center justify-center rounded ${
                            enabledSteps.has(step.key)
                              ? 'bg-primary text-primary-foreground'
                              : 'bg-muted border-border border'
                          }`}
                        >
                          {enabledSteps.has(step.key) && <Check size={12} />}
                        </div>
                        <div className="flex min-w-0 flex-1 items-center gap-2">
                          <span className="text-muted-foreground">{step.icon}</span>
                          <div>
                            <span className="text-foreground text-sm">{step.label}</span>
                            <span className="text-muted-foreground ml-2 text-xs">
                              {step.description}
                            </span>
                          </div>
                        </div>
                      </label>
                    ))}
                  </div>
                </div>

                {/* Business context (collapsible) */}
                <div>
                  <button
                    onClick={() => setShowContext(!showContext)}
                    className="text-muted-foreground hover:text-foreground flex items-center gap-1.5 text-sm transition-colors"
                  >
                    {showContext ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
                    Business context (optional)
                  </button>
                  {showContext && (
                    <div className="bg-muted/50 border-border mt-3 space-y-3 rounded-lg border p-4">
                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="text-muted-foreground mb-1 block text-xs">
                            Business name
                          </label>
                          <input
                            type="text"
                            value={businessName}
                            onChange={(e) => setBusiness(e.target.value)}
                            className="bg-background border-border focus:ring-primary/40 text-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none"
                          />
                        </div>
                        <div>
                          <label className="text-muted-foreground mb-1 block text-xs">
                            Industry
                          </label>
                          <input
                            type="text"
                            value={industry}
                            onChange={(e) => setIndustry(e.target.value)}
                            className="bg-background border-border focus:ring-primary/40 text-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none"
                          />
                        </div>
                        <div>
                          <label className="text-muted-foreground mb-1 block text-xs">Phone</label>
                          <input
                            type="text"
                            value={phone}
                            onChange={(e) => setPhone(e.target.value)}
                            className="bg-background border-border focus:ring-primary/40 text-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none"
                          />
                        </div>
                        <div>
                          <label className="text-muted-foreground mb-1 block text-xs">
                            Address
                          </label>
                          <input
                            type="text"
                            value={address}
                            onChange={(e) => setAddress(e.target.value)}
                            className="bg-background border-border focus:ring-primary/40 text-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none"
                          />
                        </div>
                      </div>
                      <div>
                        <label className="text-muted-foreground mb-1 block text-xs">
                          Services (comma-separated)
                        </label>
                        <input
                          type="text"
                          value={services}
                          onChange={(e) => setServices(e.target.value)}
                          placeholder="e.g. Web design, SEO, Content marketing"
                          className="bg-background border-border focus:ring-primary/40 text-foreground placeholder:text-muted-foreground w-full rounded-md border px-2.5 py-1.5 text-sm focus:ring-2 focus:outline-none"
                        />
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}

            {phase === 'generating' && (
              <div className="space-y-6 py-8">
                <div className="text-center">
                  <Loader2 size={32} className="text-primary mx-auto mb-3 animate-spin" />
                  <p className="text-foreground text-sm font-medium">
                    {stepMessage || 'Generating...'}
                  </p>
                  <p className="text-muted-foreground mt-1 text-xs">This may take 15-30 seconds</p>
                </div>

                <div className="space-y-2">
                  {ALL_STEPS.filter((s) => enabledSteps.has(s.key)).map((step) => {
                    const isComplete = completedSteps.includes(step.key)
                    const isCurrent = currentStep === step.key

                    return (
                      <div
                        key={step.key}
                        className={`flex items-center gap-3 rounded-lg border p-3 transition-colors ${
                          isComplete
                            ? 'border-primary/30 bg-primary/5'
                            : isCurrent
                              ? 'border-primary/50 bg-primary/10'
                              : 'border-border bg-muted/30'
                        }`}
                      >
                        <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full">
                          {isComplete ? (
                            <div className="bg-primary flex h-6 w-6 items-center justify-center rounded-full">
                              <Check size={12} className="text-primary-foreground" />
                            </div>
                          ) : isCurrent ? (
                            <Loader2 size={16} className="text-primary animate-spin" />
                          ) : (
                            <div className="bg-muted border-border h-6 w-6 rounded-full border" />
                          )}
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="text-muted-foreground">{step.icon}</span>
                          <span
                            className={`text-sm ${isCurrent || isComplete ? 'text-foreground' : 'text-muted-foreground'}`}
                          >
                            {step.label}
                          </span>
                        </div>
                      </div>
                    )
                  })}
                </div>
              </div>
            )}

            {phase === 'review' && result && (
              <div className="space-y-5">
                {/* Summary */}
                <div className="bg-primary/5 border-primary/20 flex items-center gap-3 rounded-lg border p-4">
                  <div className="bg-primary/10 flex h-10 w-10 shrink-0 items-center justify-center rounded-full">
                    <Sparkles size={18} className="text-primary" />
                  </div>
                  <div>
                    <p className="text-foreground text-sm font-medium">
                      Page generated successfully
                    </p>
                    <p className="text-muted-foreground mt-0.5 text-xs">
                      {result.totalTokensUsed.toLocaleString()} tokens
                      {' \u00B7 '}
                      {(result.totalDurationMs / 1000).toFixed(1)}s{' \u00B7 '}
                      {result.steps.length} step{result.steps.length !== 1 ? 's' : ''}
                    </p>
                  </div>
                </div>

                {/* Step details */}
                <div className="space-y-2">
                  <h3 className="text-foreground text-sm font-medium">Generation steps</h3>
                  {result.steps.map((step) => {
                    const info = ALL_STEPS.find((s) => s.key === step.step)
                    const isExpanded = expandedStep === step.step

                    return (
                      <div
                        key={step.step}
                        className="border-border overflow-hidden rounded-lg border"
                      >
                        <button
                          onClick={() => setExpandedStep(isExpanded ? null : step.step)}
                          className="hover:bg-muted/50 flex w-full items-center gap-3 p-3 text-left transition-colors"
                        >
                          <div className="bg-primary flex h-6 w-6 shrink-0 items-center justify-center rounded-full">
                            <Check size={12} className="text-primary-foreground" />
                          </div>
                          <span className="text-muted-foreground">{info?.icon}</span>
                          <span className="text-foreground flex-1 text-sm">{info?.label}</span>
                          <span className="text-muted-foreground text-xs">
                            {(step.metadata.durationMs / 1000).toFixed(1)}s
                          </span>
                          {isExpanded ? (
                            <ChevronUp size={14} className="text-muted-foreground" />
                          ) : (
                            <ChevronDown size={14} className="text-muted-foreground" />
                          )}
                        </button>
                        {isExpanded && (
                          <div className="border-border border-t px-3 pt-2 pb-3">
                            <ul className="space-y-1">
                              {step.metadata.changes.map((change, i) => (
                                <li
                                  key={i}
                                  className="text-muted-foreground flex items-start gap-2 text-xs"
                                >
                                  <ArrowRight size={10} className="mt-0.5 shrink-0" />
                                  {change}
                                </li>
                              ))}
                            </ul>
                            <p className="text-muted-foreground mt-2 text-xs">
                              Tokens: {step.metadata.tokensUsed.toLocaleString()}
                            </p>
                          </div>
                        )}
                      </div>
                    )
                  })}
                </div>

                <p className="text-muted-foreground text-xs">
                  Review the generated page in the canvas after accepting. You can always undo to
                  revert.
                </p>
              </div>
            )}
          </div>

          {/* Footer */}
          <div className="border-border flex items-center justify-end gap-3 border-t px-6 py-4">
            {phase === 'prompt' && (
              <>
                <button
                  onClick={handleClose}
                  className="text-muted-foreground hover:text-foreground px-4 py-2 text-sm transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleGenerate}
                  disabled={!prompt.trim()}
                  className="bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
                >
                  <Sparkles size={14} />
                  Generate Page
                </button>
              </>
            )}

            {phase === 'generating' && (
              <button
                onClick={handleClose}
                className="text-muted-foreground hover:text-foreground px-4 py-2 text-sm transition-colors"
              >
                Cancel
              </button>
            )}

            {phase === 'review' && (
              <>
                <button
                  onClick={() => {
                    setPhase('prompt')
                    setResult(null)
                  }}
                  className="text-muted-foreground hover:text-foreground px-4 py-2 text-sm transition-colors"
                >
                  Regenerate
                </button>
                <button
                  onClick={handleAccept}
                  className="bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors"
                >
                  <Check size={14} />
                  Accept &amp; Apply
                </button>
              </>
            )}
          </div>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  )
}
