/**
 * Page PlaylistListPage
 * T0462: Create Playlist Routes
 * T0504: Create Playlist Mobile Responsive
 * T0506: Create Playlist Batch Operations
 * FE-PAGE-009: Complete Playlist List page implementation
 */

import { useState } from 'react';
import { PlaylistList } from '../components/PlaylistList';
import { CreatePlaylistDialog } from '../components/CreatePlaylistDialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
import {
  CheckSquare,
  Plus,
  Search,
  Filter,
  X,
  ArrowUpDown,
} from 'lucide-react';
import '../styles/playlists.mobile.css';

// FE-PAGE-009: Complete Playlist List page implementation

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

export function PlaylistListPage() {
  const [enableSelection, setEnableSelection] = useState(false);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [showFilters, setShowFilters] = useState(false);

  // FE-PAGE-009: Filtering state
  const [filterIsPublic, setFilterIsPublic] = useState<boolean | undefined>(
    undefined,
  );
  const [filterOwner, setFilterOwner] = useState<'all' | 'mine' | 'others'>(
    'all',
  );

  // FE-PAGE-009: Sorting state
  const [sortBy, setSortBy] = useState<SortField>('created_at');
  const [sortOrder, setSortOrder] = useState<SortOrder>('desc');

  const hasActiveFilters =
    searchQuery || filterIsPublic !== undefined || filterOwner !== 'all';

  const handleClearFilters = () => {
    setSearchQuery('');
    setFilterIsPublic(undefined);
    setFilterOwner('all');
    setSortBy('created_at');
    setSortOrder('desc');
  };

  return (
    <div className="space-y-4 sm:space-y-6 playlist-container">
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-0">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight">
            Playlists
          </h1>
          <p className="text-sm sm:text-base text-muted-foreground">
            Découvrez et gérez vos playlists
          </p>
        </div>
        <div className="flex gap-2">
          <Button
            variant="default"
            size="sm"
            onClick={() => setIsCreateDialogOpen(true)}
            className="touch-manipulation min-h-[44px] sm:min-h-0"
            aria-label="Créer une nouvelle playlist"
            data-testid="create-playlist-btn"
          >
            <Plus className="h-4 w-4 sm:mr-2" aria-hidden="true" />
            <span className="hidden sm:inline">Créer</span>
            <span className="sm:hidden">Nouvelle</span>
          </Button>
          <Button
            variant={enableSelection ? 'default' : 'outline'}
            size="sm"
            onClick={() => setEnableSelection(!enableSelection)}
            className="touch-manipulation min-h-[44px] sm:min-h-0"
            aria-label={
              enableSelection
                ? 'Désactiver la sélection'
                : 'Activer la sélection'
            }
          >
            <CheckSquare className="h-4 w-4 sm:mr-2" aria-hidden="true" />
            <span className="hidden sm:inline">
              {enableSelection ? 'Annuler' : 'Sélectionner'}
            </span>
          </Button>
        </div>
      </div>

      {/* FE-PAGE-009: Search and Filters */}
      <Card>
        <CardContent className="p-4">
          <div className="space-y-4">
            <div className="flex items-center gap-4">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <Input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Rechercher des playlists..."
                  className="pl-10"
                  data-testid="playlist-search"
                />
              </div>
              <Button
                variant="outline"
                onClick={() => setShowFilters(!showFilters)}
              >
                <Filter className="mr-2 h-4 w-4" />
                Filters
                {hasActiveFilters && (
                  <span className="ml-2 bg-blue-600 text-white rounded-full px-2 py-0.5 text-xs">
                    Active
                  </span>
                )}
              </Button>
              {hasActiveFilters && (
                <Button variant="ghost" onClick={handleClearFilters}>
                  <X className="mr-2 h-4 w-4" />
                  Clear
                </Button>
              )}
            </div>

            {showFilters && (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-4 border-t">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Visibility</label>
                  <Select
                    value={
                      filterIsPublic === undefined
                        ? 'all'
                        : filterIsPublic
                          ? 'public'
                          : 'private'
                    }
                    onChange={(value) => {
                      if (value === 'all') setFilterIsPublic(undefined);
                      else if (value === 'public') setFilterIsPublic(true);
                      else setFilterIsPublic(false);
                    }}
                    options={[
                      { value: 'all', label: 'All' },
                      { value: 'public', label: 'Public' },
                      { value: 'private', label: 'Private' },
                    ]}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Owner</label>
                  <Select
                    value={filterOwner}
                    onChange={(value) =>
                      setFilterOwner(
                        (Array.isArray(value) ? value[0] : value) as
                          | 'all'
                          | 'mine'
                          | 'others',
                      )
                    }
                    options={[
                      { value: 'all', label: 'All' },
                      { value: 'mine', label: 'My Playlists' },
                      { value: 'others', label: 'Others' },
                    ]}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Sort By</label>
                  <div className="flex gap-2">
                    <Select
                      value={sortBy}
                      onChange={(value) =>
                        setSortBy(
                          (Array.isArray(value)
                            ? value[0]
                            : value) as SortField,
                        )
                      }
                      options={[
                        { value: 'created_at', label: 'Date' },
                        { value: 'title', label: 'Title' },
                        { value: 'track_count', label: 'Tracks' },
                      ]}
                      className="flex-1"
                    />
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() =>
                        setSortOrder((prev) =>
                          prev === 'asc' ? 'desc' : 'asc',
                        )
                      }
                    >
                      <ArrowUpDown className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      <PlaylistList
        enableSelection={enableSelection}
        searchQuery={searchQuery}
        filterIsPublic={filterIsPublic}
        filterOwner={filterOwner}
        sortBy={sortBy}
        sortOrder={sortOrder}
      />
      <CreatePlaylistDialog
        open={isCreateDialogOpen}
        onOpenChange={setIsCreateDialogOpen}
        onCreated={() => {
          setIsCreateDialogOpen(false);
          // The PlaylistList will refetch automatically via usePlaylists hook
        }}
      />
    </div>
  );
}
