import React, { useState } from 'react';
import { TranscriptComparison, TranscriptComparisonData } from '@/components/transcript/TranscriptComparison';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Shield } from 'lucide-react';
import { 
  TranscriptResult, 
  TranscriptSource, 
  ExtractionMethod,
  compareTranscriptQuality 
} from '@/types/transcript.types';

// Mock data for demonstration
const createMockTranscriptResult = (
  videoId: string, 
  method: ExtractionMethod,
  transcript: string,
  wordCount: number,
  processingTime: number
): TranscriptResult => ({
  videoId,
  transcript,
  segments: null,
  metadata: {
    wordCount,
    estimatedReadingTime: Math.ceil(wordCount / 200),
    language: 'en',
    hasTimestamps: false,
    extractionMethod: method,
    processingTimeSeconds: processingTime / 1000,
    qualityScore: method === ExtractionMethod.WHISPER_AUDIO ? 0.92 : 0.73,
    confidenceScore: method === ExtractionMethod.WHISPER_AUDIO ? 0.89 : 0.68
  },
  method,
  success: true,
  fromCache: false,
  error: null
});

const mockYouTubeTranscript = `Welcome to our tutorial on advanced machine learning techniques. In todays session we'll explore deep learning algorithms and their practical applications.

First lets discuss neural networks and how they process information. Neural networks are inspired by biological neural networks and consist of layers of interconnected nodes.

These algorithms can recognize patterns in data and make predictions based on training data. Common applications include image recognition speech processing and natural language understanding.

The key advantage of deep learning is its ability to learn complex representations automatically without requiring manual feature engineering.`;

const mockWhisperTranscript = `Welcome to our tutorial on advanced machine learning techniques. In today's session, we'll explore deep learning algorithms and their practical applications.

First, let's discuss neural networks and how they process information. Neural networks are inspired by biological neural networks and consist of layers of interconnected nodes.

These algorithms can recognize patterns in data and make predictions based on training data. Common applications include image recognition, speech processing, and natural language understanding.

The key advantage of deep learning is its ability to learn complex representations automatically without requiring manual feature engineering.`;

export function TranscriptComparisonDemo() {
  const [selectedTranscript, setSelectedTranscript] = useState<Exclude<TranscriptSource, 'both'> | null>(null);
  const [showComparison, setShowComparison] = useState(false);

  const youtubeResult = createMockTranscriptResult(
    'dQw4w9WgXcQ',
    ExtractionMethod.YOUTUBE_API,
    mockYouTubeTranscript,
    67,
    3000
  );

  const whisperResult = createMockTranscriptResult(
    'dQw4w9WgXcQ',
    ExtractionMethod.WHISPER_AUDIO,
    mockWhisperTranscript,
    69,
    45000
  );

  const comparisonData: TranscriptComparisonData = {
    youtubeTranscript: youtubeResult,
    whisperTranscript: whisperResult,
    comparison: compareTranscriptQuality(youtubeResult, whisperResult),
    highlightedDifferences: [
      {
        type: 'modification',
        text: "today's vs todays",
        position: { start: 85, end: 92 },
        significance: 'medium',
        category: 'punctuation'
      },
      {
        type: 'modification', 
        text: "let's vs lets",
        position: { start: 201, end: 206 },
        significance: 'medium',
        category: 'punctuation'
      },
      {
        type: 'addition',
        text: "Added commas in applications list",
        position: { start: 485, end: 520 },
        significance: 'low',
        category: 'punctuation'
      }
    ]
  };

  const handleSelectTranscript = (source: Exclude<TranscriptSource, 'both'>) => {
    setSelectedTranscript(source);
    console.log('Selected transcript source:', source);
  };

  return (
    <div className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-6xl mx-auto space-y-8">
          {/* Header */}
          <header className="text-center mb-8">
            <div className="flex items-center justify-center gap-3 mb-4">
              <Shield className="h-8 w-8 text-orange-600" />
              <Badge variant="outline" className="text-orange-600 border-orange-600">
                Demo Mode
              </Badge>
            </div>
            
            <h1 className="text-4xl font-bold tracking-tight">Transcript Comparison Demo</h1>
            <p className="text-xl text-muted-foreground mt-2">
              Preview the dual transcript comparison functionality
            </p>
            
            <div className="mt-4">
              <Badge variant="secondary" className="text-sm">
                YouTube vs AI Whisper • Quality Analysis • Side-by-Side Comparison
              </Badge>
            </div>
          </header>

          {/* Demo Controls */}
          <Card>
            <CardHeader>
              <CardTitle>Demo Controls</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-4">
                <Button 
                  onClick={() => setShowComparison(!showComparison)}
                  variant={showComparison ? "default" : "outline"}
                >
                  {showComparison ? 'Hide Comparison' : 'Show Comparison'}
                </Button>
                
                {selectedTranscript && (
                  <Badge variant="secondary" className="flex items-center gap-1">
                    Selected: {selectedTranscript === 'youtube' ? '📺 YouTube' : '🎯 Whisper'}
                  </Badge>
                )}
              </div>
              
              <div className="mt-4 text-sm text-muted-foreground">
                <p><strong>Mock Data:</strong> This demo uses sample transcript data to demonstrate the comparison interface.</p>
                <p><strong>Features:</strong> Side-by-side comparison, quality metrics, difference highlighting, and transcript selection.</p>
              </div>
            </CardContent>
          </Card>

          {/* Transcript Comparison */}
          {showComparison && (
            <TranscriptComparison
              data={comparisonData}
              onSelectTranscript={handleSelectTranscript}
              selectedTranscript={selectedTranscript}
              showTimestamps={true}
              showQualityMetrics={true}
              showDifferencesOnly={false}
              highlightSignificantChanges={true}
            />
          )}

          {/* Selected Transcript Preview */}
          {selectedTranscript && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  {selectedTranscript === 'youtube' ? '📺' : '🎯'}
                  Selected Transcript: {selectedTranscript === 'youtube' ? 'YouTube Captions' : 'AI Whisper'}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="bg-muted/50 rounded-lg p-4">
                  <pre className="whitespace-pre-wrap text-sm">
                    {selectedTranscript === 'youtube' ? mockYouTubeTranscript : mockWhisperTranscript}
                  </pre>
                </div>
                
                <div className="mt-4 grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div>
                    <span className="font-medium">Word Count:</span>
                    <p className="text-muted-foreground">
                      {selectedTranscript === 'youtube' ? youtubeResult.metadata?.wordCount : whisperResult.metadata?.wordCount}
                    </p>
                  </div>
                  <div>
                    <span className="font-medium">Processing Time:</span>
                    <p className="text-muted-foreground">
                      {selectedTranscript === 'youtube' ? '3.0s' : '45.0s'}
                    </p>
                  </div>
                  <div>
                    <span className="font-medium">Quality Score:</span>
                    <p className="text-muted-foreground">
                      {Math.round((selectedTranscript === 'youtube' ? 0.73 : 0.92) * 100)}%
                    </p>
                  </div>
                  <div>
                    <span className="font-medium">Method:</span>
                    <p className="text-muted-foreground">
                      {selectedTranscript === 'youtube' ? 'YouTube API' : 'Whisper AI'}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          <footer className="text-center pt-8 border-t">
            <p className="text-sm text-muted-foreground">
              Demo Mode - Showcasing dual transcript functionality with mock data
            </p>
          </footer>
        </div>
      </div>
    </div>
  );
}