'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'react-hot-toast';
import {
  Sparkles, Copy, Camera, Check, Loader2, Info, Sliders,
  RefreshCw, Lock
} from 'lucide-react';
import { modulesApi } from '@/lib/api';

interface CineOption {
  value: string;
  display?: string;
  name?: string;
  tooltip?: string;
  tags?: string;
  keywords?: string;
  compatibleLenses?: string[];
  compatibleFormats?: string[];
  defaultCamera?: string;
  defaultLens?: string;
  focusType?: string;
  [key: string]: any;
}

interface CineOptions {
  cameras: CineOption[];
  lenses: CineOption[];
  applications: CineOption[];
  aspect_ratios: string[];
}

export default function CinePromptStudioPage() {
  const router = useRouter();

  // Data State
  const [options, setOptions] = useState<CineOptions | null>(null);
  const [loadingOptions, setLoadingOptions] = useState(true);

  // Selection State
  const [application, setApplication] = useState('');
  const [camera, setCamera] = useState('');
  const [lens, setLens] = useState('');
  const [aspectRatio, setAspectRatio] = useState('16:9');
  const [prompt, setPrompt] = useState('');
  const [creativeFreedom, setCreativeFreedom] = useState(0.3);

  // UI State
  const [compatibleLenses, setCompatibleLenses] = useState<CineOption[]>([]);
  const [generating, setGenerating] = useState(false);
  const [enhancedPrompt, setEnhancedPrompt] = useState('');
  const [negativePrompt, setNegativePrompt] = useState('');
  const [copied, setCopied] = useState<string | null>(null);
  const [showTooltip, setShowTooltip] = useState<string | null>(null);

  // Fetch Options on Mount
  useEffect(() => {
    const fetchOptions = async () => {
      try {
        const response = await modulesApi.getCineOptions();
        setOptions(response.data);

        // Set Defaults
        const apps = response.data.applications;
        if (apps && apps.length > 0) {
          const defaultApp = apps.find((a: any) => a.value === 'Golden Hour (Outdoor)') || apps[0];
          setApplication(defaultApp.value);
        }
      } catch (error) {
        console.error('Failed to load CineOptions:', error);
        toast.error('Failed to load studio options');
      } finally {
        setLoadingOptions(false);
      }
    };
    fetchOptions();
  }, []);

  // Update Camera/Lens when Application Changes
  useEffect(() => {
    if (!options || !application) return;

    const selectedApp = options.applications.find(a => a.value === application);
    if (selectedApp) {
      if (selectedApp.defaultCamera) setCamera(selectedApp.defaultCamera);
      if (selectedApp.defaultLens) setLens(selectedApp.defaultLens);
    }
  }, [application, options]);

  // Filter Compatible Lenses
  useEffect(() => {
    if (!options || !camera) return;

    const selectedCamera = options.cameras.find(c => c.value === camera);
    if (selectedCamera && selectedCamera.compatibleLenses) {
      const filtered = options.lenses.filter(l =>
        selectedCamera.compatibleLenses?.includes(l.value)
      );
      setCompatibleLenses(filtered);

      // Auto-select valid lens if current is invalid
      if (lens && !filtered.find(l => l.value === lens) && filtered.length > 0) {
        setLens(filtered[0].value);
      }
    } else {
      setCompatibleLenses(options.lenses);
    }
  }, [camera, options]);

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

    setGenerating(true);
    setEnhancedPrompt('');

    try {
      const response = await modulesApi.enhancePrompt({
        prompt,
        application,
        camera,
        lens,
        aspect_ratio: aspectRatio,
        creative_freedom: creativeFreedom
      });

      setEnhancedPrompt(response.data.enhanced_prompt);
      setNegativePrompt(response.data.negative_prompt);
      toast.success('Prompt optimized successfully!');
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Optimization failed');
    } finally {
      setGenerating(false);
    }
  };

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

  if (loadingOptions) {
    return (
      <div className="flex h-96 items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-forge-yellow" />
      </div>
    );
  }

  const selectedApp = options?.applications.find(a => a.value === application);
  const selectedCamera = options?.cameras.find(c => c.value === camera);
  const selectedLens = options?.lenses.find(l => l.value === lens);

  return (
    <div className="max-w-7xl mx-auto space-y-8 pb-12">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 bg-forge-yellow/10 rounded-lg flex items-center justify-center">
            <Camera className="w-6 h-6 text-forge-yellow" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">Prompt Studio Pro</h1>
            <p className="text-gray-500">Physics-based prompt engineering engine</p>
          </div>
        </div>
        <div className="text-xs text-gray-500 bg-gray-900 px-3 py-1 rounded-full border border-gray-800">
          v3.3 - Auteur Logic Enabled
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">

        {/* LEFT COLUMN: CONTROLS */}
        <div className="lg:col-span-4 space-y-6">
          <div className="bg-forge-dark rounded-xl border border-gray-800 p-6 space-y-6">
            <h2 className="text-sm font-bold text-gray-400 uppercase tracking-wider flex items-center gap-2 border-b border-gray-800 pb-2">
              <Sliders className="w-4 h-4" />
              Technical Specs
            </h2>

            {/* Application */}
            <div className="space-y-2">
              <label className="text-sm text-gray-300 font-medium">Application Context</label>
              <select
                value={application}
                onChange={(e) => setApplication(e.target.value)}
                className="w-full bg-black/50 border border-gray-700 rounded-lg px-3 py-2 text-white focus:border-forge-yellow focus:ring-1 focus:ring-forge-yellow outline-none"
              >
                {options?.applications.map((app) => (
                  <option key={app.value} value={app.value}>{app.value}</option>
                ))}
              </select>
            </div>

            {/* Camera */}
            <div className="space-y-2 relative">
              <div className="flex items-center justify-between">
                <label className="text-sm text-gray-300 font-medium">Camera Body</label>
                <button
                  onMouseEnter={() => setShowTooltip('camera')}
                  onMouseLeave={() => setShowTooltip(null)}
                  className="text-gray-500 hover:text-white"
                >
                  <Info className="w-4 h-4" />
                </button>
              </div>
              <select
                value={camera}
                onChange={(e) => setCamera(e.target.value)}
                className="w-full bg-black/50 border border-gray-700 rounded-lg px-3 py-2 text-white focus:border-forge-yellow focus:ring-1 focus:ring-forge-yellow outline-none"
              >
                {options?.cameras.map((c) => (
                  <option key={c.value} value={c.value}>{c.display}</option>
                ))}
              </select>
              <div className="text-xs text-gray-500 mt-1 truncate">
                {selectedCamera?.tags}
              </div>
              {/* Tooltip Overlay */}
              {showTooltip === 'camera' && (
                <div className="absolute z-10 bottom-full mb-2 left-0 right-0 bg-gray-900 border border-gray-700 p-3 rounded-lg shadow-xl text-xs text-gray-300">
                  {selectedCamera?.tooltip}
                </div>
              )}
            </div>

            {/* Lens */}
            <div className="space-y-2 relative">
              <div className="flex items-center justify-between">
                <label className="text-sm text-gray-300 font-medium">Lens Kit</label>
                <button
                  onMouseEnter={() => setShowTooltip('lens')}
                  onMouseLeave={() => setShowTooltip(null)}
                  className="text-gray-500 hover:text-white"
                >
                  <Info className="w-4 h-4" />
                </button>
              </div>
              <select
                value={lens}
                onChange={(e) => setLens(e.target.value)}
                className="w-full bg-black/50 border border-gray-700 rounded-lg px-3 py-2 text-white focus:border-forge-yellow focus:ring-1 focus:ring-forge-yellow outline-none"
              >
                {compatibleLenses.map((l) => (
                  <option key={l.value} value={l.value}>{l.display}</option>
                ))}
              </select>
              <div className="text-xs text-gray-500 mt-1 truncate">
                {selectedLens?.keywords}
              </div>
              {showTooltip === 'lens' && (
                <div className="absolute z-10 bottom-full mb-2 left-0 right-0 bg-gray-900 border border-gray-700 p-3 rounded-lg shadow-xl text-xs text-gray-300">
                  {selectedLens?.tooltip}
                </div>
              )}
            </div>

            {/* Aspect Ratio */}
            <div className="space-y-2">
              <label className="text-sm text-gray-300 font-medium">Aspect Ratio</label>
              <div className="grid grid-cols-3 gap-2">
                {options?.aspect_ratios.map((ratio) => (
                  <button
                    key={ratio}
                    onClick={() => setAspectRatio(ratio)}
                    className={`text-xs py-2 rounded-md transition-colors ${aspectRatio === ratio
                      ? 'bg-forge-yellow text-black font-bold'
                      : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
                      }`}
                  >
                    {ratio}
                  </button>
                ))}
              </div>
            </div>

            {/* Pro Tip */}
            <div className="bg-blue-900/20 border border-blue-900/50 rounded-lg p-3 flex items-start gap-2">
              <Info className="w-4 h-4 text-blue-400 mt-0.5 shrink-0" />
              <p className="text-xs text-blue-300">
                Selecting an Application auto-configures optimal camera/lens physics. Override manually if needed.
              </p>
            </div>

          </div>
        </div>

        {/* RIGHT COLUMN: EDITOR */}
        <div className="lg:col-span-8 space-y-6">

          {/* Creative Freedom */}
          <div className="bg-forge-dark rounded-xl border border-gray-800 p-6">
            <div className="flex items-center justify-between mb-4">
              <label className="text-sm font-bold text-gray-300 flex items-center gap-2">
                <Sparkles className="w-4 h-4 text-forge-yellow" />
                Creative Freedom
              </label>
              <span className="text-xs text-forge-yellow font-mono px-2 py-1 bg-forge-yellow/10 rounded">
                {(creativeFreedom * 100).toFixed(0)}%
              </span>
            </div>
            <input
              type="range"
              min="0"
              max="100"
              value={creativeFreedom * 100}
              onChange={(e) => setCreativeFreedom(Number(e.target.value) / 100)}
              className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-forge-yellow"
            />
            <div className="flex justify-between text-xs text-gray-500 mt-2">
              <span>Strict (Literal)</span>
              <span>Balanced</span>
              <span>Creative (Smart Fill)</span>
            </div>
          </div>

          {/* Input Area */}
          <div className="space-y-4">
            <label className="text-sm font-bold text-gray-300 block">Scene Description</label>
            <textarea
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder="Describe your scene... e.g., 'A vintage car parked in front of a neon-lit diner at dusk'"
              className="w-full h-32 bg-forge-dark border border-gray-800 rounded-xl p-4 text-white placeholder-gray-600 focus:border-forge-yellow outline-none resize-none transition-all"
            />

            <div className="flex gap-4">
              <button
                onClick={handleEnhance}
                disabled={generating || !prompt.trim()}
                className="flex-1 btn-primary py-3 flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {generating ? (
                  <>
                    <Loader2 className="w-5 h-5 animate-spin" />
                    Optimizing Physics...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-5 h-5" />
                    Optimize My Prompt
                  </>
                )}
              </button>
            </div>
          </div>

          {/* Output Area */}
          {enhancedPrompt && (
            <div className="space-y-4">
              {/* Enhanced Prompt */}
              <div className="relative group">
                <div className="absolute -inset-0.5 bg-gradient-to-r from-forge-yellow to-purple-600 rounded-xl opacity-30 group-hover:opacity-50 transition duration-1000"></div>
                <div className="relative bg-forge-dark rounded-xl border border-gray-700 p-6">
                  <div className="flex items-center justify-between mb-4 border-b border-gray-800 pb-4">
                    <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider">Physics-Optimized Prompt</h3>
                    <div className="flex gap-2">
                      <button
                        onClick={() => router.push(`/image/generate?prompt=${encodeURIComponent(enhancedPrompt)}&provider=nano-banana&model=gemini-3-pro-image-preview`)}
                        className="text-xs bg-blue-600 hover:bg-blue-500 text-white px-3 py-1.5 rounded-lg flex items-center gap-1 transition-colors"
                      >
                        <Sparkles className="w-3 h-3" />
                        Generate
                      </button>
                      <button
                        onClick={() => copyToClipboard(enhancedPrompt, 'enhanced')}
                        className="text-xs bg-gray-700 hover:bg-gray-600 text-white px-3 py-1.5 rounded-lg flex items-center gap-1 transition-colors"
                      >
                        {copied === 'enhanced' ? <Check className="w-3 h-3" /> : <Copy className="w-3 h-3" />}
                        Copy
                      </button>
                    </div>
                  </div>
                  <p className="text-gray-200 leading-relaxed font-mono text-sm whitespace-pre-wrap">
                    {enhancedPrompt}
                  </p>

                  {/* Stats */}
                  <div className="mt-4 pt-4 border-t border-gray-800 flex gap-4 text-xs text-gray-500">
                    <span>{enhancedPrompt.split(' ').length} words</span>
                    <span>Focus: {selectedApp?.focusType === 'realism' ? 'Deep Realism' : 'Stylistic'}</span>
                    <span>Sensor: {selectedCamera?.sensorFormat}</span>
                  </div>
                </div>
              </div>

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

            </div>
          )}

          {/* Current Settings Summary */}
          {!enhancedPrompt && (
            <div className="bg-gray-900/50 rounded-xl p-6 border border-gray-800">
              <div className="flex items-center justify-between mb-4">
                <span className="text-xs text-gray-500 font-bold uppercase">Current Physics Config</span>
                <span className={`text-xs px-2 py-0.5 rounded-full border ${selectedApp?.focusType === 'realism' ? 'bg-green-900/20 text-green-400 border-green-900' : 'bg-purple-900/20 text-purple-400 border-purple-900'}`}>
                  {selectedApp?.focusType === 'realism' ? 'Realism Mode' : 'Stylistic Mode'}
                </span>
              </div>
              <div className="grid grid-cols-2 gap-4 text-xs text-gray-400">
                <div><span className="text-gray-600 block mb-1">Sensor Physics</span> {selectedCamera?.physics}</div>
                <div><span className="text-gray-600 block mb-1">Optical Characteristics</span> {selectedLens?.physics}</div>
                <div><span className="text-gray-600 block mb-1">Lighting Model</span> {selectedApp?.lighting}</div>
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}
