import { useState, useEffect } from 'react';
import { api } from '../lib/api';
import type { TTSPreferences, ProviderOptionsResponse, TTSModel, TTSStylePreset } from '../types/api';

interface TTSSettingsPanelProps {
  preferences: TTSPreferences;
  onChange: (preferences: TTSPreferences) => void;
  disabled?: boolean;
}

export function TTSSettingsPanel({ preferences, onChange, disabled }: TTSSettingsPanelProps) {
  const [options, setOptions] = useState<ProviderOptionsResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch TTS options on mount
  useEffect(() => {
    const fetchOptions = async () => {
      try {
        setLoading(true);
        const data = await api.getTTSOptions('gemini');
        setOptions(data);
        setError(null);
      } catch (err) {
        console.error('Failed to fetch TTS options:', err);
        setError('Failed to load TTS options');
      } finally {
        setLoading(false);
      }
    };

    fetchOptions();
  }, []);

  if (loading) {
    return (
      <div className="space-y-4 animate-pulse">
        <div className="bg-gray-100 rounded-lg h-20"></div>
        <div className="bg-gray-100 rounded-lg h-24"></div>
        <div className="bg-gray-100 rounded-lg h-20"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-red-600 text-sm p-4 bg-red-50 rounded-lg">
        {error}
      </div>
    );
  }

  if (!options || !options.models || !options.style_presets || !options.speed_range) return null;

  return (
    <div className="space-y-4">
      {/* Model Selection */}
      <div className="bg-gray-50 rounded-lg p-4">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Quality / Model
        </label>
        <p className="text-xs text-gray-500 mb-3">
          Flash is faster and more cost-efficient. Pro offers higher quality output.
        </p>
        <select
          value={preferences.model}
          onChange={(e) => onChange({ ...preferences, model: e.target.value as TTSModel })}
          disabled={disabled}
          className="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 disabled:bg-gray-100 disabled:text-gray-500"
        >
          {options.models.map((m) => (
            <option key={m.value} value={m.value}>
              {m.label}
            </option>
          ))}
        </select>
      </div>

      {/* Speed Slider */}
      <div className="bg-gray-50 rounded-lg p-4">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Speed: {preferences.speed.toFixed(1)}x
        </label>
        <p className="text-xs text-gray-500 mb-3">
          Adjust the speech rate. 1.0x is normal speed.
        </p>
        <input
          type="range"
          min={options.speed_range.min}
          max={options.speed_range.max}
          step={options.speed_range.step}
          value={preferences.speed}
          onChange={(e) => onChange({ ...preferences, speed: parseFloat(e.target.value) })}
          disabled={disabled}
          className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer disabled:cursor-not-allowed"
        />
        <div className="flex justify-between text-xs text-gray-500 mt-1">
          <span>{options.speed_range.min}x (Slow)</span>
          <span>1.0x (Normal)</span>
          <span>{options.speed_range.max}x (Fast)</span>
        </div>
      </div>

      {/* Style Preset */}
      <div className="bg-gray-50 rounded-lg p-4">
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Speaking Style
        </label>
        <p className="text-xs text-gray-500 mb-3">
          Choose a preset style or create a custom prompt for the voice.
        </p>
        <select
          value={preferences.style_preset}
          onChange={(e) => onChange({
            ...preferences,
            style_preset: e.target.value as TTSStylePreset
          })}
          disabled={disabled}
          className="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 disabled:bg-gray-100 disabled:text-gray-500"
        >
          {options.style_presets.map((s) => (
            <option key={s.value} value={s.value}>
              {s.label}
            </option>
          ))}
        </select>
      </div>

      {/* Custom Style Prompt (shown when style_preset === "custom") */}
      {preferences.style_preset === "custom" && (
        <div className="bg-gray-50 rounded-lg p-4">
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Custom Style Prompt
          </label>
          <p className="text-xs text-gray-500 mb-3">
            Describe how you want the voice to sound. Be specific about tone, pace, and emotion.
          </p>
          <textarea
            value={preferences.custom_style_prompt || ""}
            onChange={(e) => onChange({
              ...preferences,
              custom_style_prompt: e.target.value
            })}
            placeholder="E.g., Speak in a mysterious, suspenseful tone with dramatic pauses. Use a deep, resonant voice as if narrating a thriller documentary."
            disabled={disabled}
            rows={3}
            className="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 disabled:bg-gray-100 disabled:text-gray-500"
          />
        </div>
      )}
    </div>
  );
}
