import { useState } from 'preact/hooks';
import type { MediaType } from '../types/index.js';
import './Modal.css';

interface NewRecommendationModalProps {
  onClose: () => void;
  onSubmit: (body: {
    main_prompt: string;
    liked_shows: string;
    disliked_shows: string;
    themes: string;
    brainstorm_count?: number;
    media_type: MediaType;
    use_web_search?: boolean;
    use_validator?: boolean;
    hard_requirements?: boolean;
    self_expansive?: boolean;
    expansive_passes?: number;
    expansive_mode?: 'soft' | 'extreme';
  }) => Promise<void>;
}

export function NewRecommendationModal({ onClose, onSubmit }: NewRecommendationModalProps) {
  const [step, setStep] = useState<'type' | 'form'>('type');
  const [mediaType, setMediaType] = useState<MediaType>('tv_show');
  const [mainPrompt, setMainPrompt] = useState('');
  const [likedShows, setLikedShows] = useState('');
  const [dislikedShows, setDislikedShows] = useState('');
  const [themes, setThemes] = useState('');
  const [brainstormCount, setBrainstormCount] = useState(100);
  const [useWebSearch, setUseWebSearch] = useState(false);
  const [useValidator, setUseValidator] = useState(false);
  const [useHardRequirements, setUseHardRequirements] = useState(false);
  const [selfExpansive, setSelfExpansive] = useState(false);
  const [expansivePasses, setExpansivePasses] = useState(2);
  const [expansiveMode, setExpansiveMode] = useState<'soft' | 'extreme'>('soft');
  const [loading, setLoading] = useState(false);

  const mediaLabel = mediaType === 'movie' ? 'Movie' : 'TV Show';
  const mediaPluralLabel = mediaType === 'movie' ? 'movies' : 'shows';

  const handleSelectType = (type: MediaType) => {
    setMediaType(type);
    setStep('form');
  };

  const handleWebSearchToggle = () => {
    const next = !useWebSearch;
    setUseWebSearch(next);
    if (!next) setUseValidator(false);
  };

  const handleSubmit = async (e: Event) => {
    e.preventDefault();
    if (!mainPrompt.trim()) return;
    setLoading(true);
    try {
      await onSubmit({
        main_prompt: mainPrompt.trim(),
        liked_shows: likedShows.trim(),
        disliked_shows: dislikedShows.trim(),
        themes: themes.trim(),
        brainstorm_count: brainstormCount,
        media_type: mediaType,
        use_web_search: useWebSearch,
        use_validator: useValidator,
        hard_requirements: useHardRequirements,
        self_expansive: selfExpansive,
        expansive_passes: selfExpansive ? expansivePasses : 1,
        expansive_mode: expansiveMode,
      });
      onClose();
    } finally {
      setLoading(false);
    }
  };

  const handleBackdropClick = (e: MouseEvent) => {
    if ((e.target as HTMLElement).classList.contains('modal-backdrop')) {
      onClose();
    }
  };

  return (
    <div class="modal-backdrop" onClick={handleBackdropClick}>
      <div class="modal">
        {step === 'type' ? (
          <>
            <div class="modal-header">
              <h2>New Recommendation</h2>
              <button class="modal-close" onClick={onClose} aria-label="Close">×</button>
            </div>
            <div class="modal-type-select">
              <p class="modal-type-hint">What would you like recommendations for?</p>
              <div class="modal-type-cards">
                <button class="type-card" onClick={() => handleSelectType('tv_show')}>
                  <span class="type-card-icon">📺</span>
                  <span class="type-card-label">TV Shows</span>
                  <span class="type-card-desc">Series &amp; episodic content</span>
                </button>
                <button class="type-card" onClick={() => handleSelectType('movie')}>
                  <span class="type-card-icon">🎬</span>
                  <span class="type-card-label">Movies</span>
                  <span class="type-card-desc">Feature films &amp; cinema</span>
                </button>
              </div>
            </div>
          </>
        ) : (
          <>
            <div class="modal-header">
              <div class="modal-header-left">
                <button class="modal-back" onClick={() => setStep('type')} aria-label="Back">←</button>
                <h2>New {mediaLabel} Recommendation</h2>
              </div>
              <button class="modal-close" onClick={onClose} aria-label="Close">×</button>
            </div>

            <form class="modal-form" onSubmit={handleSubmit}>
              <div class="form-group">
                <label for="main-prompt">What are you looking for?</label>
                <textarea
                  id="main-prompt"
                  class="form-textarea"
                  placeholder={`Describe what you want to watch. Be as specific as you like — mood, themes, setting, what you've enjoyed before...`}
                  value={mainPrompt}
                  onInput={(e) => setMainPrompt((e.target as HTMLTextAreaElement).value)}
                  rows={5}
                  required
                />
              </div>

              <div class="form-group">
                <label for="liked-shows">{mediaLabel}s you liked</label>
                <input
                  id="liked-shows"
                  type="text"
                  class="form-input"
                  placeholder={mediaType === 'movie' ? 'e.g. Inception, The Godfather' : 'e.g. Breaking Bad, The Wire'}
                  value={likedShows}
                  onInput={(e) => setLikedShows((e.target as HTMLInputElement).value)}
                />
              </div>

              <div class="form-group">
                <label for="disliked-shows">{mediaLabel}s you disliked</label>
                <input
                  id="disliked-shows"
                  type="text"
                  class="form-input"
                  placeholder={mediaType === 'movie' ? 'e.g. Transformers' : 'e.g. Game of Thrones'}
                  value={dislikedShows}
                  onInput={(e) => setDislikedShows((e.target as HTMLInputElement).value)}
                />
              </div>

              <div class="form-group">
                <label for="themes">Themes and requirements</label>
                <input
                  id="themes"
                  type="text"
                  class="form-input"
                  placeholder="e.g. dramatic setting, historical, sci-fi, etc."
                  value={themes}
                  onInput={(e) => setThemes((e.target as HTMLInputElement).value)}
                />
              </div>

              <div class="form-group">
                <label for="brainstorm-count">{mediaLabel}s to brainstorm ({brainstormCount})</label>
                <input
                  id="brainstorm-count"
                  type="range"
                  class="form-input"
                  min={50}
                  max={200}
                  step={10}
                  value={brainstormCount}
                  onInput={(e) => setBrainstormCount(Number((e.target as HTMLInputElement).value))}
                />
              </div>

              <div class="form-group-toggle">
                <label class="toggle-label" for="web-search">
                  <div class="toggle-text">
                    <span class="toggle-title">Web Search</span>
                    <span class="toggle-desc">Use real-time web search for more accurate and up-to-date {mediaPluralLabel}</span>
                  </div>
                  <div class={`toggle-switch${useWebSearch ? ' on' : ''}`} onClick={handleWebSearchToggle}>
                    <div class="toggle-knob" />
                  </div>
                </label>
              </div>

              <div class="form-group-toggle">
                <label class={`toggle-label${!useWebSearch ? ' toggle-disabled' : ''}`}>
                  <div class="toggle-text">
                    <span class="toggle-title">Validator Agent</span>
                    <span class="toggle-desc">
                      Verify candidates against real {mediaPluralLabel} metadata using web search
                      {!useWebSearch && ' (requires Web Search)'}
                    </span>
                  </div>
                  <div
                    class={`toggle-switch${useValidator ? ' on' : ''}${!useWebSearch ? ' toggle-switch-disabled' : ''}`}
                    onClick={() => useWebSearch && setUseValidator((v) => !v)}
                  >
                    <div class="toggle-knob" />
                  </div>
                </label>
              </div>

              <div class="form-group-toggle">
                <label class="toggle-label">
                  <div class="toggle-text">
                    <span class="toggle-title">Hard Requirements</span>
                    <span class="toggle-desc">Strictly enforce all specified requirements when generating and ranking</span>
                  </div>
                  <div class={`toggle-switch${useHardRequirements ? ' on' : ''}`} onClick={() => setUseHardRequirements((v) => !v)}>
                    <div class="toggle-knob" />
                  </div>
                </label>
              </div>

              <div class="form-group-toggle">
                <label class="toggle-label">
                  <div class="toggle-text">
                    <span class="toggle-title">Self Expansive Mode</span>
                    <span class="toggle-desc">Re-run the pipeline using Full Match results to discover more great {mediaPluralLabel}</span>
                  </div>
                  <div class={`toggle-switch${selfExpansive ? ' on' : ''}`} onClick={() => setSelfExpansive((v) => !v)}>
                    <div class="toggle-knob" />
                  </div>
                </label>
              </div>

              {selfExpansive && (
                <div class="expansive-options">
                  <div class="form-group">
                    <label for="expansive-passes">Extra passes ({expansivePasses})</label>
                    <input
                      id="expansive-passes"
                      type="range"
                      class="form-input"
                      min={1}
                      max={5}
                      step={1}
                      value={expansivePasses}
                      onInput={(e) => setExpansivePasses(Number((e.target as HTMLInputElement).value))}
                    />
                  </div>
                  <div class="form-group">
                    <label>Mode</label>
                    <div class="mode-buttons">
                      <button
                        type="button"
                        class={`mode-btn${expansiveMode === 'soft' ? ' mode-btn--active' : ''}`}
                        onClick={() => setExpansiveMode('soft')}
                      >
                        Soft
                      </button>
                      <button
                        type="button"
                        class={`mode-btn${expansiveMode === 'extreme' ? ' mode-btn--active' : ''}`}
                        onClick={() => setExpansiveMode('extreme')}
                      >
                        Extreme
                      </button>
                    </div>
                    <span class="toggle-desc mode-desc">
                      {expansiveMode === 'soft'
                        ? 'Each extra pass brainstorms 60 new candidates in 2 buckets'
                        : `Each extra pass brainstorms ${brainstormCount} new candidates (same as main pass)`}
                    </span>
                  </div>
                </div>
              )}

              <div class="modal-actions">
                <button type="button" class="btn-secondary" onClick={onClose} disabled={loading}>
                  Cancel
                </button>
                <button type="submit" class="btn-primary" disabled={loading || !mainPrompt.trim()}>
                  {loading ? 'Starting…' : 'Get Recommendations'}
                </button>
              </div>
            </form>
          </>
        )}
      </div>
    </div>
  );
}
