import { useState } from 'react';
import { useMyTracks } from '../hooks/useMyTracks';
import { usePlaylists, useAddTrackToPlaylist } from '@/features/playlists/hooks/usePlaylists';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Upload,
  Search,
  Music,
  MoreVertical,
  Play,
  Plus,
} from 'lucide-react';
import { Input } from '@/components/ui/input';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
  DropdownMenuPortal,
} from '@/components/ui/dropdown-menu';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';

export default function LibraryPage() {
  const { data: tracksData, isLoading: isTracksLoading } = useMyTracks();
  const { data: playlistsData } = usePlaylists();
  const addTrackToPlaylistMutation = useAddTrackToPlaylist();
  
  const [searchTerm, setSearchTerm] = useState('');

  const handleAddToPlaylist = async (playlistId: number, trackId: number) => {
    try {
      await addTrackToPlaylistMutation.mutateAsync({ playlistId, trackId });
      // TODO: Show toast success
    } catch (error) {
      console.error(error);
      // TODO: Show toast error
    }
  };

  const filteredTracks = tracksData?.tracks.filter(track => 
    track.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    track.artist.toLowerCase().includes(searchTerm.toLowerCase())
  ) || [];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Bibliothèque</h1>
          <p className="text-muted-foreground">
            Gérez vos fichiers et documents
          </p>
        </div>
        <Button>
          <Upload className="mr-2 h-4 w-4" />
          Uploader un fichier
        </Button>
      </div>

      <Card>
        <CardContent className="p-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="Rechercher dans la bibliothèque..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
        </CardContent>
      </Card>

      {isTracksLoading ? (
        <div className="text-center py-12">Chargement...</div>
      ) : (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">#</TableHead>
                  <TableHead>Titre</TableHead>
                  <TableHead>Artiste</TableHead>
                  <TableHead>Durée</TableHead>
                  <TableHead className="w-12"></TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredTracks.map((track, index) => (
                  <TableRow key={track.id}>
                    <TableCell>{index + 1}</TableCell>
                    <TableCell className="font-medium">
                      <div className="flex items-center gap-2">
                        <Button size="icon" variant="ghost" className="h-6 w-6">
                          <Play className="h-3 w-3" />
                        </Button>
                        {track.title}
                      </div>
                    </TableCell>
                    <TableCell>{track.artist}</TableCell>
                    <TableCell>{Math.floor(track.duration / 60)}:{(track.duration % 60).toString().padStart(2, '0')}</TableCell>
                    <TableCell>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8">
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuSub>
                            <DropdownMenuSubTrigger>
                              <Plus className="mr-2 h-4 w-4" />
                              Ajouter à une playlist
                            </DropdownMenuSubTrigger>
                            <DropdownMenuPortal>
                              <DropdownMenuSubContent>
                                {playlistsData?.playlists.map(playlist => (
                                  <DropdownMenuItem 
                                    key={playlist.id}
                                    onClick={() => handleAddToPlaylist(playlist.id, track.id)}
                                  >
                                    {playlist.title}
                                  </DropdownMenuItem>
                                ))}
                                {(!playlistsData?.playlists || playlistsData.playlists.length === 0) && (
                                  <DropdownMenuItem disabled>
                                    Aucune playlist
                                  </DropdownMenuItem>
                                )}
                              </DropdownMenuSubContent>
                            </DropdownMenuPortal>
                          </DropdownMenuSub>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
                {filteredTracks.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={5} className="text-center py-12">
                      <div className="flex flex-col items-center justify-center text-muted-foreground">
                        <Music className="h-12 w-12 mb-4" />
                        <p>Aucun titre trouvé</p>
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
