import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { apiClient } from '../lib/api';

type LanguageOutput = {
  captions_vtt_url?: string;
  audio_description_vtt_url?: string;
  accessible_video_mp4_url?: string;
  audio_description_mp3_url?: string;
};

type JobPreview = {
  job_id: string;
  job_title: string;
  job_status: string;
  source_language: string;
  languages: string[];
  language_outputs: Record<string, LanguageOutput>;
};

export function ShareView() {
  const { token } = useParams<{ token: string }>();
  const [preview, setPreview] = useState<JobPreview | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedLang, setSelectedLang] = useState('');

  useEffect(() => {
    if (!token) return;
    apiClient.getPublicJobPreview(token)
      .then((data) => {
        setPreview(data);
        setSelectedLang(data.source_language || data.languages[0] || '');
      })
      .catch((e) => {
        const status = e?.response?.status;
        if (status === 404) setError('This share link is not valid or has been revoked.');
        else if (status === 410) setError('This share link has expired.');
        else setError('Failed to load preview. Please try again later.');
      })
      .finally(() => setLoading(false));
  }, [token]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-gray-500 text-sm">Loading…</div>
      </div>
    );
  }

  if (error || !preview) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center max-w-md px-4">
          <div className="text-4xl mb-4">🔒</div>
          <h1 className="text-xl font-semibold text-gray-800 mb-2">Link unavailable</h1>
          <p className="text-gray-500 text-sm">{error}</p>
        </div>
      </div>
    );
  }

  const langOut = preview.language_outputs[selectedLang] ?? {};

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white border-b border-gray-200 px-6 py-4">
        <div className="max-w-5xl mx-auto flex items-center justify-between">
          <div>
            <h1 className="text-xl font-semibold text-gray-900">{preview.job_title}</h1>
            <p className="text-sm text-gray-500 mt-0.5">Read-only preview · Shared by Oliver</p>
          </div>
          <span className="text-xs px-2 py-1 bg-gray-100 text-gray-600 rounded-full">{preview.job_status.replace(/_/g, ' ')}</span>
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-6 py-8 space-y-6">
        {/* Language selector */}
        {preview.languages.length > 1 && (
          <div className="flex items-center gap-3">
            <span className="text-sm font-medium text-gray-700">Language:</span>
            <div className="flex gap-2 flex-wrap">
              {preview.languages.map((lang) => (
                <button
                  key={lang}
                  onClick={() => setSelectedLang(lang)}
                  className={`px-3 py-1 text-sm rounded-full border transition-colors ${
                    selectedLang === lang
                      ? 'bg-indigo-600 text-white border-indigo-600'
                      : 'bg-white text-gray-600 border-gray-300 hover:border-indigo-400'
                  }`}
                >
                  {lang.toUpperCase()}
                  {lang === preview.source_language && <span className="ml-1 opacity-60">(source)</span>}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Video player */}
        {langOut.accessible_video_mp4_url ? (
          <div className="bg-black rounded-xl overflow-hidden">
            <video
              key={langOut.accessible_video_mp4_url}
              controls
              className="w-full max-h-[60vh]"
              src={langOut.accessible_video_mp4_url}
            />
          </div>
        ) : (
          <div className="bg-gray-100 rounded-xl h-48 flex items-center justify-center text-gray-400 text-sm">
            No accessible video available for {selectedLang.toUpperCase()}
          </div>
        )}

        {/* Downloads */}
        <div className="bg-white border border-gray-200 rounded-xl p-5">
          <h2 className="text-sm font-semibold text-gray-700 mb-4">Downloads — {selectedLang.toUpperCase()}</h2>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
            {langOut.captions_vtt_url && (
              <a
                href={langOut.captions_vtt_url}
                download={`captions-${selectedLang}.vtt`}
                className="flex flex-col items-center gap-2 p-3 border border-gray-200 rounded-lg hover:border-indigo-400 hover:bg-indigo-50 transition-colors text-center"
              >
                <span className="text-2xl">📄</span>
                <span className="text-xs text-gray-700 font-medium">Captions VTT</span>
              </a>
            )}
            {langOut.audio_description_vtt_url && (
              <a
                href={langOut.audio_description_vtt_url}
                download={`ad-${selectedLang}.vtt`}
                className="flex flex-col items-center gap-2 p-3 border border-gray-200 rounded-lg hover:border-indigo-400 hover:bg-indigo-50 transition-colors text-center"
              >
                <span className="text-2xl">📝</span>
                <span className="text-xs text-gray-700 font-medium">Audio Description VTT</span>
              </a>
            )}
            {langOut.audio_description_mp3_url && (
              <a
                href={langOut.audio_description_mp3_url}
                download={`ad-${selectedLang}.mp3`}
                className="flex flex-col items-center gap-2 p-3 border border-gray-200 rounded-lg hover:border-indigo-400 hover:bg-indigo-50 transition-colors text-center"
              >
                <span className="text-2xl">🔊</span>
                <span className="text-xs text-gray-700 font-medium">AD Audio MP3</span>
              </a>
            )}
            {langOut.accessible_video_mp4_url && (
              <a
                href={langOut.accessible_video_mp4_url}
                download={`accessible-video-${selectedLang}.mp4`}
                className="flex flex-col items-center gap-2 p-3 border border-gray-200 rounded-lg hover:border-indigo-400 hover:bg-indigo-50 transition-colors text-center"
              >
                <span className="text-2xl">🎬</span>
                <span className="text-xs text-gray-700 font-medium">Accessible Video MP4</span>
              </a>
            )}
            {!langOut.captions_vtt_url && !langOut.audio_description_vtt_url && !langOut.accessible_video_mp4_url && (
              <p className="col-span-4 text-sm text-gray-400 italic">No files available for this language yet.</p>
            )}
          </div>
        </div>

        <p className="text-xs text-gray-400 text-center">
          This is a read-only preview link. To request revisions, contact your Oliver project manager.
        </p>
      </div>
    </div>
  );
}
