'use client';

import { useState, useRef, KeyboardEvent } from 'react';
import { useApiKey } from '@/components/shared/ApiKeyWidget/apikey-context';
import { Section } from '@/components/shared/Section';
import { GenerationTimer } from '@/components/demo/GenerationTimer';
import { ResultCard } from '@/components/demo/ResultCard';
import { AdvancedOptionsModal, AdvancedOptionsData } from '@/components/demo/AdvancedOptionsModal';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';

// Generate random 6-character uppercase ID for pairing images
function generatePairId(): string {
  return Math.random().toString(36).substring(2, 8).toUpperCase();
}

interface GenerationResult {
  id: string;
  timestamp: Date;
  originalPrompt: string;
  enhancedPrompt?: string;
  leftImage: {
    url: string;
    width: number;
    height: number;
    error?: string;
  } | null;
  rightImage: {
    url: string;
    width: number;
    height: number;
    error?: string;
  } | null;
  durationMs?: number;
  leftData?: {
    request: object;
    response: object;
    geminiParams: object;
  };
  rightData?: {
    request: object;
    response: object;
    geminiParams: object;
  };
  enhancementOptions?: {
    template?: string;
    meta?: {
      tags?: string[];
    };
  } & AdvancedOptionsData;
}

export default function DemoTTIPage() {
  // API Key from context
  const { apiKey, apiKeyValidated, focus } = useApiKey();

  // Prompt State
  const [prompt, setPrompt] = useState('');
  const [generating, setGenerating] = useState(false);
  const [generationStartTime, setGenerationStartTime] = useState<number | undefined>();
  const [generationError, setGenerationError] = useState('');

  // Enhancement Options State
  const [aspectRatio, setAspectRatio] = useState('1:1');
  const [template, setTemplate] = useState('photorealistic');
  const [advancedOptions, setAdvancedOptions] = useState<AdvancedOptionsData>({});
  const [showAdvancedModal, setShowAdvancedModal] = useState(false);

  // Results State
  const [results, setResults] = useState<GenerationResult[]>([]);

  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // Generate Images
  const generateImages = async () => {
    if (!prompt.trim()) {
      setGenerationError('Please enter a prompt');
      return;
    }

    setGenerating(true);
    setGenerationError('');
    const startTime = Date.now();
    setGenerationStartTime(startTime);

    const resultId = Date.now().toString();
    const pairId = generatePairId(); // NEW: Generate unique pair ID
    const timestamp = new Date();

    try {
      // Call API twice in parallel
      // Left: original prompt WITHOUT enhancement (autoEnhance: false)
      // Right: original prompt WITH enhancement (autoEnhance: true + template)
      const [leftResult, rightResult] = await Promise.all([
        fetch(`${API_BASE_URL}/api/text-to-image`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-API-Key': apiKey,
          },
          body: JSON.stringify({
            prompt: prompt.trim(),
            filename: `demo_${resultId}_left`,
            aspectRatio,
            autoEnhance: false, // Explicitly disable enhancement for left image
            meta: {
              tags: [pairId, 'simple'], // NEW: Pair ID + "simple" tag
            },
          }),
        }),
        fetch(`${API_BASE_URL}/api/text-to-image`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-API-Key': apiKey,
          },
          body: JSON.stringify({
            prompt: prompt.trim(),
            filename: `demo_${resultId}_right`,
            aspectRatio,
            autoEnhance: true, // Enable enhancement for right image
            enhancementOptions: {
              template: template || 'photorealistic', // Only template parameter
            },
            meta: {
              tags: [pairId, 'enhanced'], // NEW: Pair ID + "enhanced" tag
            },
          }),
        }),
      ]);

      const leftData = await leftResult.json();
      const rightData = await rightResult.json();

      const endTime = Date.now();
      const durationMs = endTime - startTime;

      // Create result object
      const newResult: GenerationResult = {
        id: resultId,
        timestamp,
        originalPrompt: prompt.trim(),
        enhancedPrompt: rightData.data?.promptEnhancement?.enhancedPrompt,
        leftImage: leftData.success
          ? {
              url: leftData.data.url || leftData.data.filepath,
              width: 1024, // Default, would come from API
              height: 1024,
            }
          : null,
        rightImage: rightData.success
          ? {
              url: rightData.data.url || rightData.data.filepath,
              width: 1024,
              height: 1024,
            }
          : null,
        durationMs,
        // Store full request/response data for inspect mode
        leftData: {
          request: {
            prompt: prompt.trim(),
            filename: `demo_${resultId}_left`,
            aspectRatio,
            autoEnhance: false,
            meta: {
              tags: [pairId, 'simple'],
            },
          },
          response: leftData,
          geminiParams: leftData.data?.geminiParams || {},
        },
        rightData: {
          request: {
            prompt: prompt.trim(),
            filename: `demo_${resultId}_right`,
            aspectRatio,
            autoEnhance: true,
            enhancementOptions: {
              template: template || 'photorealistic',
            },
            meta: {
              tags: [pairId, 'enhanced'],
            },
          },
          response: rightData,
          geminiParams: rightData.data?.geminiParams || {},
        },
        // Store enhancement options for display in inspect mode
        enhancementOptions: {
          template,
          meta: {
            tags: [pairId, 'enhanced'],
          },
        },
      };

      if (!leftData.success) {
        newResult.leftImage = { url: '', width: 0, height: 0, error: leftData.error };
      }

      if (!rightData.success) {
        newResult.rightImage = { url: '', width: 0, height: 0, error: rightData.error };
      }

      // Add to results at the top
      setResults((prev) => [newResult, ...prev]);

      // Clear prompt
      setPrompt('');
    } catch (error) {
      setGenerationError(error instanceof Error ? error.message : 'Failed to generate images');
    } finally {
      setGenerating(false);
      setGenerationStartTime(undefined);
    }
  };

  // Handle Ctrl+Enter
  const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.ctrlKey && e.key === 'Enter') {
      e.preventDefault();
      generateImages();
    }
  };

  // Copy to clipboard
  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
  };

  // Download image
  const downloadImage = async (url: string, filename: string) => {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      const blobUrl = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = blobUrl;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(blobUrl);
    } catch (error) {
      console.error('Download failed:', error);
    }
  };

  // Reuse prompt
  const reusePrompt = (promptText: string) => {
    setPrompt(promptText);
    textareaRef.current?.focus();
  };

  return (
    <Section className="py-12 md:py-16 min-h-screen">
      {/* Page Header */}
      <header className="mb-8 md:mb-12">
        <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold text-white mb-3">
          Text-to-Image Workbench
        </h1>
        <p className="text-gray-400 text-base md:text-lg">
          Developer tool for API testing and prompt engineering
        </p>
      </header>

      {/* API Key Required Notice - Only show when not validated */}
      {!apiKeyValidated && (
        <div className="mb-6 p-5 bg-amber-900/10 border border-amber-700/50 rounded-2xl">
          <div className="flex items-center justify-between flex-wrap gap-4">
            <div>
              <h3 className="text-lg font-semibold text-white mb-1">API Key Required</h3>
              <p className="text-sm text-gray-400">Enter your API key to use this workbench</p>
            </div>
            <button
              onClick={focus}
              className="px-5 py-2.5 bg-amber-600 hover:bg-amber-700 text-white font-medium rounded-lg transition-colors"
            >
              Enter API Key
            </button>
          </div>
        </div>
      )}

      {/* Unified Prompt & Generation Card */}
      <section
        className="mb-8 p-6 bg-slate-900/80 backdrop-blur-sm border border-slate-700 rounded-2xl"
        aria-label="Image Generation"
      >
        {/* Prompt Textarea */}
        <div className="mb-4">
          <label htmlFor="prompt-input" className="block text-lg font-semibold text-white mb-3">
            Your Prompt
          </label>
          <textarea
            id="prompt-input"
            ref={textareaRef}
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Describe the image you want to generate..."
            disabled={!apiKeyValidated || generating}
            rows={4}
            className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed resize-none"
            aria-label="Image generation prompt"
          />
        </div>

        {/* Enhancement Options Row */}
        <div className="mb-4 flex flex-col md:flex-row gap-3 items-start md:items-end">
          {/* Aspect Ratio */}
          <div className="flex-1 min-w-[150px]">
            <label
              htmlFor="aspect-ratio"
              className="block text-xs font-medium text-gray-400 mb-1.5"
            >
              Aspect Ratio
            </label>
            <select
              id="aspect-ratio"
              value={aspectRatio}
              onChange={(e) => setAspectRatio(e.target.value)}
              disabled={!apiKeyValidated || generating}
              className="w-full px-3 py-2 text-sm bg-slate-800 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <option value="1:1">Square (1:1)</option>
              <option value="3:4">Portrait (3:4)</option>
              <option value="4:3">Landscape (4:3)</option>
              <option value="9:16">Vertical (9:16)</option>
              <option value="16:9">Widescreen (16:9)</option>
              <option value="21:9">Ultrawide (21:9)</option>
            </select>
          </div>

          {/* Template */}
          <div className="flex-1 min-w-[150px]">
            <label htmlFor="template" className="block text-xs font-medium text-gray-400 mb-1.5">
              Template
            </label>
            <select
              id="template"
              value={template}
              onChange={(e) => setTemplate(e.target.value)}
              disabled={!apiKeyValidated || generating}
              className="w-full px-3 py-2 text-sm bg-slate-800 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <option value="photorealistic">Photorealistic</option>
              <option value="illustration">Illustration</option>
              <option value="minimalist">Minimalist</option>
              <option value="sticker">Sticker</option>
              <option value="product">Product</option>
              <option value="comic">Comic</option>
              <option value="general">General</option>
            </select>
          </div>

          {/* Advanced Options Button - Disabled (Coming Soon) */}
          <div className="flex-1 min-w-[150px]">
            <label className="block text-xs font-medium text-gray-400 mb-1.5 md:invisible">
              Advanced
            </label>
            <div className="relative">
              <button
                disabled={true}
                className="w-full px-3 py-2 text-sm bg-slate-800 border border-slate-700 rounded-lg text-gray-500 opacity-50 cursor-not-allowed flex items-center justify-center gap-2"
                aria-label="Advanced options (coming soon)"
                title="Advanced options coming soon"
              >
                <span>⚙️</span>
                <span>Advanced</span>
                <span className="ml-1 px-1.5 py-0.5 text-xs bg-slate-700 text-gray-400 rounded-full">
                  🔒
                </span>
              </button>
            </div>
          </div>
        </div>

        {/* Generate Button & Timer */}
        <div className="flex items-center justify-between gap-4 flex-wrap pt-2 border-t border-slate-700/50">
          <div className="text-sm text-gray-500">
            {generating ? (
              <GenerationTimer isGenerating={generating} startTime={generationStartTime} />
            ) : (
              'Press Ctrl+Enter to submit'
            )}
          </div>
          <button
            onClick={generateImages}
            disabled={!apiKeyValidated || generating || !prompt.trim()}
            className="px-6 py-2.5 rounded-lg bg-gradient-to-r from-amber-600 to-orange-600 text-white font-semibold hover:from-amber-500 hover:to-orange-500 transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-amber-900/30 focus:ring-2 focus:ring-amber-500"
          >
            {generating ? 'Generating...' : 'Generate Images'}
          </button>
        </div>

        {generationError && (
          <p className="mt-3 text-sm text-red-400" role="alert">
            {generationError}
          </p>
        )}
      </section>

      {/* Advanced Options Modal */}
      <AdvancedOptionsModal
        isOpen={showAdvancedModal}
        onClose={() => setShowAdvancedModal(false)}
        value={advancedOptions}
        onChange={setAdvancedOptions}
        disabled={generating}
      />

      {/* Results Section */}
      {results.length > 0 && (
        <section className="space-y-6" aria-label="Generated Results">
          <h2 className="text-xl md:text-2xl font-bold text-white">Generated Images</h2>

          {results.map((result) => (
            <ResultCard
              key={result.id}
              result={result}
              apiKey={apiKey}
              onCopy={copyToClipboard}
              onDownload={downloadImage}
              onReusePrompt={reusePrompt}
            />
          ))}
        </section>
      )}
    </Section>
  );
}
