import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import { apiService, type TranscodeJob, type Track } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import { 
  Loader2,
  Plus,
  RefreshCw,
  CheckCircle,
  XCircle,
  Clock,
  Zap,
  Activity,
  TrendingUp,
  AlertCircle
} from 'lucide-react';

interface TranscodeStats {
  total: number;
  pending: number;
  processing: number;
  completed: number;
  failed: number;
}

export function TranscodingDashboard() {
  const [stats, setStats] = useState<TranscodeStats>({
    total: 0,
    pending: 0,
    processing: 0,
    completed: 0,
    failed: 0,
  });
  const [jobs, setJobs] = useState<TranscodeJob[]>([]);
  const [availableTracks, setAvailableTracks] = useState<Track[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [selectedTrack, setSelectedTrack] = useState<string>('');
  const [selectedQuality, setSelectedQuality] = useState<string>('medium');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    fetchStats();
    fetchTracks();
    
    // Auto-refresh every 5 seconds
    const interval = setInterval(() => {
      fetchStats();
    }, 5000);

    return () => clearInterval(interval);
  }, []);

  const fetchStats = async () => {
    try {
      setIsLoading(true);
      const data = await apiService.getTranscodeStats();
      setStats(data);
      
      // Mock jobs data - In real implementation, fetch from API
      setJobs([
        {
          id: '1',
          trackId: 'track-1',
          status: 'processing',
          inputPath: '/uploads/track1.wav',
          outputDir: '/streams/track1',
          quality: 'high',
          progress: 65,
          createdAt: new Date().toISOString(),
        },
        {
          id: '2',
          trackId: 'track-2',
          status: 'completed',
          inputPath: '/uploads/track2.mp3',
          outputDir: '/streams/track2',
          quality: 'medium',
          progress: 100,
          createdAt: new Date(Date.now() - 3600000).toISOString(),
          completedAt: new Date(Date.now() - 1800000).toISOString(),
        },
        {
          id: '3',
          trackId: 'track-3',
          status: 'failed',
          inputPath: '/uploads/track3.flac',
          outputDir: '/streams/track3',
          quality: 'high',
          progress: 45,
          errorMessage: 'Invalid audio format',
          createdAt: new Date(Date.now() - 7200000).toISOString(),
        },
      ]);
    } catch (error: any) {
      console.error('Failed to fetch stats:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchTracks = async () => {
    try {
      const response = await apiService.getTracks({ limit: 100 });
      setAvailableTracks(response.tracks);
    } catch (error: any) {
      console.error('Failed to fetch tracks:', error);
    }
  };

  const handleSubmitJob = async () => {
    if (!selectedTrack) {
      toast({
        title: 'Track required',
        description: 'Please select a track to transcode',
        variant: 'destructive',
      });
      return;
    }

    try {
      setIsSubmitting(true);
      
      const track = availableTracks.find(t => t.id === selectedTrack);
      if (!track) throw new Error('Track not found');

      await apiService.submitTranscodeJob(
        selectedTrack,
        track.filePath || `/uploads/${track.id}`,
        selectedQuality
      );
      
      toast({
        title: 'Job submitted',
        description: 'Transcoding job has been queued successfully.',
      });
      
      setSelectedTrack('');
      setSelectedQuality('medium');
      setIsCreateDialogOpen(false);
      fetchStats();
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.response?.data?.error || 'Failed to submit job',
        variant: 'destructive',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'pending':
        return <Clock className="h-5 w-5 text-yellow-500" />;
      case 'processing':
        return <Loader2 className="h-5 w-5 text-blue-500 animate-spin" />;
      case 'completed':
        return <CheckCircle className="h-5 w-5 text-green-500" />;
      case 'failed':
        return <XCircle className="h-5 w-5 text-red-500" />;
      default:
        return <AlertCircle className="h-5 w-5 text-gray-500" />;
    }
  };

  const getStatusBadgeVariant = (status: string): 'default' | 'secondary' | 'destructive' => {
    switch (status) {
      case 'completed':
        return 'default';
      case 'failed':
        return 'destructive';
      default:
        return 'secondary';
    }
  };

  const formatDuration = (startTime: string, endTime?: string): string => {
    const start = new Date(startTime).getTime();
    const end = endTime ? new Date(endTime).getTime() : Date.now();
    const duration = Math.floor((end - start) / 1000);
    
    const minutes = Math.floor(duration / 60);
    const seconds = duration % 60;
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Transcoding Dashboard</h1>
          <p className="text-muted-foreground">
            Monitor and manage audio transcoding jobs
          </p>
        </div>
        
        <div className="flex items-center space-x-2">
          <Button
            variant="outline"
            size="sm"
            onClick={fetchStats}
          >
            <RefreshCw className="h-4 w-4 mr-2" />
            Refresh
          </Button>
          
          <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                New Job
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Create Transcoding Job</DialogTitle>
                <DialogDescription>
                  Select a track and quality level to start transcoding
                </DialogDescription>
              </DialogHeader>
              
              <div className="space-y-4 py-4">
                <div className="space-y-2">
                  <Label htmlFor="track">Track *</Label>
                  <select
                    id="track"
                    className="w-full px-3 py-2 border rounded-md"
                    value={selectedTrack}
                    onChange={(e) => setSelectedTrack(e.target.value)}
                  >
                    <option value="">Select a track...</option>
                    {availableTracks.map((track) => (
                      <option key={track.id} value={track.id}>
                        {track.title} - {track.artist}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="quality">Quality *</Label>
                  <select
                    id="quality"
                    className="w-full px-3 py-2 border rounded-md"
                    value={selectedQuality}
                    onChange={(e) => setSelectedQuality(e.target.value)}
                  >
                    <option value="low">Low (128k) - Fast</option>
                    <option value="medium">Medium (192k) - Balanced</option>
                    <option value="high">High (320k) - Best Quality</option>
                    <option value="lossless">Lossless (FLAC) - Maximum Quality</option>
                  </select>
                </div>
                
                <div className="p-4 bg-muted rounded-lg text-sm">
                  <p className="font-medium mb-2">Estimated Processing Time:</p>
                  <p className="text-muted-foreground">
                    {selectedQuality === 'low' && '~30 seconds per minute of audio'}
                    {selectedQuality === 'medium' && '~45 seconds per minute of audio'}
                    {selectedQuality === 'high' && '~60 seconds per minute of audio'}
                    {selectedQuality === 'lossless' && '~90 seconds per minute of audio'}
                  </p>
                </div>
              </div>
              
              <DialogFooter>
                <Button
                  variant="outline"
                  onClick={() => setIsCreateDialogOpen(false)}
                >
                  Cancel
                </Button>
                <Button
                  onClick={handleSubmitJob}
                  disabled={isSubmitting || !selectedTrack}
                >
                  {isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                  Submit Job
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Stats Overview */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium">Total Jobs</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="text-2xl font-bold">{stats.total}</div>
              <Activity className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium">Pending</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="text-2xl font-bold text-yellow-600">{stats.pending}</div>
              <Clock className="h-8 w-8 text-yellow-500" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium">Processing</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="text-2xl font-bold text-blue-600">{stats.processing}</div>
              <Zap className="h-8 w-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium">Completed</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="text-2xl font-bold text-green-600">{stats.completed}</div>
              <CheckCircle className="h-8 w-8 text-green-500" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium">Failed</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="text-2xl font-bold text-red-600">{stats.failed}</div>
              <XCircle className="h-8 w-8 text-red-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Jobs List */}
      <Card>
        <CardHeader>
          <CardTitle>Recent Jobs</CardTitle>
          <CardDescription>
            Monitor the status of transcoding operations
          </CardDescription>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex items-center justify-center p-8">
              <Loader2 className="h-8 w-8 animate-spin" />
            </div>
          ) : jobs.length === 0 ? (
            <div className="text-center py-8">
              <Zap className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <h3 className="text-lg font-medium mb-2">No Jobs Yet</h3>
              <p className="text-muted-foreground mb-4">
                Create your first transcoding job to get started
              </p>
              <Button onClick={() => setIsCreateDialogOpen(true)}>
                <Plus className="h-4 w-4 mr-2" />
                Create Job
              </Button>
            </div>
          ) : (
            <div className="space-y-4">
              {jobs.map((job) => (
                <div
                  key={job.id}
                  className="border rounded-lg p-4 space-y-3"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex items-start space-x-3">
                      {getStatusIcon(job.status)}
                      <div>
                        <div className="font-medium">Job #{job.id}</div>
                        <div className="text-sm text-muted-foreground">{job.inputPath}</div>
                      </div>
                    </div>
                    <Badge variant={getStatusBadgeVariant(job.status)}>
                      {job.status.toUpperCase()}
                    </Badge>
                  </div>

                  {job.status === 'processing' && (
                    <div className="space-y-2">
                      <div className="flex items-center justify-between text-sm">
                        <span className="text-muted-foreground">Progress</span>
                        <span className="font-medium">{job.progress}%</span>
                      </div>
                      <Progress value={job.progress} />
                    </div>
                  )}

                  {job.errorMessage && (
                    <div className="p-3 bg-red-50 border border-red-200 rounded-md text-sm text-red-800">
                      <div className="flex items-center space-x-2">
                        <AlertCircle className="h-4 w-4" />
                        <span>Error: {job.errorMessage}</span>
                      </div>
                    </div>
                  )}

                  <div className="flex items-center justify-between text-xs text-muted-foreground">
                    <div className="flex items-center space-x-4">
                      <span>Quality: {job.quality}</span>
                      <span>•</span>
                      <span>Created: {new Date(job.createdAt).toLocaleString()}</span>
                    </div>
                    {job.status === 'processing' && (
                      <span>Duration: {formatDuration(job.createdAt)}</span>
                    )}
                    {job.completedAt && (
                      <span>Duration: {formatDuration(job.createdAt, job.completedAt)}</span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Performance Metrics */}
      <Card>
        <CardHeader>
          <CardTitle>Performance Metrics</CardTitle>
          <CardDescription>
            System performance and throughput
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Success Rate</span>
                <TrendingUp className="h-4 w-4 text-green-500" />
              </div>
              <div className="text-2xl font-bold">
                {stats.total > 0 
                  ? Math.round((stats.completed / stats.total) * 100) 
                  : 0}%
              </div>
              <Progress 
                value={stats.total > 0 ? (stats.completed / stats.total) * 100 : 0} 
                className="h-2"
              />
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Avg Processing Time</span>
                <Clock className="h-4 w-4 text-blue-500" />
              </div>
              <div className="text-2xl font-bold">2.3m</div>
              <p className="text-xs text-muted-foreground">per job</p>
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Queue Health</span>
                <Activity className="h-4 w-4 text-purple-500" />
              </div>
              <div className="text-2xl font-bold">
                {stats.processing + stats.pending < 10 ? 'Good' : 'Busy'}
              </div>
              <p className="text-xs text-muted-foreground">
                {stats.processing + stats.pending} jobs in queue
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

export default TranscodingDashboard;

