import { useState } from 'react'
import { Sparkles, Loader2, AlertCircle } from 'lucide-react'

interface AIPromptDialogProps {
  isOpen: boolean
  onClose: () => void
  onGenerate: (prompt: string) => Promise<void>
  flowType: 'troubleshooting' | 'procedural' | 'maintenance'
}

const FLOW_TYPE_LABELS = {
  troubleshooting: 'Troubleshooting Flow',
  procedural: 'Project Flow',
  maintenance: 'Maintenance Flow',
}

export function AIPromptDialog({
  isOpen,
  onClose,
  onGenerate,
  flowType,
}: AIPromptDialogProps) {
  const [prompt, setPrompt] = useState('')
  const [isGenerating, setIsGenerating] = useState(false)
  const [error, setError] = useState<string | null>(null)

  if (!isOpen) return null

  const handleGenerate = async () => {
    if (!prompt.trim()) return
    setIsGenerating(true)
    setError(null)
    try {
      await onGenerate(prompt)
      setPrompt('')
      onClose()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Generation failed. Please try again.')
    } finally {
      setIsGenerating(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-xs"
        onClick={() => !isGenerating && onClose()}
      />

      {/* Dialog */}
      <div className="card-flat relative w-full max-w-lg p-6 shadow-xl">
        <div className="flex items-center gap-2 mb-4">
          <Sparkles className="h-5 w-5 text-primary" />
          <h2 className="text-lg font-heading font-semibold text-foreground">
            AI-Assisted {FLOW_TYPE_LABELS[flowType]}
          </h2>
        </div>

        <p className="text-sm text-muted-foreground mb-4">
          Describe what you want to build and AI will generate a starting structure for you.
        </p>

        <textarea
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          placeholder={`Example: "A flow for troubleshooting VPN connectivity issues when users can't connect to the corporate network"`}
          rows={4}
          disabled={isGenerating}
          className="w-full rounded-xl border border-border bg-background px-4 py-3 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary/30 focus:outline-hidden resize-none disabled:opacity-50"
          autoFocus
        />

        {error && (
          <div className="mt-3 flex items-start gap-2 rounded-lg bg-rose-500/10 border border-rose-500/20 px-3 py-2">
            <AlertCircle className="h-4 w-4 text-rose-400 mt-0.5 shrink-0" />
            <p className="text-sm text-rose-400">{error}</p>
          </div>
        )}

        <div className="mt-4 flex justify-end gap-3">
          <button
            onClick={onClose}
            disabled={isGenerating}
            className="rounded-[10px] bg-input border border-border px-4 py-2 text-sm text-foreground hover:border-border-hover transition-colors disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            onClick={handleGenerate}
            disabled={!prompt.trim() || isGenerating}
            className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-white hover:brightness-110 active:scale-[0.98] transition-all disabled:opacity-50"
          >
            {isGenerating ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                Generating...
              </>
            ) : (
              <>
                <Sparkles className="h-4 w-4" />
                Generate
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  )
}
