import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { usePlaylist } from '../hooks/usePlaylist';
import { useQuery } from '@tanstack/react-query';
import { playlistsApi } from '@/services/api/playlists';
import { usePlaylistPermissions } from '../hooks/usePlaylistPermissions';
import { PlaylistHeader } from '../components/PlaylistHeader';
import { PlaylistActions } from '../components/PlaylistActions';
import { PlaylistTrackList } from '../components/PlaylistTrackList';
import { AddTrackToPlaylistModal } from '../components/AddTrackToPlaylistModal';
import { CollaboratorList } from '../components/CollaboratorList';
import { PlaylistRecommendations } from '../components/PlaylistRecommendations';
import { SharePlaylistModal } from '../components/SharePlaylistModal';
import { AddCollaboratorModal } from '../components/AddCollaboratorModal';
import { Button } from '@/components/ui/button';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { Plus, Users, Sparkles } from 'lucide-react';
// CRITICAL FIX: Utiliser le wrapper lazy pour éviter les collisions de noms de variables
import toast from '@/utils/toast';
import type { Track } from '../types';

// FE-PAGE-008: Complete Playlist Detail page implementation

export function PlaylistDetailPage() {
  const { id } = useParams<{ id: string }>();
  const [isAddTrackModalOpen, setIsAddTrackModalOpen] = useState(false);
  const [isShareModalOpen, setIsShareModalOpen] = useState(false);
  const [isAddCollaboratorModalOpen, setIsAddCollaboratorModalOpen] =
    useState(false);

  const { data: playlist, isLoading, error, refetch } = usePlaylist(id || '');

  const permissions = usePlaylistPermissions(playlist);

  const { data: collaborators, refetch: refetchCollaborators } = useQuery({
    queryKey: ['playlistCollaborators', id],
    queryFn: () => playlistsApi.getCollaborators(id || ''),
    enabled: !!id && permissions.canRead,
  });

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <LoadingSpinner />
        </div>
      </div>
    );
  }

  if (error || !playlist) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center">
              <h2 className="text-2xl font-bold text-destructive mb-2">
                Error
              </h2>
              <p className="text-muted-foreground">
                {error instanceof Error
                  ? error.message
                  : 'Failed to load playlist'}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  const tracks =
    (playlist.tracks?.map((pt) => pt.track).filter((t) => !!t) as Track[]) ||
    [];
  const playlistTracks = playlist.tracks || [];

  const handleTrackAdded = () => {
    setIsAddTrackModalOpen(false);
    refetch();
    toast.success('Track added to playlist');
  };

  const handleTrackRemoved = () => {
    refetch();
    toast.success('Track removed from playlist');
  };

  const handleTracksReordered = () => {
    refetch();
    toast.success('Playlist tracks reordered');
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <PlaylistHeader playlist={playlist} />

      <div className="mb-6">
        <PlaylistActions
          playlist={playlist}
          onUpdated={refetch}
          onShareClick={() => setIsShareModalOpen(true)}
          canShare={permissions.canRead}
        />
      </div>

      {/* FE-PAGE-008: Tabs for Tracks, Collaborators, Recommendations */}
      <Tabs defaultValue="tracks" className="w-full">
        <TabsList>
          <TabsTrigger value="tracks">Tracks</TabsTrigger>
          {permissions.canRead && (
            <TabsTrigger value="collaborators">
              <Users className="mr-2 h-4 w-4" />
              Collaborators
            </TabsTrigger>
          )}
          <TabsTrigger value="recommendations">
            <Sparkles className="mr-2 h-4 w-4" />
            Recommendations
          </TabsTrigger>
        </TabsList>

        <TabsContent value="tracks" className="mt-6">
          <div className="mb-4 flex justify-between items-center">
            <h2 className="text-2xl font-bold">Tracks</h2>
            {permissions.canAddTracks && (
              <Button
                onClick={() => setIsAddTrackModalOpen(true)}
                className="gap-2"
              >
                <Plus className="h-4 w-4" />
                Ajouter des tracks
              </Button>
            )}
          </div>

          <PlaylistTrackList
            playlistTracks={playlistTracks}
            tracks={tracks}
            playlistId={playlist.id}
            onTrackRemoved={handleTrackRemoved}
            onTracksReordered={handleTracksReordered}
            enableDragAndDrop={permissions.canEdit}
            canRemoveTracks={permissions.canRemoveTracks}
          />
        </TabsContent>

        <TabsContent value="collaborators" className="mt-6">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2">
                  <Users className="h-5 w-5" />
                  Collaborators
                </CardTitle>
                {permissions.canManageCollaborators && (
                  <Button
                    onClick={() => setIsAddCollaboratorModalOpen(true)}
                    size="sm"
                  >
                    <Plus className="mr-2 h-4 w-4" />
                    Add Collaborator
                  </Button>
                )}
              </div>
            </CardHeader>
            <CardContent>
              <CollaboratorList
                collaborators={collaborators || []}
                playlistId={playlist.id}
                canManage={permissions.canManageCollaborators}
              />
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="recommendations" className="mt-6">
          <Card>
            <CardContent className="pt-6">
              <PlaylistRecommendations
                limit={12}
                minScore={0.1}
                includeOwn={false}
                onPlaylistClick={(recPlaylist) => {
                  // Navigate to playlist detail
                  window.location.href = `/playlists/${recPlaylist.id}`;
                }}
              />
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      <AddTrackToPlaylistModal
        open={isAddTrackModalOpen}
        onClose={() => setIsAddTrackModalOpen(false)}
        playlistId={playlist.id}
        onTracksAdded={handleTrackAdded}
      />

      {/* FE-PAGE-008: Share Modal */}
      {playlist && (
        <SharePlaylistModal
          open={isShareModalOpen}
          onClose={() => setIsShareModalOpen(false)}
          playlistId={playlist.id}
        />
      )}

      {/* FE-PAGE-008: Add Collaborator Modal */}
      {playlist && (
        <AddCollaboratorModal
          open={isAddCollaboratorModalOpen}
          onClose={() => setIsAddCollaboratorModalOpen(false)}
          playlistId={playlist.id}
          onAdded={() => {
            refetchCollaborators();
            refetch();
          }}
        />
      )}
    </div>
  );
}
