/**
 * Story Input Component - Casual & Professional Modes
 * 
 * Allows users to input their story idea and generate a comic script
 */

import type { JSX, FormEvent } from 'react';
import { useState, useCallback } from 'react';
import { Sparkles, Loader2, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useComicStore } from '@/store/comicStore';
import { generateComicScriptWithRetry } from '@/services/deepseekService';
import type { GenerateScriptOptions } from '@/types';

// Genre options
const GENRES = [
  { value: 'action', label: 'Action' },
  { value: 'comedy', label: 'Comedy' },
  { value: 'drama', label: 'Drama' },
  { value: 'scifi', label: 'Sci-Fi' },
  { value: 'fantasy', label: 'Fantasy' },
  { value: 'horror', label: 'Horror' },
  { value: 'romance', label: 'Romance' },
  { value: 'mystery', label: 'Mystery' },
  { value: 'slice-of-life', label: 'Slice of Life' },
];

// Art style options
const ART_STYLES = [
  { value: 'manga', label: 'Manga', description: 'Japanese manga style' },
  { value: 'western-comic', label: 'Western Comic', description: 'American comic book style' },
  { value: 'pixel-art', label: 'Pixel Art', description: '16-bit retro style' },
  { value: 'watercolor', label: 'Watercolor', description: 'Artistic watercolor' },
  { value: 'noir', label: 'Noir', description: 'Film noir style' },
  { value: 'chibi', label: 'Chibi', description: 'Cute anime style' },
  { value: 'sketch', label: 'Sketch', description: 'Pencil sketch' },
  { value: 'cyberpunk', label: 'Cyberpunk', description: 'Futuristic neon' },
];

// Target audience options
const AUDIENCES = [
  { value: 'general', label: 'General' },
  { value: 'children', label: 'Children' },
  { value: 'teen', label: 'Teen' },
  { value: 'mature', label: 'Mature' },
];

// Page count options
const PAGE_COUNTS = [
  { value: 4, label: '4 pages' },
  { value: 8, label: '8 pages' },
  { value: 12, label: '12 pages' },
  { value: 16, label: '16 pages' },
  { value: 24, label: '24 pages' },
];

