import { useState } from 'react'
import { Terminal, Copy, Check, Loader2, Play, ChevronDown, ChevronRight } from 'lucide-react'
import { scriptsApi } from '@/api'
import { PowerShellHighlighter } from '@/components/scripts/PowerShellHighlighter'
import { toast } from '@/lib/toast'
import type { StepResponseRequest } from '@/types/ai-session'

interface InSessionScriptGeneratorProps {
  templateId: string
  preFilledParams: Record<string, string>
  instructions: string
  sessionId: string
  onRespond: (response: StepResponseRequest) => void
}

export function InSessionScriptGenerator({
  templateId,
  preFilledParams,
  instructions,
  sessionId,
  onRespond,
}: InSessionScriptGeneratorProps) {
  const [params, setParams] = useState<Record<string, string>>(preFilledParams)
  const [generatedScript, setGeneratedScript] = useState<string | null>(null)
  const [isGenerating, setIsGenerating] = useState(false)
  const [copied, setCopied] = useState(false)
  const [showParams, setShowParams] = useState(true)

  const handleGenerate = async () => {
    setIsGenerating(true)
    try {
      const result = await scriptsApi.generate({
        template_id: templateId,
        parameters: params,
        ai_session_id: sessionId,
      })
      setGeneratedScript(result.script)
      setShowParams(false)
      toast.success('Script generated')
    } catch {
      toast.error('Failed to generate script')
    } finally {
      setIsGenerating(false)
    }
  }

  const handleCopy = async () => {
    if (!generatedScript) return
    await navigator.clipboard.writeText(generatedScript)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const handleContinue = (success: boolean) => {
    onRespond({
      action_result: {
        success,
        details: success
          ? 'Script generated and executed'
          : 'Script generated but action did not resolve the issue',
      },
    })
  }

  return (
    <div className="mt-3 rounded-xl border border-primary/20 bg-primary/5 p-3 sm:p-4 space-y-3">
      <div className="flex items-center gap-2">
        <Terminal size={14} className="text-primary" />
        <span className="font-sans text-xs text-[0.625rem] uppercase tracking-wider text-primary">
          Script Generator
        </span>
      </div>

      {instructions && (
        <p className="text-xs text-muted-foreground">{instructions}</p>
      )}

      {/* Parameter editing */}
      {!generatedScript && (
        <>
          <button
            onClick={() => setShowParams(!showParams)}
            className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
          >
            {showParams ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
            Parameters ({Object.keys(params).length})
          </button>

          {showParams && Object.keys(params).length > 0 && (
            <div className="space-y-2">
              {Object.entries(params).map(([key, value]) => (
                <div key={key}>
                  <label className="block text-xs font-medium text-muted-foreground mb-1">
                    {key.replace(/_/g, ' ')}
                  </label>
                  <input
                    value={value}
                    onChange={(e) => setParams(prev => ({ ...prev, [key]: e.target.value }))}
                    className="w-full rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-[rgba(96,165,250,0.3)] focus:outline-none"
                  />
                </div>
              ))}
            </div>
          )}

          <button
            onClick={handleGenerate}
            disabled={isGenerating}
            className="w-full min-h-[44px] flex items-center justify-center gap-2 rounded-lg bg-primary text-white px-4 py-2 text-sm font-semibold hover:brightness-110 active:scale-[0.98] disabled:opacity-40 transition-all"
          >
            {isGenerating ? (
              <Loader2 size={14} className="animate-spin" />
            ) : (
              <Play size={14} />
            )}
            Generate Script
          </button>
        </>
      )}

      {/* Generated script display */}
      {generatedScript && (
        <>
          <div className="relative rounded-lg bg-card/80 border border-border overflow-hidden">
            <div className="flex items-center justify-between px-3 py-1.5 border-b border-border/50">
              <span className="text-xs text-muted-foreground font-mono">PowerShell</span>
              <button
                onClick={handleCopy}
                className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
              >
                {copied ? <Check size={12} className="text-emerald-400" /> : <Copy size={12} />}
                {copied ? 'Copied' : 'Copy'}
              </button>
            </div>
            <div className="p-3 overflow-x-auto max-h-[300px] overflow-y-auto">
              <PowerShellHighlighter script={generatedScript} />
            </div>
          </div>

          {/* Continue buttons */}
          <div className="flex flex-col gap-2 pt-1 sm:flex-row">
            <button
              onClick={() => handleContinue(true)}
              className="flex-1 min-h-[44px] rounded-lg bg-accent-dim border border-primary/20 px-4 py-2 text-sm font-medium text-primary hover:bg-primary/20 transition-colors"
            >
              Script worked — continue
            </button>
            <button
              onClick={() => handleContinue(false)}
              className="flex-1 min-h-[44px] rounded-lg bg-card/50 border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-card transition-colors"
            >
              Didn't resolve it
            </button>
          </div>
        </>
      )}
    </div>
  )
}
