import { useState, useRef } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { useToast } from "@/hooks/use-toast";
import { useMutation, useQuery } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import {
  Upload, Play, Pause, Download, Share2, Settings,
  Video, Zap, Target, Save, Trash2, Eye, Clock,
  Star, Trophy, Activity, Camera, Film, Scissors,
  BarChart3, TrendingUp, Award, CheckCircle2
} from "lucide-react";

interface VideoFile {
  id: string;
  name: string;
  size: number;
  duration: number;
  uploadedAt: string;
  status: 'uploading' | 'processing' | 'ready' | 'error';
  url?: string;
}

interface HighlightClip {
  id: string;
  type: 'goal' | 'assist' | 'save' | 'tackle' | 'run' | 'pass' | 'skill';
  startTime: number;
  endTime: number;
  confidence: number;
  description: string;
  playerName?: string;
  selected: boolean;
}

interface GenerationSettings {
  highlightTypes: string[];
  minConfidence: number;
  clipDuration: number;
  outputQuality: 'HD' | 'Full HD' | '4K';
  transitions: boolean;
  slowMotion: boolean;
  titleOverlays: boolean;
  musicTrack: string;
}

export default function VideoHighlights() {
  const { toast } = useToast();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const [uploadedVideos, setUploadedVideos] = useState<VideoFile[]>([]);
  const [selectedVideo, setSelectedVideo] = useState<VideoFile | null>(null);
  const [analysisProgress, setAnalysisProgress] = useState(0);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [detectedClips, setDetectedClips] = useState<HighlightClip[]>([]);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generationProgress, setGenerationProgress] = useState(0);
  const [previewClip, setPreviewClip] = useState<HighlightClip | null>(null);
  
  const [settings, setSettings] = useState<GenerationSettings>({
    highlightTypes: ['goal', 'assist', 'save'],
    minConfidence: 70,
    clipDuration: 10,
    outputQuality: 'Full HD',
    transitions: true,
    slowMotion: false,
    titleOverlays: true,
    musicTrack: 'epic_sports'
  });

  // Mock data for demonstration
  const mockClips: HighlightClip[] = [
    {
      id: '1',
      type: 'goal',
      startTime: 120,
      endTime: 135,
      confidence: 95,
      description: 'Amazing strike from 25 yards',
      playerName: 'John Smith',
      selected: true
    },
    {
      id: '2',
      type: 'assist',
      startTime: 340,
      endTime: 355,
      confidence: 88,
      description: 'Perfect through ball',
      playerName: 'Mike Johnson',
      selected: true
    },
    {
      id: '3',
      type: 'save',
      startTime: 678,
      endTime: 690,
      confidence: 92,
      description: 'Spectacular diving save',
      playerName: 'David Wilson',
      selected: true
    },
    {
      id: '4',
      type: 'tackle',
      startTime: 890,
      endTime: 900,
      confidence: 75,
      description: 'Crucial defensive intervention',
      playerName: 'Tom Brown',
      selected: false
    },
    {
      id: '5',
      type: 'skill',
      startTime: 1240,
      endTime: 1255,
      confidence: 85,
      description: 'Beautiful skill move',
      playerName: 'Alex Green',
      selected: true
    }
  ];

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (!files) return;

    Array.from(files).forEach((file) => {
      if (file.type.startsWith('video/')) {
        const newVideo: VideoFile = {
          id: Date.now().toString() + Math.random(),
          name: file.name,
          size: file.size,
          duration: 0, // Would be calculated after upload
          uploadedAt: new Date().toISOString(),
          status: 'uploading'
        };

        setUploadedVideos(prev => [...prev, newVideo]);

        // Simulate upload process
        setTimeout(() => {
          setUploadedVideos(prev => 
            prev.map(v => v.id === newVideo.id ? { ...v, status: 'ready', duration: 3600 } : v)
          );
          toast({
            title: "Video uploaded successfully",
            description: `${file.name} is ready for analysis`
          });
        }, 2000);
      }
    });
  };

  const analyzeVideo = async (video: VideoFile) => {
    setSelectedVideo(video);
    setIsAnalyzing(true);
    setAnalysisProgress(0);
    setDetectedClips([]);

    // Simulate AI analysis with progress updates
    const interval = setInterval(() => {
      setAnalysisProgress(prev => {
        if (prev >= 100) {
          clearInterval(interval);
          setIsAnalyzing(false);
          setDetectedClips(mockClips);
          toast({
            title: "Analysis complete",
            description: `Found ${mockClips.length} potential highlights`
          });
          return 100;
        }
        return prev + 10;
      });
    }, 500);
  };

  const generateHighlights = async () => {
    const selectedClips = detectedClips.filter(clip => clip.selected);
    
    if (selectedClips.length === 0) {
      toast({
        title: "No clips selected",
        description: "Please select at least one highlight to generate",
        variant: "destructive"
      });
      return;
    }

    setIsGenerating(true);
    setGenerationProgress(0);

    // Simulate video generation process
    const interval = setInterval(() => {
      setGenerationProgress(prev => {
        if (prev >= 100) {
          clearInterval(interval);
          setIsGenerating(false);
          toast({
            title: "Highlights generated successfully",
            description: `Created highlight reel with ${selectedClips.length} clips`
          });
          return 100;
        }
        return prev + 5;
      });
    }, 300);
  };

  const toggleClipSelection = (clipId: string) => {
    setDetectedClips(prev =>
      prev.map(clip =>
        clip.id === clipId ? { ...clip, selected: !clip.selected } : clip
      )
    );
  };

  const selectAllClips = () => {
    setDetectedClips(prev => prev.map(clip => ({ ...clip, selected: true })));
  };

  const clearAllClips = () => {
    setDetectedClips(prev => prev.map(clip => ({ ...clip, selected: false })));
  };

  const selectHighConfidenceClips = () => {
    setDetectedClips(prev =>
      prev.map(clip => ({
        ...clip,
        selected: clip.confidence >= settings.minConfidence
      }))
    );
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const formatFileSize = (bytes: number) => {
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    if (bytes === 0) return '0 Bytes';
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
  };

  const getClipIcon = (type: string) => {
    switch (type) {
      case 'goal': return <Target className="h-4 w-4 text-green-600" />;
      case 'assist': return <Star className="h-4 w-4 text-blue-600" />;
      case 'save': return <Trophy className="h-4 w-4 text-orange-600" />;
      case 'tackle': return <Activity className="h-4 w-4 text-red-600" />;
      case 'skill': return <Zap className="h-4 w-4 text-purple-600" />;
      default: return <Play className="h-4 w-4 text-gray-600" />;
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg p-6">
        <div className="flex items-center space-x-3">
          <Film className="h-8 w-8" />
          <div>
            <h1 className="text-2xl font-bold">Performance Video Highlights</h1>
            <p className="text-blue-100">AI-powered highlight generation from your match footage</p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Upload and Video Management */}
        <div className="space-y-6">
          {/* Upload Section */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Upload className="h-5 w-5" />
                <span>Upload Video</span>
              </CardTitle>
              <CardDescription>
                Upload match footage for AI analysis
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div
                  className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-blue-500 transition-colors"
                  onClick={() => fileInputRef.current?.click()}
                >
                  <Video className="h-12 w-12 text-gray-400 mx-auto mb-2" />
                  <p className="text-sm text-gray-600">
                    Drop video files here or click to browse
                  </p>
                  <p className="text-xs text-gray-500 mt-1">
                    Supports MP4, MOV, AVI (Max 1GB)
                  </p>
                </div>
                
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="video/*"
                  multiple
                  onChange={handleFileUpload}
                  className="hidden"
                />
              </div>
            </CardContent>
          </Card>

          {/* Uploaded Videos */}
          <Card>
            <CardHeader>
              <CardTitle>Video Library</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {uploadedVideos.length === 0 ? (
                  <p className="text-gray-500 text-center py-4">No videos uploaded yet</p>
                ) : (
                  uploadedVideos.map((video) => (
                    <div
                      key={video.id}
                      className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                        selectedVideo?.id === video.id
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-gray-300'
                      }`}
                      onClick={() => setSelectedVideo(video)}
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium text-sm">{video.name}</p>
                          <p className="text-xs text-gray-500">
                            {formatFileSize(video.size)} • {formatTime(video.duration)}
                          </p>
                        </div>
                        <div className="flex items-center space-x-2">
                          <Badge
                            variant={video.status === 'ready' ? 'default' : 'secondary'}
                          >
                            {video.status}
                          </Badge>
                          {video.status === 'ready' && (
                            <Button
                              size="sm"
                              onClick={(e) => {
                                e.stopPropagation();
                                analyzeVideo(video);
                              }}
                            >
                              <Zap className="h-4 w-4 mr-1" />
                              Analyze
                            </Button>
                          )}
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </CardContent>
          </Card>

          {/* Generation Settings */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Settings className="h-5 w-5" />
                <span>Settings</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div>
                  <Label>Highlight Types</Label>
                  <div className="grid grid-cols-2 gap-2 mt-2">
                    {['goal', 'assist', 'save', 'tackle', 'skill', 'pass'].map((type) => (
                      <div key={type} className="flex items-center space-x-2">
                        <input
                          type="checkbox"
                          id={type}
                          checked={settings.highlightTypes.includes(type)}
                          onChange={(e) => {
                            if (e.target.checked) {
                              setSettings(prev => ({
                                ...prev,
                                highlightTypes: [...prev.highlightTypes, type]
                              }));
                            } else {
                              setSettings(prev => ({
                                ...prev,
                                highlightTypes: prev.highlightTypes.filter(t => t !== type)
                              }));
                            }
                          }}
                          className="rounded"
                        />
                        <Label htmlFor={type} className="text-sm capitalize">{type}</Label>
                      </div>
                    ))}
                  </div>
                </div>

                <div>
                  <Label>Confidence Threshold: {settings.minConfidence}%</Label>
                  <Slider
                    value={[settings.minConfidence]}
                    onValueChange={(value) => setSettings(prev => ({ ...prev, minConfidence: value[0] }))}
                    max={100}
                    step={5}
                    className="mt-2"
                  />
                </div>

                <div>
                  <Label>Clip Duration: {settings.clipDuration}s</Label>
                  <Slider
                    value={[settings.clipDuration]}
                    onValueChange={(value) => setSettings(prev => ({ ...prev, clipDuration: value[0] }))}
                    min={5}
                    max={30}
                    step={1}
                    className="mt-2"
                  />
                </div>

                <div>
                  <Label>Output Quality</Label>
                  <Select
                    value={settings.outputQuality}
                    onValueChange={(value: any) => setSettings(prev => ({ ...prev, outputQuality: value }))}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="HD">HD (720p)</SelectItem>
                      <SelectItem value="Full HD">Full HD (1080p)</SelectItem>
                      <SelectItem value="4K">4K (2160p)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <Label>Transitions</Label>
                    <Switch
                      checked={settings.transitions}
                      onCheckedChange={(checked) => setSettings(prev => ({ ...prev, transitions: checked }))}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <Label>Slow Motion</Label>
                    <Switch
                      checked={settings.slowMotion}
                      onCheckedChange={(checked) => setSettings(prev => ({ ...prev, slowMotion: checked }))}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <Label>Title Overlays</Label>
                    <Switch
                      checked={settings.titleOverlays}
                      onCheckedChange={(checked) => setSettings(prev => ({ ...prev, titleOverlays: checked }))}
                    />
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Middle Column - Analysis and Clips */}
        <div className="space-y-6">
          {/* Analysis Progress */}
          {isAnalyzing && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Activity className="h-5 w-5 animate-pulse text-blue-600" />
                  <span>Analyzing Video</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <Progress value={analysisProgress} className="w-full" />
                  <p className="text-sm text-gray-600">
                    AI is detecting performance highlights... {analysisProgress}%
                  </p>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Detected Clips */}
          {detectedClips.length > 0 && (
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle>Detected Highlights</CardTitle>
                  <div className="flex items-center space-x-2">
                    <Button size="sm" variant="outline" onClick={selectAllClips}>
                      Select All
                    </Button>
                    <Button size="sm" variant="outline" onClick={clearAllClips}>
                      Clear All
                    </Button>
                    <Button size="sm" variant="outline" onClick={selectHighConfidenceClips}>
                      High Confidence
                    </Button>
                  </div>
                </div>
                <CardDescription>
                  {detectedClips.filter(clip => clip.selected).length} of {detectedClips.length} clips selected
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3 max-h-96 overflow-y-auto">
                  {detectedClips.map((clip) => (
                    <div
                      key={clip.id}
                      className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                        clip.selected
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-gray-300'
                      }`}
                      onClick={() => toggleClipSelection(clip.id)}
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <input
                            type="checkbox"
                            checked={clip.selected}
                            onChange={() => toggleClipSelection(clip.id)}
                            className="rounded"
                          />
                          {getClipIcon(clip.type)}
                          <div>
                            <p className="font-medium text-sm capitalize">{clip.type}</p>
                            <p className="text-xs text-gray-500">{clip.description}</p>
                            {clip.playerName && (
                              <p className="text-xs text-blue-600">{clip.playerName}</p>
                            )}
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="flex items-center space-x-2">
                            <Badge variant="outline">
                              {clip.confidence}%
                            </Badge>
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={(e) => {
                                e.stopPropagation();
                                setPreviewClip(clip);
                              }}
                            >
                              <Eye className="h-4 w-4" />
                            </Button>
                          </div>
                          <p className="text-xs text-gray-500 mt-1">
                            {formatTime(clip.startTime)} - {formatTime(clip.endTime)}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Generation Controls */}
          {detectedClips.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle>Generate Highlights</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {isGenerating ? (
                    <div className="space-y-3">
                      <Progress value={generationProgress} className="w-full" />
                      <p className="text-sm text-gray-600">
                        Creating highlight reel... {generationProgress}%
                      </p>
                    </div>
                  ) : (
                    <Button
                      onClick={generateHighlights}
                      className="w-full"
                      disabled={detectedClips.filter(clip => clip.selected).length === 0}
                    >
                      <Scissors className="h-4 w-4 mr-2" />
                      Generate Highlights
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          )}
        </div>

        {/* Right Column - Preview and Export */}
        <div className="space-y-6">
          {/* Quick Stats */}
          <div className="grid grid-cols-2 gap-4">
            <Card>
              <CardContent className="p-4">
                <div className="flex items-center space-x-2">
                  <Video className="h-5 w-5 text-blue-600" />
                  <div>
                    <p className="text-sm font-medium">{uploadedVideos.length}</p>
                    <p className="text-xs text-gray-500">Videos</p>
                  </div>
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4">
                <div className="flex items-center space-x-2">
                  <Target className="h-5 w-5 text-green-600" />
                  <div>
                    <p className="text-sm font-medium">{detectedClips.length}</p>
                    <p className="text-xs text-gray-500">Highlights</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Export Options */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Download className="h-5 w-5" />
                <span>Export & Share</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                <Button className="w-full" variant="outline">
                  <Download className="h-4 w-4 mr-2" />
                  Download Highlights
                </Button>
                <Button className="w-full" variant="outline">
                  <Share2 className="h-4 w-4 mr-2" />
                  Share to Social Media
                </Button>
                <Button className="w-full" variant="outline">
                  <Save className="h-4 w-4 mr-2" />
                  Save to Library
                </Button>
              </div>
            </CardContent>
          </Card>

          {/* Recent Highlights */}
          <Card>
            <CardHeader>
              <CardTitle>Recent Highlights</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                <div className="p-3 border rounded-lg">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-sm">Match vs City FC</p>
                      <p className="text-xs text-gray-500">5 highlights • 2:30 duration</p>
                    </div>
                    <div className="flex items-center space-x-1">
                      <Button size="sm" variant="ghost">
                        <Eye className="h-4 w-4" />
                      </Button>
                      <Button size="sm" variant="ghost">
                        <Download className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </div>
                <div className="p-3 border rounded-lg">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-sm">Training Session</p>
                      <p className="text-xs text-gray-500">3 highlights • 1:45 duration</p>
                    </div>
                    <div className="flex items-center space-x-1">
                      <Button size="sm" variant="ghost">
                        <Eye className="h-4 w-4" />
                      </Button>
                      <Button size="sm" variant="ghost">
                        <Download className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Preview Modal */}
      <Dialog open={!!previewClip} onOpenChange={() => setPreviewClip(null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Preview Highlight</DialogTitle>
          </DialogHeader>
          {previewClip && (
            <div className="space-y-4">
              <div className="bg-black rounded-lg aspect-video flex items-center justify-center">
                <div className="text-white text-center">
                  <Play className="h-12 w-12 mx-auto mb-2" />
                  <p>Video Preview</p>
                  <p className="text-sm opacity-70">
                    {formatTime(previewClip.startTime)} - {formatTime(previewClip.endTime)}
                  </p>
                </div>
              </div>
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="font-medium capitalize">{previewClip.type}</h3>
                  <p className="text-sm text-gray-600">{previewClip.description}</p>
                  {previewClip.playerName && (
                    <p className="text-sm text-blue-600">{previewClip.playerName}</p>
                  )}
                </div>
                <Badge variant="outline">
                  {previewClip.confidence}% confidence
                </Badge>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}