
import React, { useState, useEffect } from 'react';
import { VlaData, Interaction } from '../types';
import { TaskSegmentCard } from './TaskSegmentCard';
import { Loader, AlertTriangle, WandSparkles, Copy, Check, Download } from './Icons';

type HighlightPoint = { x: number; y: number; isEditing: boolean } | null;
type CoordinatePickerCallback = ((coords: { x: number; y: number }) => void) | null;

interface ResultsDisplayProps {
  vlaData: VlaData | null;
  isLoading: boolean;
  loadingMessage: string;
  error: string | null;
  hasVideo: boolean;
  videoDuration: number;
  totalFrames: number;
  usedFallback: boolean;
  onDownload: () => void;
  onSeekToTime: (time: number) => void;
  onUpdateInteraction: (taskId: number, interactionIndex: number, updatedInteraction: Interaction) => void;
  onHighlightPoint: (point: HighlightPoint) => void;
  onSetCoordinatePicker: (callback: CoordinatePickerCallback) => void;
}

export const ResultsDisplay: React.FC<ResultsDisplayProps> = ({ 
  vlaData, 
  isLoading, 
  loadingMessage, 
  error, 
  hasVideo, 
  videoDuration, 
  totalFrames,
  usedFallback,
  onDownload, 
  onSeekToTime, 
  onUpdateInteraction,
  onHighlightPoint,
  onSetCoordinatePicker
}) => {
  const [hasCopied, setHasCopied] = useState(false);

  useEffect(() => {
    if(hasCopied) {
      const timer = setTimeout(() => setHasCopied(false), 2000);
      return () => clearTimeout(timer);
    }
  }, [hasCopied]);

  const handleCopy = () => {
    if(vlaData) {
      navigator.clipboard.writeText(JSON.stringify(vlaData, null, 2));
      setHasCopied(true);
    }
  };

  const renderContent = () => {
    if (isLoading) {
      return (
        <div className="flex flex-col items-center justify-center h-full text-center">
          <Loader className="w-12 h-12 text-indigo-400" />
          <p className="mt-4 text-lg font-semibold text-slate-300">Analyzing Video</p>
          <p className="text-slate-400">{loadingMessage}</p>
        </div>
      );
    }

    if (error) {
      return (
        <div className="flex flex-col items-center justify-center h-full text-center p-4">
          <AlertTriangle className="w-12 h-12 text-red-400" />
          <p className="mt-4 text-lg font-semibold text-slate-200">Analysis Failed</p>
          <p className="text-red-300 bg-red-900/50 p-3 rounded-lg mt-2 max-w-md">{error}</p>
        </div>
      );
    }

    if (vlaData) {
      return (
        <div className="p-4 md:p-6 space-y-6">
          <div>
            <h3 className="text-xs font-semibold uppercase text-slate-400 tracking-wider">Overall Goal</h3>
            <p className="mt-2 text-lg text-slate-200 bg-slate-700/50 p-3 rounded-lg">{vlaData.overallGoal}</p>
          </div>
          <div>
            <h3 className="text-xs font-semibold uppercase text-slate-400 tracking-wider">Sequential Tasks</h3>
            <div className="space-y-4 mt-2">
              {vlaData.tasks.map((task) => (
                <TaskSegmentCard
                  key={task.id}
                  task={task}
                  videoDuration={videoDuration}
                  totalFrames={totalFrames}
                  onSeekToTime={onSeekToTime}
                  onUpdateInteraction={onUpdateInteraction}
                  onHighlightPoint={onHighlightPoint}
                  onSetCoordinatePicker={onSetCoordinatePicker}
                />
              ))}
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className="flex flex-col items-center justify-center h-full text-center p-4">
        <WandSparkles className="w-16 h-16 text-slate-600" />
        <h3 className="mt-4 text-xl font-bold text-slate-300">Analysis Results</h3>
        <p className="text-slate-400 mt-1 max-w-xs">
          {hasVideo ? 'Click "Generate Action Data" to begin the analysis.' : 'Upload a video to get started.'}
        </p>
      </div>
    );
  };
  
  return (
    <div className="flex-grow flex flex-col h-full overflow-hidden">
        <div className="flex-shrink-0 flex justify-between items-center p-4 border-b border-slate-700">
            <h2 className="text-xl font-bold text-white">Generated Data</h2>
            {vlaData && (
                <div className="flex items-center gap-2">
                    <button 
                        onClick={handleCopy}
                        className="flex items-center gap-2 px-3 py-1.5 text-sm font-semibold bg-slate-700 hover:bg-slate-600 rounded-md transition-colors"
                        aria-label="Copy JSON to clipboard"
                    >
                        {hasCopied ? <Check className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4" />}
                        {hasCopied ? 'Copied!' : 'Copy JSON'}
                    </button>
                    <button 
                        onClick={onDownload}
                        className="flex items-center gap-2 px-3 py-1.5 text-sm font-semibold bg-slate-700 hover:bg-slate-600 rounded-md transition-colors"
                        aria-label="Download JSON data"
                    >
                        <Download className="w-4 h-4" />
                        Download
                    </button>
                </div>
            )}
        </div>

        {usedFallback && !isLoading && vlaData && (
          <div className="flex-shrink-0 bg-yellow-900/50 border-b border-yellow-700/50 text-yellow-200 p-3 text-sm flex items-start gap-3" role="alert">
              <AlertTriangle className="w-5 h-5 flex-shrink-0 text-yellow-400 mt-0.5" aria-hidden="true" />
              <div>
                  <span className="font-semibold">Using Fallback Configuration.</span> Due to high demand, results were generated using a faster, alternate setting. Quality may vary slightly.
              </div>
          </div>
        )}

        <div className="flex-grow overflow-y-auto">
            {renderContent()}
        </div>
    </div>
  );
};
