"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 { jasonTranslator, type JasonPrompt } from "@/services/jason-translator"
import { Sparkles, Wand2, Copy, Download, Settings, CheckCircle, AlertCircle } from "lucide-react"

export function JasonEditor() {
  const [inputText, setInputText] = useState("")
  const [jasonPrompt, setJasonPrompt] = useState<JasonPrompt | null>(null)
  const [validation, setValidation] = useState<{ isValid: boolean; errors: string[]; warnings: string[] } | null>(null)

  const handleTranslate = () => {
    if (!inputText.trim()) {
      setValidation({
        isValid: false,
        errors: ['Input text is required'],
        warnings: [],
      })
      return
    }

    const result = jasonTranslator.translateToJason(inputText, {
      preferredStyle: undefined,
      preferredMood: undefined,
      includeCharacters: true,
      includeItems: true,
    })

    setJasonPrompt(result)
    setValidation(jasonTranslator.validateJasonPrompt(result))
  }

  const handleQuickTemplate = (template: 'portrait' | 'landscape' | 'action' | 'fantasy' | 'sci-fi') => {
    const result = jasonTranslator.createQuickJason(template)
    setJasonPrompt(result)
    setValidation(jasonTranslator.validateJasonPrompt(result))
    setInputText(result.prompt)
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
    // Show success message here
  }

  const downloadJason = () => {
    if (!jasonPrompt) return

    const dataStr = JSON.stringify(jasonPrompt, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'jason-prompt.json'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }

  return (
    <div className="container mx-auto px-4 py-16">
      <div className="max-w-4xl mx-auto space-y-8">
        <div className="text-center mb-8">
          <h2 className="text-3xl font-bold mb-4">Jason Language Editor</h2>
          <p className="text-gray-600">
            Convert natural language to Jason format - no AI API required! 
            Perfect for offline use and universal compatibility.
          </p>
        </div>

        <div className="grid lg:grid-cols-2 gap-8">
          {/* Input Section */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Wand2 className="h-5 w-5" />
                Natural Language Input
              </CardTitle>
              <CardDescription>
                Describe your image in plain English. The translator will automatically 
                detect style, mood, characters, and items.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <label className="text-sm font-medium mb-2 block">
                  Your Description
                </label>
                <textarea
                  className="flex min-h-[200px] w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm placeholder:text-gray-500 resize-none"
                  placeholder="A beautiful magical forest with glowing trees where a young wizard discovers an ancient crystal..."
                  value={inputText}
                  onChange={(e) => setInputText(e.target.value)}
                />
              </div>
              
              <div className="flex gap-2">
                <Button onClick={handleTranslate} className="flex-1">
                  <Sparkles className="mr-2 h-4 w-4" />
                  Translate to Jason
                </Button>
              </div>

              {/* Quick Templates */}
              <div className="pt-4 border-t border-gray-200">
                <h4 className="text-sm font-medium mb-3">Quick Templates</h4>
                <div className="grid grid-cols-2 gap-2">
                  {(['portrait', 'landscape', 'action', 'fantasy', 'sci-fi'] as const).map(template => (
                    <Button
                      key={template}
                      variant="outline"
                      size="sm"
                      onClick={() => handleQuickTemplate(template)}
                      className="capitalize"
                    >
                      {template}
                    </Button>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Jason Output Section */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Settings className="h-5 w-5" />
                Jason Language Output
              </CardTitle>
              <CardDescription>
                Universal prompt format compatible with NanoBanana, OpenAI, Midjourney, and more.
              </CardDescription>
            </CardHeader>
            <CardContent>
              {jasonPrompt ? (
                <div className="space-y-4">
                  {/* Validation Results */}
                  {validation && (
                    <div className="space-y-2">
                      {validation.isValid ? (
                        <div className="flex items-center gap-2 p-2 bg-green-50 border border-green-200 rounded-lg text-green-700 text-sm">
                          <CheckCircle className="h-4 w-4" />
                          Valid Jason prompt
                        </div>
                      ) : (
                        <div className="space-y-2">
                          {validation.errors.map((error, index) => (
                            <div key={index} className="flex items-center gap-2 p-2 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
                              <AlertCircle className="h-4 w-4" />
                              {error}
                            </div>
                          ))}
                          {validation.warnings.map((warning, index) => (
                            <div key={index} className="flex items-center gap-2 p-2 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-700 text-sm">
                              <AlertCircle className="h-4 w-4" />
                              {warning}
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  )}

                  {/* Jason Prompt Display */}
                  <div className="space-y-3">
                    <div>
                      <label className="text-sm font-medium mb-2 block">JSON Output</label>
                      <div className="p-3 bg-gray-100 rounded-lg text-sm font-mono max-h-[400px] overflow-auto">
                        {JSON.stringify(jasonPrompt, null, 2)}
                      </div>
                    </div>

                    <div className="grid grid-cols-2 gap-2">
                      <Button variant="outline" onClick={() => copyToClipboard(JSON.stringify(jasonPrompt, null, 2))}>
                        <Copy className="mr-2 h-4 w-4" />
                        Copy JSON
                      </Button>
                      <Button variant="outline" onClick={downloadJason}>
                        <Download className="mr-2 h-4 w-4" />
                        Download
                      </Button>
                    </div>
                  </div>

                  {/* Detected Elements */}
                  <div className="space-y-3 pt-4 border-t border-gray-200">
                    <h4 className="text-sm font-medium mb-2">Detected Elements</h4>
                    
                    <div className="grid md:grid-cols-2 gap-4 text-sm">
                      <div>
                        <span className="font-medium">Style:</span>
                        <span className="ml-2 bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
                          {jasonPrompt.style}
                        </span>
                      </div>
                      
                      <div>
                        <span className="font-medium">Mood:</span>
                        <span className="ml-2 bg-purple-100 text-purple-800 px-2 py-1 rounded text-xs">
                          {jasonPrompt.mood}
                        </span>
                      </div>
                      
                      <div>
                        <span className="font-medium">Characters:</span>
                        <div className="mt-1 flex flex-wrap gap-1">
                          {jasonPrompt.characters?.map(char => (
                            <span key={char} className="bg-green-100 text-green-800 px-2 py-1 rounded text-xs">
                              {char}
                            </span>
                          ))}
                        </div>
                      </div>
                      
                      <div>
                        <span className="font-medium">Color Palette:</span>
                        <div className="mt-1 flex flex-wrap gap-1">
                          {jasonPrompt.consistency?.colorPalette?.map(color => (
                            <span key={color} className="bg-gray-200 text-gray-800 px-2 py-1 rounded text-xs">
                              {color}
                            </span>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  <Settings className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>Your translated Jason prompt will appear here</p>
                  <p className="text-sm">Enter a description and click "Translate to Jason" to get started</p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Features Section */}
        <Card>
          <CardHeader>
            <CardTitle>Offline Jason Language Features</CardTitle>
            <CardDescription>
              Pattern-based translation that works completely offline
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid md:grid-cols-3 gap-6 text-sm">
              <div className="space-y-2">
                <h4 className="font-medium">🎨 Style Detection</h4>
                <ul className="space-y-1 text-gray-600">
                  <li>Realistic, Anime, Cartoon, Fantasy</li>
                  <li>Cyberpunk, Artistic, Photorealistic</li>
                  <li>Automatically detected from keywords</li>
                </ul>
              </div>
              
              <div className="space-y-2">
                <h4 className="font-medium">🎭 Mood Analysis</h4>
                <ul className="space-y-1 text-gray-600">
                  <li>Happy, Sad, Angry, Peaceful</li>
                  <li>Mysterious, Epic, Wonderful</li>
                  <li>Context-based mood detection</li>
                </ul>
              </div>
              
              <div className="space-y-2">
                <h4 className="font-medium">👥 Character & Items</h4>
                <ul className="space-y-1 text-gray-600">
                  <li>Pattern-based character extraction</li>
                  <li>Automatic item identification</li>
                  <li>Color and material analysis</li>
                </ul>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}