import { useState, useEffect } from 'react';
import { EnhancedAudioPlayer } from '@/features/stream/components/EnhancedAudioPlayer';
import { QueueManager } from '@/features/stream/components/QueueManager';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Music, ListMusic, Radio, Headphones } from 'lucide-react';
// import { completeApiService } from '@/services/api-complete';
import { useToast } from '@/hooks/use-toast';

interface Track {
  id: string;
  title: string;
  artist: string;
  duration: number;
  coverUrl?: string;
  quality: string;
  bitrate: number;
  format: string;
}

export function StreamPage() {
  const [currentTrack, setCurrentTrack] = useState<Track | null>(null);
  const [queue, setQueue] = useState<Track[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const { toast } = useToast();

  // Simuler des pistes de test
  useEffect(() => {
    const mockTracks: Track[] = [
      {
        id: '1',
        title: 'Summer Vibes',
        artist: 'DJ Mike',
        duration: 180,
        coverUrl: 'https://api.dicebear.com/7.x/initials/svg?seed=Summer',
        quality: '320k',
        bitrate: 320,
        format: 'MP3',
      },
      {
        id: '2',
        title: 'Night Drive',
        artist: 'Synthwave Artist',
        duration: 240,
        coverUrl: 'https://api.dicebear.com/7.x/initials/svg?seed=Night',
        quality: 'FLAC',
        bitrate: 1411,
        format: 'FLAC',
      },
      {
        id: '3',
        title: 'Chill Beats',
        artist: 'LoFi Producer',
        duration: 200,
        coverUrl: 'https://api.dicebear.com/7.x/initials/svg?seed=Chill',
        quality: '256k',
        bitrate: 256,
        format: 'MP3',
      },
    ];
    setQueue(mockTracks);
    setCurrentTrack(mockTracks[0]);
  }, []);

  const handleTrackSelect = (trackId: string) => {
    const track = queue.find(t => t.id === trackId);
    if (track) {
      setCurrentTrack(track);
    }
  };

  const handleTrackRemove = (trackId: string) => {
    setQueue(prev => prev.filter(t => t.id !== trackId));
    if (currentTrack?.id === trackId) {
      const nextTrack = queue.find(t => t.id !== trackId);
      setCurrentTrack(nextTrack || null);
    }
  };

  const handleQueueReorder = (fromIndex: number, toIndex: number) => {
    setQueue(prev => {
      const newQueue = [...prev];
      [newQueue[fromIndex], newQueue[toIndex]] = [newQueue[toIndex], newQueue[fromIndex]];
      return newQueue;
    });
  };

  const handleTrackEnd = () => {
    const currentIndex = queue.findIndex(t => t.id === currentTrack?.id);
    const nextTrack = queue[currentIndex + 1];
    if (nextTrack) {
      setCurrentTrack(nextTrack);
    }
  };

  const handleTrackChange = (trackId: string) => {
    const track = queue.find(t => t.id === trackId);
    if (track) {
      setCurrentTrack(track);
    }
  };

  if (!currentTrack) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Streaming Audio</h1>
          <p className="text-muted-foreground">
            Écoutez vos pistes audio en streaming haute qualité
          </p>
        </div>
        <Card>
          <CardContent className="flex items-center justify-center h-64">
            <div className="text-center">
              <Music className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
              <h3 className="text-lg font-semibold mb-2">Aucune piste sélectionnée</h3>
              <p className="text-muted-foreground mb-4">
                Sélectionnez une piste dans votre bibliothèque pour commencer l'écoute
              </p>
              <Button onClick={() => window.location.href = '/library'}>
                Ouvrir la bibliothèque
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Streaming Audio</h1>
        <p className="text-muted-foreground">
          Écoutez vos pistes audio en streaming haute qualité
        </p>
      </div>

      {/* Main Player V5 */}
      <EnhancedAudioPlayer
        trackId={currentTrack.id}
        title={currentTrack.title}
        artist={currentTrack.artist}
        coverUrl={currentTrack.coverUrl}
        duration={currentTrack.duration}
        onTrackEnd={handleTrackEnd}
        onTrackChange={handleTrackChange}
      />

      {/* Tabs for Queue and Settings */}
      <Tabs defaultValue="queue" className="w-full">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="queue" className="flex items-center gap-2">
            <ListMusic className="h-4 w-4" />
            File d'attente
          </TabsTrigger>
          <TabsTrigger value="radio" className="flex items-center gap-2">
            <Radio className="h-4 w-4" />
            Radio
          </TabsTrigger>
          <TabsTrigger value="settings" className="flex items-center gap-2">
            <Headphones className="h-4 w-4" />
            Paramètres
          </TabsTrigger>
        </TabsList>

        <TabsContent value="queue" className="space-y-4">
          <QueueManager
            currentTrackId={currentTrack.id}
            onTrackSelect={handleTrackSelect}
            onTrackRemove={handleTrackRemove}
            onQueueReorder={handleQueueReorder}
          />
        </TabsContent>

        <TabsContent value="radio" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Radio className="h-5 w-5" />
                Radio en ligne
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-center py-8">
                <Radio className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
                <h3 className="text-lg font-semibold mb-2">Radio en cours de développement</h3>
                <p className="text-muted-foreground">
                  Cette fonctionnalité sera bientôt disponible
                </p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="settings" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Headphones className="h-5 w-5" />
                Paramètres audio
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Qualité par défaut</label>
                  <select className="w-full p-2 border rounded-md">
                    <option value="auto">Automatique</option>
                    <option value="128k">128 kbps</option>
                    <option value="256k">256 kbps</option>
                    <option value="320k">320 kbps</option>
                    <option value="flac">FLAC (Lossless)</option>
                  </select>
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Format préféré</label>
                  <select className="w-full p-2 border rounded-md">
                    <option value="mp3">MP3</option>
                    <option value="flac">FLAC</option>
                    <option value="aac">AAC</option>
                    <option value="ogg">OGG</option>
                  </select>
                </div>
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Cache audio</label>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">500 MB utilisés</span>
                  <Button variant="outline" size="sm">
                    Vider le cache
                  </Button>
                </div>
                <div className="w-full bg-muted rounded-full h-2">
                  <div className="bg-primary h-2 rounded-full" style={{ width: '25%' }}></div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

export default StreamPage;