'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'react-hot-toast';
import { Wand2, Copy, Check, Sparkles, RefreshCw } from 'lucide-react';
import { modulesApi } from '@/lib/api';

const styles = [
  { value: 'cinematic', label: 'Cinematic', description: 'Movie-like scenes with dramatic lighting' },
  { value: 'photographic', label: 'Photographic', description: 'Professional photography style' },
  { value: 'artistic', label: 'Artistic', description: 'Painterly with rich colors' },
  { value: 'product', label: 'Product', description: 'Commercial product photography' },
  { value: 'fantasy', label: 'Fantasy', description: 'Magical and otherworldly' },
  { value: 'minimal', label: 'Minimal', description: 'Clean and simple' },
  { value: 'vintage', label: 'Vintage', description: 'Nostalgic retro aesthetics' },
  { value: 'futuristic', label: 'Futuristic', description: 'Sci-fi and modern tech' },
];

export default function PromptStudioPage() {
  const router = useRouter();
  const [prompt, setPrompt] = useState('');
  const [style, setStyle] = useState('cinematic');
  const [enhancedPrompt, setEnhancedPrompt] = useState('');
  const [negativePrompt, setNegativePrompt] = useState('');
  const [loading, setLoading] = useState(false);
  const [copied, setCopied] = useState<string | null>(null);

  const handleEnhance = async () => {
    if (!prompt.trim()) {
      toast.error('Please enter a prompt');
      return;
    }

    setLoading(true);

    try {
      const response = await modulesApi.enhancePrompt({
        prompt,
        style,
      });

      setEnhancedPrompt(response.data.enhanced_prompt);
      setNegativePrompt(response.data.negative_prompt);
      toast.success('Prompt enhanced!');
    } catch (err: any) {
      toast.error(err.response?.data?.detail || 'Failed to enhance prompt');
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = (text: string, field: string) => {
    navigator.clipboard.writeText(text);
    setCopied(field);
    toast.success('Copied to clipboard!');
    setTimeout(() => setCopied(null), 2000);
  };

  const useEnhancedPrompt = () => {
    setPrompt(enhancedPrompt);
    toast.success('Enhanced prompt moved to input');
  };

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      <div className="flex items-center gap-4">
        <div className="w-12 h-12 bg-forge-yellow/10 rounded-lg flex items-center justify-center">
          <Wand2 className="w-6 h-6 text-forge-yellow" />
        </div>
        <div>
          <h1 className="text-2xl font-bold text-white">Prompt Studio</h1>
          <p className="text-gray-500">Enhance your prompts with AI assistance</p>
        </div>
      </div>

      {/* Input Section */}
      <div className="bg-forge-dark rounded-xl border border-gray-800 p-6 space-y-6">
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-2">
            Your Prompt
          </label>
          <textarea
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            placeholder="Enter a basic prompt to enhance..."
            className="input-field min-h-[120px] resize-none"
          />
        </div>

        {/* Style Selection */}
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-3">
            Enhancement Style
          </label>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {styles.map((s) => (
              <button
                key={s.value}
                onClick={() => setStyle(s.value)}
                className={`p-3 rounded-lg text-left transition-all ${style === s.value
                  ? 'bg-forge-yellow/10 border-forge-yellow text-white border'
                  : 'bg-forge-gray border border-gray-700 text-gray-400 hover:border-gray-600'
                  }`}
              >
                <p className="font-medium text-sm">{s.label}</p>
                <p className="text-xs mt-1 opacity-70">{s.description}</p>
              </button>
            ))}
          </div>
        </div>

        <button
          onClick={handleEnhance}
          disabled={loading || !prompt.trim()}
          className="btn-primary w-full flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {loading ? (
            <>
              <RefreshCw className="w-5 h-5 animate-spin" />
              Enhancing...
            </>
          ) : (
            <>
              <Sparkles className="w-5 h-5" />
              Enhance Prompt
            </>
          )}
        </button>
      </div>

      {/* Results Section */}
      {(enhancedPrompt || negativePrompt) && (
        <div className="space-y-6">
          {/* Enhanced Prompt */}
          <div className="bg-forge-dark rounded-xl border border-gray-800 p-6">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-white font-medium">Enhanced Prompt</h3>
              <div className="flex items-center gap-2">
                <button
                  onClick={useEnhancedPrompt}
                  className="text-sm text-forge-yellow hover:text-yellow-400 flex items-center gap-1"
                >
                  <RefreshCw className="w-3 h-3" />
                  Use as input
                </button>
                <button
                  onClick={() => router.push(`/image/generate?prompt=${encodeURIComponent(enhancedPrompt)}`)}
                  className="text-sm text-blue-400 hover:text-blue-300 flex items-center gap-1"
                >
                  <Sparkles className="w-3 h-3" />
                  Generate Image
                </button>
                <button
                  onClick={() => copyToClipboard(enhancedPrompt, 'enhanced')}
                  className="p-2 text-gray-400 hover:text-forge-yellow transition-colors"
                >
                  {copied === 'enhanced' ? (
                    <Check className="w-4 h-4" />
                  ) : (
                    <Copy className="w-4 h-4" />
                  )}
                </button>
              </div>
            </div>
            <p className="text-gray-300 whitespace-pre-wrap">{enhancedPrompt}</p>
          </div>

          {/* Negative Prompt */}
          <div className="bg-forge-dark rounded-xl border border-gray-800 p-6">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-white font-medium">Negative Prompt</h3>
              <button
                onClick={() => copyToClipboard(negativePrompt, 'negative')}
                className="p-2 text-gray-400 hover:text-forge-yellow transition-colors"
              >
                {copied === 'negative' ? (
                  <Check className="w-4 h-4" />
                ) : (
                  <Copy className="w-4 h-4" />
                )}
              </button>
            </div>
            <p className="text-gray-300 whitespace-pre-wrap">{negativePrompt}</p>
          </div>
        </div>
      )}

      {/* Tips */}
      <div className="bg-forge-gray rounded-xl p-6">
        <h3 className="text-white font-medium mb-3">Tips for Better Prompts</h3>
        <ul className="space-y-2 text-gray-400 text-sm">
          <li>• Be specific about subjects, actions, and settings</li>
          <li>• Include mood, lighting, and atmosphere details</li>
          <li>• Mention art styles or artist references if desired</li>
          <li>• Use the negative prompt to exclude unwanted elements</li>
          <li>• Iterate by using enhanced prompts as new input</li>
        </ul>
      </div>
    </div>
  );
}