export function StoryInput(): JSX.Element {
  const { 
    userMode, 
    storyIdea, 
    storyGenre, 
    targetAudience, 
    artStyle,
    setStoryIdea, 
    setStoryGenre, 
    setTargetAudience, 
    setArtStyle,
    setScript,
    setCharacters,
    workflow,
    setWorkflowStep,
    setWorkflowError,
    setGenerationProgress,
  } = useComicStore();

  const [isGenerating, setIsGenerating] = useState(false);
  const [localError, setLocalError] = useState<string | null>(null);

  const handleSubmit = useCallback(async (e: FormEvent) => {
    e.preventDefault();
    
    if (!storyIdea.trim()) {
      setLocalError('Please enter a story idea');
      return;
    }

    setLocalError(null);
    setIsGenerating(true);
    setWorkflowStep('generating-script');
    setGenerationProgress(0);

    try {
      const options: GenerateScriptOptions = {
        storyIdea: storyIdea.trim(),
        genre: storyGenre,
        artStyle: ART_STYLES.find(s => s.value === artStyle)?.label || artStyle,
        numPages: userMode === 'professional' ? 8 : 4,
        audience: targetAudience,
      };

      setGenerationProgress(10);
      const script = await generateComicScriptWithRetry(options);
      setGenerationProgress(100);

      // Update store with generated script
      setScript(script);
      setCharacters(script.characters);
      
      // Move to next step
      setWorkflowStep('script-review');
    } catch (error) {
      console.error('Script generation failed:', error);
      const errorMessage = error instanceof Error 
        ? error.message 
        : 'Failed to generate script. Please try again.';
      setLocalError(errorMessage);
      setWorkflowError(errorMessage);
    } finally {
      setIsGenerating(false);
    }
  }, [
    storyIdea, 
    storyGenre, 
    artStyle, 
    targetAudience, 
    userMode,
    setScript, 
    setCharacters, 
    setWorkflowStep, 
    setWorkflowError,
    setGenerationProgress,
  ]);

  const isCasual = userMode === 'casual';

  return (
    <div className="max-w-3xl mx-auto space-y-8">
      {/* Header */}
      <div className="text-center space-y-3">
        <h1 className="text-4xl font-bold tracking-tight">
          {isCasual ? "What's your story idea?" : 'Create Your Comic Script'}
        </h1>
        <p className="text-lg text-muted-foreground max-w-xl mx-auto">
          {isCasual 
            ? "Describe your comic in a few sentences and we'll generate the complete script, characters, and panels."
            : 'Provide detailed information to generate a professional comic script with full control over the output.'
          }
        </p>
      </div>

      {/* Error Display */}
      {(localError || workflow.error) && (
        <div className="bg-destructive/10 border border-destructive/30 text-destructive px-4 py-3 rounded-lg flex items-center gap-3">
          <AlertCircle className="w-5 h-5 shrink-0" />
          <p className="text-sm">{localError || workflow.error}</p>
        </div>
      )}

      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Story Idea Textarea */}
        <div className="space-y-2">
          <label htmlFor="story-idea" className="text-sm font-medium">
            Story Idea
          </label>
          <textarea
            id="story-idea"
            value={storyIdea}
            onChange={(e) => setStoryIdea(e.target.value)}
            placeholder={isCasual 
              ? "A detective investigates a mysterious disappearance in a cyberpunk city..."
              : "Provide a detailed story concept including setting, main characters, conflict, and resolution..."
            }
            disabled={isGenerating}
            className="w-full h-40 p-4 rounded-lg border bg-background resize-none focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50 disabled:cursor-not-allowed"
          />
          <p className="text-xs text-muted-foreground">
            {storyIdea.length} characters
          </p>
        </div>

        {/* Professional Mode: Additional Options */}
        {!isCasual && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-muted/50 rounded-lg border">
            {/* Genre */}
            <div className="space-y-2">
              <label htmlFor="genre" className="text-sm font-medium">
                Genre
              </label>
              <select
                id="genre"
                value={storyGenre}
                onChange={(e) => setStoryGenre(e.target.value)}
                disabled={isGenerating}
                className="w-full p-2 rounded-md border bg-background focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
              >
                {GENRES.map((g) => (
                  <option key={g.value} value={g.value}>{g.label}</option>
                ))}
              </select>
            </div>

            {/* Art Style */}
            <div className="space-y-2">
              <label htmlFor="art-style" className="text-sm font-medium">
                Art Style
              </label>
              <select
                id="art-style"
                value={artStyle}
                onChange={(e) => setArtStyle(e.target.value)}
                disabled={isGenerating}
                className="w-full p-2 rounded-md border bg-background focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
              >
                {ART_STYLES.map((s) => (
                  <option key={s.value} value={s.value}>{s.label}</option>
                ))}
              </select>
            </div>

            {/* Target Audience */}
            <div className="space-y-2">
              <label htmlFor="audience" className="text-sm font-medium">
                Target Audience
              </label>
              <select
                id="audience"
                value={targetAudience}
                onChange={(e) => setTargetAudience(e.target.value)}
                disabled={isGenerating}
                className="w-full p-2 rounded-md border bg-background focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
              >
                {AUDIENCES.map((a) => (
                  <option key={a.value} value={a.value}>{a.label}</option>
                ))}
              </select>
            </div>

            {/* Page Count */}
            <div className="space-y-2">
              <label htmlFor="page-count" className="text-sm font-medium">
                Page Count
              </label>
              <select
                id="page-count"
                defaultValue={8}
                disabled={isGenerating}
                className="w-full p-2 rounded-md border bg-background focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"
              >
                {PAGE_COUNTS.map((p) => (
                  <option key={p.value} value={p.value}>{p.label}</option>
                ))}
              </select>
            </div>
          </div>
        )}

        {/* Casual Mode: Hidden defaults */}
        {isCasual && (
          <div className="flex items-center justify-center gap-4 text-sm text-muted-foreground">
            <span>Genre: {GENRES.find(g => g.value === storyGenre)?.label}</span>
            <span>•</span>
            <span>Style: {ART_STYLES.find(s => s.value === artStyle)?.label}</span>
          </div>
        )}

        {/* Submit Button */}
        <Button 
          type="submit" 
          className="w-full" 
          size="lg"
          disabled={isGenerating || !storyIdea.trim()}
        >
          {isGenerating ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              Generating Script...
            </>
          ) : (
            <>
              <Sparkles className="w-4 h-4 mr-2" />
              {isCasual ? 'Generate Comic' : 'Generate Script'}
            </>
          )}
        </Button>

        {/* Progress Bar */}
        {isGenerating && (
          <div className="space-y-2">
            <div className="h-2 bg-muted rounded-full overflow-hidden">
              <div 
                className="h-full bg-primary transition-all duration-500"
                style={{ width: `${workflow.generationProgress}%` }}
              />
            </div>
            <p className="text-center text-sm text-muted-foreground">
              {workflow.generationProgress < 30 && 'Analyzing your story idea...'}
              {workflow.generationProgress >= 30 && workflow.generationProgress < 60 && 'Creating characters and plot...'}
              {workflow.generationProgress >= 60 && workflow.generationProgress < 90 && 'Structuring panels and dialogue...'}
              {workflow.generationProgress >= 90 && 'Finalizing script...'}
            </p>
          </div>
        )}
      </form>
    </div>
  );
}
