import { useParams, useNavigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { getTrack, TrackUploadError } from '../services/trackService';
import { Track } from '../types/track';
import { usePlayerStore } from '@/stores/player';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Alert } from '@/components/ui/alert';
import { useToast } from '@/hooks/useToast';
import { 
  Play, 
  Pause, 
  Heart, 
  Share2, 
  Download, 
  Music, 
  Clock, 
  Calendar,
  User,
  ArrowLeft,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import type { Track as PlayerTrack } from '@/types/api';

/**
 * TrackDetailPage Component
 * T0277: Page pour afficher les détails d'un track (métadonnées, waveform, player, actions)
 */

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

const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleDateString('fr-FR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
};

// Convert Track from features/tracks to PlayerTrack type
const convertToPlayerTrack = (track: Track): PlayerTrack => {
  return {
    id: track.id.toString(),
    title: track.title,
    artist_id: track.user_id.toString(),
    artist: track.artist,
    duration: track.duration,
    file_path: track.file_path,
    cover_art_url: track.cover_art_path,
    genre: track.genre || '',
    plays: track.play_count,
    created_at: track.created_at,
    updated_at: track.updated_at,
  } as PlayerTrack;
};

export function TrackDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [track, setTrack] = useState<Track | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { play, pause, currentTrack, isPlaying, addToQueue } = usePlayerStore();
  const { toast } = useToast();

  useEffect(() => {
    if (!id) {
      setError('Track ID is required');
      setLoading(false);
      return;
    }

    loadTrack(parseInt(id));
  }, [id]);

  const loadTrack = async (trackId: number) => {
    setLoading(true);
    setError(null);
    try {
      const data = await getTrack(trackId);
      setTrack(data);
    } catch (err) {
      console.error('Failed to load track:', err);
      let errorMessage = 'Impossible de charger le track';
      if (err instanceof TrackUploadError) {
        errorMessage = err.message;
      }
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handlePlay = () => {
    if (!track) return;
    
    const playerTrack = convertToPlayerTrack(track);
    
    // If this track is already playing, pause/resume
    if (currentTrack?.id === playerTrack.id) {
      if (isPlaying) {
        pause();
      } else {
        play(playerTrack);
      }
    } else {
      // Play this track
      play(playerTrack);
    }
  };

  const handleAddToQueue = () => {
    if (!track) return;
    const playerTrack = convertToPlayerTrack(track);
    addToQueue(playerTrack);
    toast.success('Track ajouté à la file d\'attente');
  };

  const handleLike = () => {
    // TODO: Implement like functionality
    toast.info('Fonctionnalité de like à implémenter');
  };

  const handleShare = async () => {
    if (!track) return;
    const url = `${window.location.origin}/tracks/${track.id}`;
    try {
      await navigator.clipboard.writeText(url);
      toast.success('Lien copié dans le presse-papiers');
    } catch (err) {
      toast.error('Impossible de copier le lien');
    }
  };

  const handleDownload = () => {
    if (!track) return;
    // TODO: Implement download functionality
    toast.info('Fonctionnalité de téléchargement à implémenter');
  };

  if (loading) {
    return (
      <div className="container mx-auto py-8">
        <LoadingSpinner text="Chargement du track..." />
      </div>
    );
  }

  if (error || !track) {
    return (
      <div className="container mx-auto py-8">
        <Alert variant="destructive">
          <p>{error || 'Track introuvable'}</p>
        </Alert>
        <Button
          variant="outline"
          onClick={() => navigate(-1)}
          className="mt-4"
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          Retour
        </Button>
      </div>
    );
  }

  const isCurrentTrack = currentTrack?.id === track.id.toString();
  const isCurrentlyPlaying = isCurrentTrack && isPlaying;

  return (
    <div className="container mx-auto py-8 space-y-6">
      {/* Back Button */}
      <Button
        variant="ghost"
        onClick={() => navigate(-1)}
        className="mb-4"
      >
        <ArrowLeft className="h-4 w-4 mr-2" />
        Retour
      </Button>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left Column - Cover Art and Player */}
        <div className="lg:col-span-1">
          <Card>
            <CardContent className="p-0">
              {/* Cover Art */}
              <div className="relative aspect-square bg-muted flex items-center justify-center">
                {track.cover_art_path ? (
                  <img
                    src={track.cover_art_path}
                    alt={track.title}
                    className="w-full h-full object-cover rounded-t-lg"
                  />
                ) : (
                  <Music className="h-32 w-32 text-muted-foreground/50" />
                )}
              </div>

              {/* Player Controls */}
              <div className="p-6 space-y-4">
                <div className="flex items-center justify-center gap-2">
                  <Button
                    size="lg"
                    onClick={handlePlay}
                    className="rounded-full h-16 w-16"
                  >
                    {isCurrentlyPlaying ? (
                      <Pause className="h-8 w-8" />
                    ) : (
                      <Play className="h-8 w-8 fill-current" />
                    )}
                  </Button>
                </div>

                {/* Action Buttons */}
                <div className="flex items-center justify-center gap-2">
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={handleLike}
                    title="Ajouter aux favoris"
                  >
                    <Heart className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={handleAddToQueue}
                    title="Ajouter à la file d'attente"
                  >
                    <Music className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={handleShare}
                    title="Partager"
                  >
                    <Share2 className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={handleDownload}
                    title="Télécharger"
                  >
                    <Download className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Right Column - Track Details */}
        <div className="lg:col-span-2 space-y-6">
          {/* Title and Artist */}
          <div>
            <h1 className="text-4xl font-bold mb-2">{track.title}</h1>
            <p className="text-2xl text-muted-foreground mb-4">{track.artist}</p>
            {track.album && (
              <p className="text-lg text-muted-foreground mb-4">Album: {track.album}</p>
            )}
          </div>

          {/* Metadata Grid */}
          <Card>
            <CardHeader>
              <CardTitle>Informations</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                <div className="flex items-center gap-2">
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  <div>
                    <p className="text-sm text-muted-foreground">Durée</p>
                    <p className="font-medium">{formatDuration(track.duration)}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Calendar className="h-4 w-4 text-muted-foreground" />
                  <div>
                    <p className="text-sm text-muted-foreground">Date de création</p>
                    <p className="font-medium">{formatDate(track.created_at)}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Music className="h-4 w-4 text-muted-foreground" />
                  <div>
                    <p className="text-sm text-muted-foreground">Format</p>
                    <p className="font-medium">{track.format}</p>
                  </div>
                </div>
                {track.genre && (
                  <div>
                    <p className="text-sm text-muted-foreground mb-1">Genre</p>
                    <Badge>{track.genre}</Badge>
                  </div>
                )}
                {track.year && (
                  <div>
                    <p className="text-sm text-muted-foreground mb-1">Année</p>
                    <p className="font-medium">{track.year}</p>
                  </div>
                )}
                {track.bitrate && (
                  <div>
                    <p className="text-sm text-muted-foreground mb-1">Bitrate</p>
                    <p className="font-medium">{track.bitrate} kbps</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Statistics */}
          <Card>
            <CardHeader>
              <CardTitle>Statistiques</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground">Écoutes</p>
                  <p className="text-2xl font-bold">{track.play_count}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Likes</p>
                  <p className="text-2xl font-bold">{track.like_count}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Waveform Placeholder */}
          {track.waveform_path && (
            <Card>
              <CardHeader>
                <CardTitle>Waveform</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-32 bg-muted rounded flex items-center justify-center">
                  <img
                    src={track.waveform_path}
                    alt="Waveform"
                    className="max-w-full max-h-full"
                  />
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}

