import { useState } from 'react';
import { TrackSearchParams } from '../services/trackSearchService';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectOption } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';

/**
 * TrackSearchFilters Component
 * T0305: Composant pour les filtres avancés de recherche de tracks
 */

const GENRES: SelectOption[] = [
  { value: '', label: 'Tous les genres' },
  { value: 'Rock', label: 'Rock' },
  { value: 'Pop', label: 'Pop' },
  { value: 'Jazz', label: 'Jazz' },
  { value: 'Classical', label: 'Classique' },
  { value: 'Electronic', label: 'Électronique' },
  { value: 'Hip-Hop', label: 'Hip-Hop' },
  { value: 'Country', label: 'Country' },
  { value: 'Blues', label: 'Blues' },
  { value: 'Reggae', label: 'Reggae' },
  { value: 'Metal', label: 'Metal' },
];

const FORMATS: SelectOption[] = [
  { value: '', label: 'Tous les formats' },
  { value: 'MP3', label: 'MP3' },
  { value: 'FLAC', label: 'FLAC' },
  { value: 'WAV', label: 'WAV' },
  { value: 'OGG', label: 'OGG' },
  { value: 'M4A', label: 'M4A' },
  { value: 'AAC', label: 'AAC' },
];

const TAG_MODE_OPTIONS: SelectOption[] = [
  { value: 'OR', label: 'OU (au moins un tag)' },
  { value: 'AND', label: 'ET (tous les tags)' },
];

const SORT_OPTIONS: SelectOption[] = [
  { value: 'created_at', label: 'Date de création' },
  { value: 'title', label: 'Titre' },
  { value: 'popularity', label: 'Popularité' },
  { value: 'play_count', label: "Nombre d'écoutes" },
  { value: 'comment_count', label: 'Nombre de commentaires' },
  { value: 'duration', label: 'Durée' },
  { value: 'artist', label: 'Artiste' },
];

const SORT_ORDER_OPTIONS: SelectOption[] = [
  { value: 'desc', label: 'Décroissant' },
  { value: 'asc', label: 'Croissant' },
];

interface TrackSearchFiltersProps {
  filters: Partial<TrackSearchParams>;
  onFiltersChange: (filters: Partial<TrackSearchParams>) => void;
  className?: string;
}

