import { useState, useCallback, useEffect } from 'react'
import { Sparkles, ArrowRight, PencilRuler, Wand2, X } from 'lucide-react'
import { networkDiagramsApi } from '@/api'
import type { AIGenerateResponse } from '@/types'

const EXAMPLE_PROMPTS = [
  'Small office with firewall and core switch',
  'Azure hybrid cloud with VPN gateway',
  'Branch office connected to HQ via MPLS',
  'Data center with redundant core switches',
  'Remote workforce with Meraki and cloud apps',
]

interface CanvasEmptyPromptProps {
  onGenerate: (result: AIGenerateResponse, mode: 'replace' | 'merge') => void
}

export function CanvasEmptyPrompt({ onGenerate }: CanvasEmptyPromptProps) {
  const [mode, setMode] = useState<'choice' | 'ai' | 'manual'>('choice')
  const [description, setDescription] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const switchToManual = useCallback(() => {
    if (loading) return
    setMode('manual')
    setError(null)
  }, [loading])

  const handleGenerate = useCallback(async (text?: string) => {
    const desc = (text ?? description).trim()
    if (!desc) return
    setLoading(true)
    setError(null)
    try {
      const result = await networkDiagramsApi.aiGenerate({
        description: desc,
        mode: 'replace',
        existingBounds: null,
      })
      onGenerate(result, 'replace')
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Generation failed. Please try again.')
    } finally {
      setLoading(false)
    }
  }, [description, onGenerate])

  useEffect(() => {
    if (mode === 'manual') return

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        event.preventDefault()
        switchToManual()
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [mode, switchToManual])

  if (mode === 'manual') {
    return (
      <div className="pointer-events-none absolute inset-x-0 bottom-6 z-10 flex justify-center px-6">
        <div className="pointer-events-auto flex max-w-xl items-center gap-3 rounded-lg border border-default bg-card px-4 py-3 shadow-xl">
          <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-accent">
            <PencilRuler size={14} />
          </div>
          <div className="min-w-0 flex-1">
            <p className="text-sm font-medium text-heading">Manual mode is on</p>
            <p className="text-xs text-muted-foreground">
              Drag devices from the left panel onto the canvas, or reopen AI whenever you want.
            </p>
          </div>
          <button
            onClick={() => setMode('ai')}
            className="inline-flex shrink-0 items-center gap-1 rounded-full border border-default px-3 py-1 text-xs font-medium text-primary hover:border-accent hover:text-accent"
          >
            <Sparkles size={12} />
            Open AI Generator
          </button>
        </div>
      </div>
    )
  }

  return (
    <div
      className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-[rgba(10,14,20,0.42)] px-6"
      onClick={event => {
        if (event.target === event.currentTarget) {
          switchToManual()
        }
      }}
    >
      <div className="pointer-events-auto relative w-full max-w-lg rounded-lg border border-default bg-card p-8 shadow-2xl">
        <button
          onClick={switchToManual}
          disabled={loading}
          aria-label="Close AI prompt and build manually"
          className="absolute right-4 top-4 inline-flex h-8 w-8 items-center justify-center rounded-full border border-default text-muted-foreground hover:border-hover hover:text-primary disabled:opacity-40"
        >
          <X size={14} />
        </button>
        {mode === 'choice' ? (
          <>
            <div className="mb-6 text-center">
              <div className="mb-2 flex items-center justify-center gap-2">
                <Wand2 size={16} className="text-accent" />
                <h2 className="font-heading text-base font-semibold text-heading">
                  Start a network map
                </h2>
              </div>
              <p className="text-xs text-muted-foreground">
                Generate a topology with AI or start with a blank canvas and build it manually.
              </p>
              <p className="mt-2 text-[11px] text-muted-foreground/80">
                Press <span className="font-medium text-primary">Esc</span> or click outside to skip AI and start dragging devices.
              </p>
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              <button
                onClick={() => setMode('ai')}
                className="rounded-lg border border-accent/40 bg-accent/10 p-4 text-left transition-colors hover:border-accent hover:bg-accent/15"
              >
                <div className="mb-3 inline-flex rounded-lg bg-accent/15 p-2 text-accent">
                  <Sparkles size={16} />
                </div>
                <div className="mb-1 text-sm font-semibold text-heading">Generate with AI</div>
                <p className="text-xs text-muted-foreground">
                  Describe the environment and let AI lay out the first version for you.
                </p>
              </button>

              <button
                onClick={switchToManual}
                className="rounded-lg border border-default bg-elevated/40 p-4 text-left transition-colors hover:border-accent hover:bg-elevated/60"
              >
                <div className="mb-3 inline-flex rounded-lg bg-primary/10 p-2 text-primary">
                  <PencilRuler size={16} />
                </div>
                <div className="mb-1 text-sm font-semibold text-heading">Build manually</div>
                <p className="text-xs text-muted-foreground">
                  Close this prompt and use click-and-drag from the left toolbar to place devices on the canvas.
                </p>
              </button>
            </div>

          </>
        ) : (
          <>
            <div className="mb-5 text-center">
              <div className="mb-2 flex items-center justify-center gap-2">
                <Sparkles size={16} className="text-accent" />
                <h2 className="font-heading text-base font-semibold text-heading">
                  Describe your network
                </h2>
              </div>
              <p className="text-xs text-muted-foreground">
                AI will generate the topology in seconds, or you can go back and switch to manual creation.
              </p>
              <p className="mt-2 text-[11px] text-muted-foreground/80">
                Press <span className="font-medium text-primary">Esc</span>, click outside, or use the close button to build manually instead.
              </p>
            </div>

            <div className="relative mb-3">
              <textarea
                value={description}
                onChange={e => setDescription(e.target.value)}
                onKeyDown={e => {
                  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) handleGenerate()
                }}
                placeholder="e.g. Small office with a firewall, core switch, 3 access points, a file server, and 20 workstations"
                rows={3}
                disabled={loading}
                autoFocus
                className="w-full resize-none rounded-lg border border-default bg-input px-4 py-3 pb-7 text-sm text-primary placeholder:text-muted-foreground focus:border-accent focus:outline-none disabled:opacity-50"
              />
              <span className="pointer-events-none absolute bottom-2 right-3 text-[10px] text-muted-foreground">
                ⌘↵ to generate
              </span>
            </div>

            <div className="mb-4 flex flex-wrap gap-1.5">
              {EXAMPLE_PROMPTS.map(p => (
                <button
                  key={p}
                  onClick={() => handleGenerate(p)}
                  disabled={loading}
                  className="rounded-full border border-default px-3 py-1 text-xs text-muted-foreground transition-colors hover:border-accent hover:text-accent disabled:opacity-40"
                >
                  {p}
                </button>
              ))}
            </div>

            {error && <p className="mb-3 text-xs text-red-400">{error}</p>}

            <div className="flex gap-2">
              <button
                onClick={switchToManual}
                disabled={loading}
                className="flex-1 rounded-lg border border-default px-4 py-2.5 text-sm font-medium text-primary hover:border-accent hover:text-accent disabled:opacity-40"
              >
                Build Manually
              </button>
              {loading ? (
                <div className="flex flex-1 items-center justify-center gap-2 py-2.5">
                  <div className="h-4 w-4 animate-spin rounded-full border-2 border-accent border-t-transparent" />
                  <span className="text-sm text-muted-foreground">Mapping your network…</span>
                </div>
              ) : (
                <button
                  onClick={() => handleGenerate()}
                  disabled={!description.trim()}
                  className="flex flex-1 items-center justify-center gap-2 rounded-lg bg-accent px-4 py-2.5 text-sm font-medium text-white transition-opacity hover:bg-accent/90 disabled:opacity-40"
                >
                  <Sparkles size={14} />
                  Generate Diagram
                  <ArrowRight size={14} />
                </button>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  )
}
