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

type DecisionState = 'idle' | 'submitting' | 'approved' | 'rejected' | 'error';

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('');

  // Review form state
  const [clientName, setClientName] = useState('');
  const [reviewNotes, setReviewNotes] = useState('');
  const [decisionState, setDecisionState] = useState<DecisionState>('idle');
  const [decisionError, setDecisionError] = useState<string | null>(null);

  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]);

  const handleDecision = async (action: 'approve' | 'reject') => {
    if (!token) return;
    if (action === 'reject' && !reviewNotes.trim()) {
      setDecisionError('Please describe what needs to be changed before returning to QC.');
      return;
    }
    setDecisionState('submitting');
    setDecisionError(null);
    try {
      await apiClient.submitShareDecision(token, {
        action,
        notes: reviewNotes.trim() || undefined,
        client_name: clientName.trim() || undefined,
      });
      setDecisionState(action === 'approve' ? 'approved' : 'rejected');
      if (preview) {
        setPreview({ ...preview, job_status: action === 'approve' ? 'completed' : 'qc_feedback' });
      }
    } catch (e: unknown) {
      const msg = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail;
      setDecisionError(msg || 'Failed to submit your decision. Please try again.');
      setDecisionState('error');
    }
  };

  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] ?? {};
  const isPendingReview = preview.job_status === 'pending_final_review';

  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">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>

        {/* Client review section */}
        {isPendingReview && (decisionState === 'idle' || decisionState === 'submitting' || decisionState === 'error') ? (
          <div className="bg-white border border-gray-200 rounded-xl p-6 space-y-5">
            <div>
              <h2 className="text-base font-semibold text-gray-900">Your Review</h2>
              <p className="text-sm text-gray-500 mt-1">
                Please review the materials above, then approve or return for corrections.
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Your name <span className="text-gray-400 font-normal">(optional)</span>
              </label>
              <input
                type="text"
                value={clientName}
                onChange={(e) => setClientName(e.target.value)}
                placeholder="e.g. Jane Smith"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Comments <span className="text-gray-400 font-normal">(required if returning for corrections)</span>
              </label>
              <textarea
                rows={4}
                value={reviewNotes}
                onChange={(e) => setReviewNotes(e.target.value)}
                placeholder="Leave any feedback or describe what needs to be corrected…"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none"
              />
            </div>

            {decisionError && (
              <p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
                {decisionError}
              </p>
            )}

            <div className="flex gap-3 pt-1">
              <button
                onClick={() => handleDecision('approve')}
                disabled={decisionState === 'submitting'}
                className="flex-1 px-4 py-2.5 bg-green-600 hover:bg-green-700 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"
              >
                {decisionState === 'submitting' ? 'Submitting…' : '✅ Approve'}
              </button>
              <button
                onClick={() => handleDecision('reject')}
                disabled={decisionState === 'submitting'}
                className="flex-1 px-4 py-2.5 bg-white hover:bg-red-50 disabled:opacity-50 text-red-600 border border-red-300 hover:border-red-400 text-sm font-medium rounded-lg transition-colors"
              >
                {decisionState === 'submitting' ? 'Submitting…' : '↩ Return for Corrections'}
              </button>
            </div>
          </div>
        ) : decisionState === 'approved' ? (
          <div className="bg-green-50 border border-green-200 rounded-xl p-6 text-center">
            <div className="text-4xl mb-3">✅</div>
            <h2 className="text-lg font-semibold text-green-800">Approved — thank you!</h2>
            <p className="text-sm text-green-700 mt-1">
              Your approval has been recorded. The Oliver team will be notified.
            </p>
          </div>
        ) : decisionState === 'rejected' ? (
          <div className="bg-orange-50 border border-orange-200 rounded-xl p-6 text-center">
            <div className="text-4xl mb-3">↩</div>
            <h2 className="text-lg font-semibold text-orange-800">Returned for corrections</h2>
            <p className="text-sm text-orange-700 mt-1">
              Your feedback has been submitted. The team will review your notes and get back to you.
            </p>
          </div>
        ) : !isPendingReview ? (
          <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>
        ) : null}
      </div>
    </div>
  );
}