export function TrackSearchFilters({
  filters,
  onFiltersChange,
  className,
}: TrackSearchFiltersProps) {
  const [tagsInput, setTagsInput] = useState(filters.tags?.join(', ') || '');
  const [showAdvanced, setShowAdvanced] = useState(false);

  const updateFilter = (key: keyof TrackSearchParams, value: any) => {
    onFiltersChange({
      ...filters,
      [key]: value || undefined,
    });
  };

  const handleTagsChange = (value: string) => {
    setTagsInput(value);
    const tags = value
      .split(',')
      .map((tag) => tag.trim())
      .filter((tag) => tag.length > 0);
    updateFilter('tags', tags.length > 0 ? tags : undefined);
  };

  const clearFilters = () => {
    onFiltersChange({});
    setTagsInput('');
  };

  const hasActiveFilters = Boolean(
    filters.genre ||
      filters.format ||
      filters.tags?.length ||
      filters.minDuration ||
      filters.maxDuration ||
      filters.minBPM ||
      filters.maxBPM ||
      filters.minDate ||
      filters.maxDate,
  );

  return (
    <div className={cn('space-y-4', className)}>
      {/* Basic Filters */}
      <div className="flex flex-wrap gap-4 items-end">
        <div className="flex-1 min-w-[200px]">
          <Label htmlFor="genre">Genre</Label>
          <Select
            options={GENRES}
            value={filters.genre || ''}
            onChange={(value) => {
              const genre = Array.isArray(value) ? value[0] : value;
              updateFilter('genre', genre || undefined);
            }}
            placeholder="Tous les genres"
            className="w-full mt-1"
          />
        </div>

        <div className="flex-1 min-w-[200px]">
          <Label htmlFor="format">Format</Label>
          <Select
            options={FORMATS}
            value={filters.format || ''}
            onChange={(value) => {
              const format = Array.isArray(value) ? value[0] : value;
              updateFilter('format', format || undefined);
            }}
            placeholder="Tous les formats"
            className="w-full mt-1"
          />
        </div>

        <div className="flex-1 min-w-[200px]">
          <Label htmlFor="sortBy">Trier par</Label>
          <Select
            options={SORT_OPTIONS}
            value={filters.sortBy || 'created_at'}
            onChange={(value) => {
              const sortBy = Array.isArray(value) ? value[0] : value;
              updateFilter('sortBy', sortBy || 'created_at');
            }}
            placeholder="Trier par"
            className="w-full mt-1"
          />
        </div>

        <div className="flex-1 min-w-[200px]">
          <Label htmlFor="sortOrder">Ordre</Label>
          <Select
            options={SORT_ORDER_OPTIONS}
            value={filters.sortOrder || 'desc'}
            onChange={(value) => {
              const sortOrder = Array.isArray(value) ? value[0] : value;
              updateFilter('sortOrder', sortOrder || 'desc');
            }}
            placeholder="Ordre"
            className="w-full mt-1"
          />
        </div>

        {hasActiveFilters && (
          <Button
            variant="outline"
            size="sm"
            onClick={clearFilters}
            className="mb-0"
          >
            <X className="h-4 w-4 mr-2" />
            Réinitialiser
          </Button>
        )}
      </div>

      {/* Advanced Filters Toggle */}
      <div>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setShowAdvanced(!showAdvanced)}
          className="text-sm"
        >
          {showAdvanced ? 'Masquer' : 'Afficher'} les filtres avancés
        </Button>
      </div>

      {/* Advanced Filters */}
      {showAdvanced && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4 border rounded-lg bg-muted/50">
          {/* Tags */}
          <div className="space-y-2">
            <Label htmlFor="tags">Tags (séparés par des virgules)</Label>
            <Input
              id="tags"
              type="text"
              placeholder="rock, pop, jazz"
              value={tagsInput}
              onChange={(e) => handleTagsChange(e.target.value)}
            />
            <div className="flex gap-2">
              <Label htmlFor="tagMode" className="text-xs">
                Mode:
              </Label>
              <Select
                options={TAG_MODE_OPTIONS}
                value={filters.tagMode || 'OR'}
                onChange={(value) => {
                  const tagMode = Array.isArray(value) ? value[0] : value;
                  updateFilter('tagMode', tagMode || 'OR');
                }}
                className="flex-1"
              />
            </div>
          </div>

          {/* Duration Range */}
          <div className="space-y-2">
            <Label>Durée (secondes)</Label>
            <div className="flex gap-2">
              <div className="flex-1">
                <Label htmlFor="minDuration" className="text-xs">
                  Min
                </Label>
                <Input
                  id="minDuration"
                  type="number"
                  placeholder="0"
                  value={filters.minDuration || ''}
                  onChange={(e) => {
                    const value = e.target.value
                      ? parseInt(e.target.value, 10)
                      : undefined;
                    updateFilter('minDuration', value);
                  }}
                  min={0}
                />
              </div>
              <div className="flex-1">
                <Label htmlFor="maxDuration" className="text-xs">
                  Max
                </Label>
                <Input
                  id="maxDuration"
                  type="number"
                  placeholder="∞"
                  value={filters.maxDuration || ''}
                  onChange={(e) => {
                    const value = e.target.value
                      ? parseInt(e.target.value, 10)
                      : undefined;
                    updateFilter('maxDuration', value);
                  }}
                  min={0}
                />
              </div>
            </div>
          </div>

          {/* BPM Range */}
          <div className="space-y-2">
            <Label>BPM</Label>
            <div className="flex gap-2">
              <div className="flex-1">
                <Label htmlFor="minBPM" className="text-xs">
                  Min
                </Label>
                <Input
                  id="minBPM"
                  type="number"
                  placeholder="0"
                  value={filters.minBPM || ''}
                  onChange={(e) => {
                    const value = e.target.value
                      ? parseInt(e.target.value, 10)
                      : undefined;
                    updateFilter('minBPM', value);
                  }}
                  min={0}
                />
              </div>
              <div className="flex-1">
                <Label htmlFor="maxBPM" className="text-xs">
                  Max
                </Label>
                <Input
                  id="maxBPM"
                  type="number"
                  placeholder="∞"
                  value={filters.maxBPM || ''}
                  onChange={(e) => {
                    const value = e.target.value
                      ? parseInt(e.target.value, 10)
                      : undefined;
                    updateFilter('maxBPM', value);
                  }}
                  min={0}
                />
              </div>
            </div>
          </div>

          {/* Date Range */}
          <div className="space-y-2">
            <Label>Date de création</Label>
            <div className="flex gap-2">
              <div className="flex-1">
                <Label htmlFor="minDate" className="text-xs">
                  Depuis
                </Label>
                <Input
                  id="minDate"
                  type="date"
                  value={filters.minDate ? filters.minDate.split('T')[0] : ''}
                  onChange={(e) => {
                    const value = e.target.value
                      ? `${e.target.value}T00:00:00Z`
                      : undefined;
                    updateFilter('minDate', value);
                  }}
                />
              </div>
              <div className="flex-1">
                <Label htmlFor="maxDate" className="text-xs">
                  Jusqu'à
                </Label>
                <Input
                  id="maxDate"
                  type="date"
                  value={filters.maxDate ? filters.maxDate.split('T')[0] : ''}
                  onChange={(e) => {
                    const value = e.target.value
                      ? `${e.target.value}T23:59:59Z`
                      : undefined;
                    updateFilter('maxDate', value);
                  }}
                />
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
