"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { jasonProcessor } from "@/services/jason-processor"
import { Copy, Download, Settings, Wand2, Palette, Users } from "lucide-react"

interface JasonOptimizerProps {
  originalPrompt: string
  onOptimized?: (optimizedJason: string) => void
}

export function JasonOptimizer({ originalPrompt, onOptimized }: JasonOptimizerProps) {
  const [jasonPrompt, setJasonPrompt] = useState("")
  const [style, setStyle] = useState("realistic")
  const [mood, setMood] = useState("neutral")
  const [characters, setCharacters] = useState("")
  const [colorPalette, setColorPalette] = useState("")
  const [targetService, setTargetService] = useState<"nanojason" | "nanobanana" | "openai" | "midjourney">("nanojason")
  const [validation, setValidation] = useState<{ valid: boolean; errors: string[]; warnings: string[] } | null>(null)

  const generateJason = () => {
    try {
      const characterArray = characters.split(',').map(c => c.trim()).filter(c => c)
      const colorArray = colorPalette.split(',').map(c => c.trim()).filter(c => c)

      const optimized = jasonProcessor.generateJasonFromPrompt(originalPrompt, {
        style,
        mood,
        characters: characterArray.length > 0 ? characterArray : undefined,
        consistency: {
          colorPalette: colorArray.length > 0 ? colorArray : undefined,
          characterFeatures: {
            style,
            mood,
          },
        },
        metadata: {
          targetService,
          version: "1.0",
        },
      })

      setJasonPrompt(optimized)
      
      // Validate the generated prompt
      const validationResult = jasonProcessor.validateJasonPrompt(optimized)
      setValidation(validationResult)
      
      if (onOptimized) {
        onOptimized(optimized)
      }
    } catch (error) {
      console.error('Failed to generate Jason prompt:', error)
    }
  }

  const optimizeForService = () => {
    try {
      const parsed = jasonProcessor.parseJasonPrompt(jasonPrompt)
      if (!parsed) {
        throw new Error('Invalid Jason prompt')
      }

      const optimized = jasonProcessor.optimizeForService(parsed, targetService)
      const optimizedString = JSON.stringify(optimized, null, 2)
      
      setJasonPrompt(optimizedString)
      setValidation(jasonProcessor.validateJasonPrompt(optimizedString))
      
      if (onOptimized) {
        onOptimized(optimizedString)
      }
    } catch (error) {
      console.error('Failed to optimize for service:', error)
    }
  }

  const copyToClipboard = () => {
    navigator.clipboard.writeText(jasonPrompt)
    // Add toast notification here
  }

  const downloadJason = () => {
    const blob = new Blob([jasonPrompt], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'jason-prompt.json'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const commonStyles = [
    "realistic", "anime", "cartoon", "fantasy", 
    "cyberpunk", "artistic", "painterly", "photorealistic"
  ]

  const commonMoods = [
    "happy", "sad", "angry", "peaceful", "mysterious", 
    "epic", "wonderful", "dramatic", "romantic", "tense"
  ]

  const commonServices = [
    { value: "nanojason", label: "NanoJason" },
    { value: "nanobanana", label: "NanoBanana" },
    { value: "openai", label: "OpenAI DALL-E" },
    { value: "midjourney", label: "Midjourney" },
  ]

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Wand2 className="h-5 w-5" />
          Jason Prompt Optimizer
        </CardTitle>
        <CardDescription>
          Convert your prompt to Jason language format and optimize for different AI services
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Configuration */}
        <div className="grid md:grid-cols-2 gap-4">
          <div>
            <label className="text-sm font-medium mb-2 block">
              Art Style
            </label>
            <div className="flex flex-wrap gap-2">
              {commonStyles.map(s => (
                <button
                  key={s}
                  className={`px-3 py-1 rounded-full text-sm transition-colors ${
                    style === s 
                      ? "bg-primary text-primary-foreground" 
                      : "bg-muted hover:bg-muted/80"
                  }`}
                  onClick={() => setStyle(s)}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>

          <div>
            <label className="text-sm font-medium mb-2 block">
              Mood
            </label>
            <div className="flex flex-wrap gap-2">
              {commonMoods.map(m => (
                <button
                  key={m}
                  className={`px-3 py-1 rounded-full text-sm transition-colors ${
                    mood === m 
                      ? "bg-accent text-accent-foreground" 
                      : "bg-muted hover:bg-muted/80"
                  }`}
                  onClick={() => setMood(m)}
                >
                  {m}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Characters Input */}
        <div>
          <label className="text-sm font-medium mb-2 flex items-center gap-2">
            <Users className="h-4 w-4" />
            Characters (comma-separated)
          </label>
          <Input
            placeholder="hero, villain, sidekick..."
            value={characters}
            onChange={(e) => setCharacters(e.target.value)}
          />
        </div>

        {/* Color Palette */}
        <div>
          <label className="text-sm font-medium mb-2 flex items-center gap-2">
            <Palette className="h-4 w-4" />
            Color Palette (comma-separated)
          </label>
          <Input
            placeholder="blue, gold, green..."
            value={colorPalette}
            onChange={(e) => setColorPalette(e.target.value)}
          />
        </div>

        {/* Target Service */}
        <div>
          <label className="text-sm font-medium mb-2 block">
            Target Service
          </label>
          <div className="grid grid-cols-2 gap-2">
            {commonServices.map(service => (
              <button
                key={service.value}
                className={`px-3 py-2 rounded-lg text-sm transition-colors ${
                  targetService === service.value 
                    ? "bg-primary text-primary-foreground" 
                    : "bg-muted hover:bg-muted/80"
                }`}
                onClick={() => setTargetService(service.value as any)}
              >
                {service.label}
              </button>
            ))}
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex gap-2">
          <Button onClick={generateJason} className="btn-primary">
            <Wand2 className="mr-2 h-4 w-4" />
            Generate Jason
          </Button>
          <Button 
            variant="outline" 
            onClick={optimizeForService}
            disabled={!jasonPrompt}
          >
            <Settings className="mr-2 h-4 w-4" />
            Optimize
          </Button>
        </div>

        {/* Generated Jason Prompt */}
        {jasonPrompt && (
          <div className="space-y-4">
            <div>
              <div className="flex justify-between items-center mb-2">
                <label className="text-sm font-medium">Generated Jason Prompt</label>
                <div className="flex gap-1">
                  <Button variant="ghost" size="sm" onClick={copyToClipboard}>
                    <Copy className="h-3 w-3" />
                  </Button>
                  <Button variant="ghost" size="sm" onClick={downloadJason}>
                    <Download className="h-3 w-3" />
                  </Button>
                </div>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <pre className="text-sm font-mono whitespace-pre-wrap">
                  {jasonPrompt}
                </pre>
              </div>
            </div>

            {/* Validation */}
            {validation && (
              <div className="space-y-2">
                {validation.valid ? (
                  <div className="p-3 bg-green-50 border border-green-200 rounded-lg text-green-700 text-sm">
                    ✓ Valid Jason prompt
                  </div>
                ) : (
                  <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
                    ✗ Invalid Jason prompt
                  </div>
                )}
                
                {validation.warnings.length > 0 && (
                  <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-700 text-sm">
                    <div className="font-medium mb-1">Warnings:</div>
                    <ul className="list-disc list-inside space-y-1">
                      {validation.warnings.map((warning, index) => (
                        <li key={index}>{warning}</li>
                      ))}
                    </ul>
                  </div>
                )}
                
                {validation.errors.length > 0 && (
                  <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
                    <div className="font-medium mb-1">Errors:</div>
                    <ul className="list-disc list-inside space-y-1">
                      {validation.errors.map((error, index) => (
                        <li key={index}>{error}</li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  )
}