import React from 'react';
import { ArrowDownTrayIcon } from '@heroicons/react/24/outline';
import { useTranscriptionStore } from '../stores/transcriptionStore';
import { generateSRT, generateWebVTT, downloadSubtitles } from '../utils/subtitleUtils';
import { trackDownloadSRT, sendGAEvent } from '../analytics/gaEvents';

const MediaDownloadControls: React.FC = () => {
  const {
    file,
    transcription,
    selectedLanguage,
    isVideoFile,
    isDownloadingVideo,
    handleDownloadVideoWithSubtitles,
  } = useTranscriptionStore();

  if (!transcription) {
    return null;
  }

  return (
    <div className="flex items-center space-x-2">
      <div className="tooltip tooltip-bottom" data-tip="Download subtitle file in SRT format. Compatible with most video players and editing software">
        <button
          onClick={() => {
            const srtContent = generateSRT(transcription.aligned_segments);
            const filename = file?.name?.replace(/\.[^/.]+$/, ".srt") || "subtitles.srt";
            downloadSubtitles(srtContent, filename);

            // Track SRT download
            if (selectedLanguage) {
              trackDownloadSRT(selectedLanguage);
            }
          }}
          className="flex items-center gap-1 px-2 py-1 text-xs bg-purple-600 hover:bg-purple-700 rounded transition-colors text-white"
        >
          <ArrowDownTrayIcon className="w-3 h-3" />
          .srt
        </button>
      </div>
      <div className="tooltip tooltip-bottom" data-tip="Download subtitle file in WebVTT format. Ideal for web browsers and HTML5 video players">
        <button
          onClick={() => {
            const vttContent = generateWebVTT(transcription.aligned_segments);
            const filename = file?.name?.replace(/\.[^/.]+$/, ".vtt") || "subtitles.vtt";
            downloadSubtitles(vttContent, filename);

            // Track VTT download
            if (selectedLanguage) {
              sendGAEvent("Download", "vtt", selectedLanguage);
            }
          }}
          className="flex items-center gap-1 px-2 py-1 text-xs bg-indigo-600 hover:bg-indigo-700 rounded transition-colors text-white"
        >
          <ArrowDownTrayIcon className="w-3 h-3" />
          .vtt
        </button>
      </div>
      {isVideoFile && (
        <div className="tooltip tooltip-bottom" data-tip="Download video with embedded subtitle track. Selectable from compatible media players">
          <button
            onClick={handleDownloadVideoWithSubtitles}
            disabled={isDownloadingVideo}
            className="flex items-center gap-1 px-2 py-1 text-xs bg-orange-600 hover:bg-orange-700 disabled:bg-gray-600 rounded transition-colors text-white"
          >
            <ArrowDownTrayIcon className="w-3 h-3" />
            {isDownloadingVideo ? "Creating..." : ".mp4"}
          </button>
        </div>
      )}
    </div>
  );
};

export default MediaDownloadControls;
