import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import {
  usePlaylists,
  useAddTrackToPlaylist,
} from '@/features/playlists/hooks/usePlaylist';
import {
  getTracks,
  batchDeleteTracks,
  batchUpdateTracks,
  type GetTracksParams,
} from '@/features/tracks/api/trackApi';
import type { Track } from '@/features/tracks/types/track';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Upload,
  Search,
  Music,
  MoreVertical,
  Play,
  Plus,
  Filter,
  ArrowUpDown,
  Trash2,
  CheckSquare,
  X,
} from 'lucide-react';
import { Input } from '@/components/ui/input';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
  DropdownMenuPortal,
  DropdownMenuLabel,
} from '@/components/ui/dropdown-menu';
import { Select } from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { UploadModal } from '@/features/upload/components/UploadModal';
import { useToast } from '@/hooks/useToast';
import { Checkbox } from '@/components/ui/checkbox';
import { Pagination } from '@/components/navigation/Pagination';

// FE-PAGE-002: Complete Library page implementation

type SortField = 'created_at' | 'title' | 'popularity';
type SortOrder = 'asc' | 'desc';

export default function LibraryPage() {
  const queryClient = useQueryClient();
  const toast = useToast();
  const [page, setPage] = useState(1);
  const [limit] = useState(50);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);

  // FE-PAGE-002: Filtering and sorting state
  const [searchTerm, setSearchTerm] = useState('');
  const [genreFilter, setGenreFilter] = useState<string>('');
  const [formatFilter, setFormatFilter] = useState<string>('');
  const [sortBy, setSortBy] = useState<SortField>('created_at');
  const [sortOrder, setSortOrder] = useState<SortOrder>('desc');

  // FE-PAGE-002: Bulk operations state
  const [selectedTracks, setSelectedTracks] = useState<Set<string>>(new Set());
  const [isBulkMode, setIsBulkMode] = useState(false);

  // Build query params
  const queryParams: GetTracksParams = {
    page,
    limit,
    sortBy,
    sortOrder,
  };

  if (genreFilter) {
    queryParams.genre = genreFilter;
  }
  if (formatFilter) {
    queryParams.format = formatFilter;
  }

  const {
    data: tracksData,
    isLoading: isTracksLoading,
    isError: isTracksError,
    error: tracksError,
  } = useQuery({
    queryKey: ['tracks', 'library', queryParams],
    queryFn: () => getTracks(page, limit, queryParams),
  });

  const { data: playlistsData } = usePlaylists();
  const addTrackToPlaylistMutation = useAddTrackToPlaylist();

  // FE-PAGE-002: Client-side search filtering (since backend search might not be implemented)
  const filteredTracks: Track[] =
    tracksData?.tracks.filter(
      (track: Track) =>
        track.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (track.artist || '').toLowerCase().includes(searchTerm.toLowerCase()),
    ) || [];

  // FE-PAGE-002: Get unique genres and formats for filters
  const genres = Array.from(
    new Set(
      tracksData?.tracks
        .map((t) => t.genre)
        .filter((g): g is string => !!g) || [],
    ),
  ).sort();
  const formats = Array.from(
    new Set(
      tracksData?.tracks
        .map((t) => t.format)
        .filter((f): f is string => !!f) || [],
    ),
  ).sort();

  const handleAddToPlaylist = async (playlistId: string, trackId: string) => {
    try {
      await addTrackToPlaylistMutation.mutateAsync({ playlistId, trackId });
      toast.success('Piste ajoutée à la playlist');
    } catch (error) {
      console.error(error);
      toast.error('Impossible d\'ajouter la piste à la playlist');
    }
  };

  const handleOpenUpload = () => {
    setIsUploadModalOpen(true);
  };

  const handleCloseUpload = () => {
    setIsUploadModalOpen(false);
    // Refresh tracks after upload
    queryClient.invalidateQueries({ queryKey: ['tracks'] });
  };

  // FE-PAGE-002: Toggle track selection
  const toggleTrackSelection = (trackId: string) => {
    setSelectedTracks((prev) => {
      const next = new Set(prev);
      if (next.has(trackId)) {
        next.delete(trackId);
      } else {
        next.add(trackId);
      }
      return next;
    });
  };

  // FE-PAGE-002: Select all / deselect all
  const toggleSelectAll = () => {
    if (selectedTracks.size === filteredTracks.length) {
      setSelectedTracks(new Set());
    } else {
      setSelectedTracks(new Set(filteredTracks.map((t) => t.id)));
    }
  };

  // FE-PAGE-002: Bulk delete
  const handleBulkDelete = async () => {
    if (selectedTracks.size === 0) return;

    if (
      !confirm(
        `Êtes-vous sûr de vouloir supprimer ${selectedTracks.size} piste(s) ?`,
      )
    ) {
      return;
    }

    try {
      await batchDeleteTracks(Array.from(selectedTracks));
      toast.success(`${selectedTracks.size} piste(s) supprimée(s)`);
      setSelectedTracks(new Set());
      setIsBulkMode(false);
      queryClient.invalidateQueries({ queryKey: ['tracks'] });
    } catch (error) {
      console.error(error);
      toast.error('Impossible de supprimer les pistes');
    }
  };

  // FE-PAGE-002: Bulk update (e.g., make public/private)
  const handleBulkUpdate = async (updates: { is_public?: boolean }) => {
    if (selectedTracks.size === 0) return;

    try {
      await batchUpdateTracks(Array.from(selectedTracks), updates);
      toast.success(`${selectedTracks.size} piste(s) mise(s) à jour`);
      setSelectedTracks(new Set());
      setIsBulkMode(false);
      queryClient.invalidateQueries({ queryKey: ['tracks'] });
    } catch (error) {
      console.error(error);
      toast.error('Impossible de mettre à jour les pistes');
    }
  };

  // FE-PAGE-002: Toggle sort order
  const handleSort = (field: SortField) => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(field);
      setSortOrder('desc');
    }
  };

  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>
        <div className="flex gap-2">
          {isBulkMode && selectedTracks.size > 0 && (
            <>
              <Button
                variant="destructive"
                onClick={handleBulkDelete}
                disabled={selectedTracks.size === 0}
              >
                <Trash2 className="mr-2 h-4 w-4" />
                Supprimer ({selectedTracks.size})
              </Button>
              <Button
                variant="outline"
                onClick={() => handleBulkUpdate({ is_public: true })}
              >
                Rendre public ({selectedTracks.size})
              </Button>
              <Button
                variant="outline"
                onClick={() => handleBulkUpdate({ is_public: false })}
              >
                Rendre privé ({selectedTracks.size})
              </Button>
            </>
          )}
          <Button
            variant={isBulkMode ? 'default' : 'outline'}
            onClick={() => {
              setIsBulkMode(!isBulkMode);
              setSelectedTracks(new Set());
            }}
          >
            {isBulkMode ? (
              <>
                <X className="mr-2 h-4 w-4" />
                Annuler
              </>
            ) : (
              <>
                <CheckSquare className="mr-2 h-4 w-4" />
                Sélection multiple
              </>
            )}
          </Button>
          <Button onClick={handleOpenUpload}>
            <Upload className="mr-2 h-4 w-4" />
            Upload Track
          </Button>
        </div>
      </div>

      {/* FE-PAGE-002: Filters and sorting */}
      <Card>
        <CardContent className="p-4 space-y-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>
          <div className="flex flex-wrap gap-4">
            <div className="flex items-center gap-2">
              <Filter className="h-4 w-4 text-muted-foreground" />
              <Select
                options={[
                  { value: '', label: 'Tous les genres' },
                  ...genres.map((genre) => ({ value: genre, label: genre })),
                ]}
                value={genreFilter}
                onChange={(value) => setGenreFilter(Array.isArray(value) ? value[0] : value)}
                placeholder="Tous les genres"
                className="w-[180px]"
              />
            </div>
            <div className="flex items-center gap-2">
              <Select
                options={[
                  { value: '', label: 'Tous les formats' },
                  ...formats.map((format) => ({ value: format, label: format })),
                ]}
                value={formatFilter}
                onChange={(value) => setFormatFilter(Array.isArray(value) ? value[0] : value)}
                placeholder="Tous les formats"
                className="w-[180px]"
              />
            </div>
            <div className="flex items-center gap-2 ml-auto">
              <span className="text-sm text-muted-foreground">Trier par:</span>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" size="sm">
                    <ArrowUpDown className="mr-2 h-4 w-4" />
                    {sortBy === 'created_at'
                      ? 'Date'
                      : sortBy === 'title'
                        ? 'Titre'
                        : 'Popularité'}
                    {sortOrder === 'asc' ? ' ↑' : ' ↓'}
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent>
                  <DropdownMenuLabel>Trier par</DropdownMenuLabel>
                  <DropdownMenuItem onClick={() => handleSort('created_at')}>
                    Date {sortBy === 'created_at' && (sortOrder === 'asc' ? '↑' : '↓')}
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => handleSort('title')}>
                    Titre {sortBy === 'title' && (sortOrder === 'asc' ? '↑' : '↓')}
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => handleSort('popularity')}>
                    Popularité {sortBy === 'popularity' && (sortOrder === 'asc' ? '↑' : '↓')}
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
        </CardContent>
      </Card>

      {isTracksLoading ? (
        <div className="text-center py-12">Chargement...</div>
      ) : isTracksError ? (
        <Card>
          <CardContent className="p-6">
            <div className="text-center text-destructive">
              <p className="font-medium">Erreur lors du chargement des pistes</p>
              <p className="text-sm text-muted-foreground mt-2">
                {tracksError instanceof Error
                  ? tracksError.message
                  : 'Une erreur est survenue'}
              </p>
            </div>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  {isBulkMode && (
                    <TableHead className="w-12">
                      <Checkbox
                        checked={
                          filteredTracks.length > 0 &&
                          selectedTracks.size === filteredTracks.length
                        }
                        onCheckedChange={toggleSelectAll}
                      />
                    </TableHead>
                  )}
                  <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: Track, index: number) => (
                  <TableRow
                    key={track.id}
                    className={
                      selectedTracks.has(track.id) ? 'bg-muted/50' : ''
                    }
                  >
                    {isBulkMode && (
                      <TableCell>
                        <Checkbox
                          checked={selectedTracks.has(track.id)}
                          onCheckedChange={() => toggleTrackSelection(track.id)}
                        />
                      </TableCell>
                    )}
                    <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={isBulkMode ? 6 : 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>
      )}

      {/* FE-COMP-006: Pagination component */}
      {tracksData?.pagination && tracksData.pagination.total_pages > 1 && (
        <Pagination
          currentPage={page}
          totalPages={tracksData.pagination.total_pages}
          onPageChange={setPage}
          totalItems={tracksData.pagination.total}
          itemsPerPage={limit}
          showItemsInfo={true}
          className="mt-6"
        />
      )}

      <UploadModal open={isUploadModalOpen} onClose={handleCloseUpload} />
    </div>
  );
}
