/**
 * TextToSpeechButton Component
 * "Read aloud" button that synthesizes text and plays it via AudioPlayer.
 *
 * Accepts text as a prop, with optional voice and tier selection.
 * Shows loading state during synthesis and integrates AudioPlayer for playback.
 *
 * Follows PDA-friendly design: no aggressive colors, calm interface.
 */

import { useCallback } from "react";
import type { ReactElement } from "react";
import { useTextToSpeech } from "@/hooks/useTextToSpeech";
import type { SynthesizeOptions } from "@/hooks/useTextToSpeech";
import { AudioPlayer } from "./AudioPlayer";

export interface TextToSpeechButtonProps {
  /** The text to synthesize to speech */
  text: string;
  /** Optional voice ID to use */
  voice?: string;
  /** Optional tier (e.g. "default", "premium", "fallback") */
  tier?: string;
  /** Optional className for the container */
  className?: string;
}

/**
 * TextToSpeechButton provides a "Read aloud" button that synthesizes
 * the given text and displays an AudioPlayer for playback control.
 */
export function TextToSpeechButton({
  text,
  voice,
  tier,
  className = "",
}: TextToSpeechButtonProps): ReactElement {
  const { synthesize, audioUrl, isLoading, error } = useTextToSpeech();

  /**
   * Handle read aloud button click
   */
  const handleClick = useCallback(async (): Promise<void> => {
    let options: SynthesizeOptions | undefined;

    if (voice !== undefined || tier !== undefined) {
      options = {};
      if (voice !== undefined) options.voice = voice;
      if (tier !== undefined) options.tier = tier;
    }

    await synthesize(text, options);
  }, [text, voice, tier, synthesize]);

  return (
    <div className={`flex flex-col gap-2 ${className}`}>
      {/* Read Aloud Button */}
      <button
        type="button"
        onClick={() => void handleClick()}
        disabled={isLoading}
        aria-label={isLoading ? "Synthesizing speech" : "Read aloud"}
        className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-300 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {isLoading ? (
          <>
            {/* Spinner */}
            <svg
              className="h-4 w-4 animate-spin text-gray-500"
              viewBox="0 0 24 24"
              fill="none"
              aria-hidden="true"
            >
              <circle
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="3"
                className="opacity-25"
              />
              <path
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                className="opacity-75"
              />
            </svg>
            <span>Synthesizing...</span>
          </>
        ) : (
          <>
            {/* Speaker Icon */}
            <svg
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden="true"
            >
              <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" />
              <path d="M15.54 8.46a5 5 0 010 7.07" />
              <path d="M19.07 4.93a10 10 0 010 14.14" />
            </svg>
            <span>Read aloud</span>
          </>
        )}
      </button>

      {/* Error Display */}
      {error && (
        <p className="text-sm text-amber-600" role="alert">
          {error}
        </p>
      )}

      {/* Audio Player (shown after synthesis) */}
      {audioUrl && <AudioPlayer src={audioUrl} />}
    </div>
  );
}

export default TextToSpeechButton;
