import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Spinner } from "@/components/ui/spinner";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { Music, LogOut, Play, Pause } from "lucide-react";
import { trpc } from "@/lib/trpc";

interface MusicPlayerProps {
  credentials: { username: string; password: string };
  onLogout: () => void;
}

export default function MusicPlayer({ credentials, onLogout }: MusicPlayerProps) {
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTrack, setCurrentTrack] = useState<any>(null);

  // Fetch categories
  const { data: categories = [], isLoading: categoriesLoading } = trpc.music.getCategories.useQuery();

  // Fetch tracks by category
  const { data: tracks = [], isLoading: tracksLoading } = trpc.music.getTracksByCategory.useQuery(
    selectedCategory || 0,
    { enabled: !!selectedCategory }
  );

  const handleLogout = () => {
    sessionStorage.removeItem("xtream_username");
    sessionStorage.removeItem("xtream_password");
    toast.success("Desconectado com sucesso");
    onLogout();
  };

  const handlePlayTrack = (track: any) => {
    setCurrentTrack(track);
    setIsPlaying(true);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 text-white p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-12">
          <div className="flex items-center gap-3">
            <div className="bg-gradient-to-br from-purple-600 to-blue-600 p-3 rounded-lg">
              <Music className="w-8 h-8" />
            </div>
            <div>
              <h1 className="text-3xl font-bold">Xtream Music</h1>
              <p className="text-slate-400">Bem-vindo, {credentials.username}</p>
            </div>
          </div>
          <Button variant="outline" onClick={handleLogout} className="gap-2">
            <LogOut className="w-4 h-4" />
            Sair
          </Button>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          {/* Categories Sidebar */}
          <div className="lg:col-span-1">
            <Card className="bg-slate-800 border-slate-700">
              <CardHeader>
                <CardTitle className="text-white">Categorias</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                {categoriesLoading ? (
                  <Spinner />
                ) : categories.length === 0 ? (
                  <p className="text-slate-400 text-sm">Nenhuma categoria disponível</p>
                ) : (
                  categories.map((category: any) => (
                    <Button
                      key={category.id}
                      variant={selectedCategory === category.id ? "default" : "outline"}
                      className="w-full justify-start"
                      onClick={() => setSelectedCategory(category.id)}
                    >
                      {category.name}
                    </Button>
                  ))
                )}
              </CardContent>
            </Card>
          </div>

          {/* Main Content */}
          <div className="lg:col-span-3 space-y-8">
            {/* Current Playing */}
            {currentTrack && (
              <Card className="bg-gradient-to-r from-purple-600 to-blue-600 border-0">
                <CardContent className="pt-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="text-2xl font-bold text-white mb-1">{currentTrack.title}</h3>
                      <p className="text-purple-100">{currentTrack.artist || "Artista desconhecido"}</p>
                    </div>
                    <Button
                      size="lg"
                      className="rounded-full w-16 h-16 bg-white text-purple-600 hover:bg-slate-100"
                      onClick={() => setIsPlaying(!isPlaying)}
                    >
                      {isPlaying ? (
                        <Pause className="w-8 h-8" />
                      ) : (
                        <Play className="w-8 h-8" />
                      )}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Tracks List */}
            <Card className="bg-slate-800 border-slate-700">
              <CardHeader>
                <CardTitle className="text-white">
                  {selectedCategory
                    ? categories.find((c: any) => c.id === selectedCategory)?.name || "Faixas"
                    : "Selecione uma categoria"}
                </CardTitle>
                <CardDescription>
                  {tracks.length} faixa{tracks.length !== 1 ? "s" : ""} disponível{tracks.length !== 1 ? "is" : ""}
                </CardDescription>
              </CardHeader>
              <CardContent>
                {!selectedCategory ? (
                  <p className="text-slate-400 text-center py-8">Selecione uma categoria para ver as faixas</p>
                ) : tracksLoading ? (
                  <div className="flex justify-center py-8">
                    <Spinner />
                  </div>
                ) : tracks.length === 0 ? (
                  <p className="text-slate-400 text-center py-8">Nenhuma faixa disponível nesta categoria</p>
                ) : (
                  <div className="space-y-2">
                    {tracks.map((track: any) => (
                      <div
                        key={track.id}
                        className={`p-4 rounded-lg cursor-pointer transition-all ${
                          currentTrack?.id === track.id
                            ? "bg-purple-600"
                            : "bg-slate-700 hover:bg-slate-600"
                        }`}
                        onClick={() => handlePlayTrack(track)}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex-1">
                            <h4 className="font-semibold text-white">{track.title}</h4>
                            <p className="text-slate-300 text-sm">
                              {track.artist || "Artista desconhecido"}
                              {track.album && ` • ${track.album}`}
                            </p>
                          </div>
                          {track.duration && (
                            <Badge variant="secondary" className="ml-4">
                              {Math.floor(track.duration / 60)}:{String(track.duration % 60).padStart(2, "0")}
                            </Badge>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}
