import { useState, useEffect, useCallback } from 'react';
import { Select } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
import { logger } from '@/utils/logger';

/**
 * FE-COMP-007: Reusable Sort component for consistent sorting UI across all pages
 */

export interface SortOption {
  value: string;
  label: string;
  icon?: React.ElementType;
}

export interface SortProps {
  sortBy: string;
  sortOrder: 'asc' | 'desc';
  onSortChange: (sortBy: string, sortOrder: 'asc' | 'desc') => void;
  options: SortOption[];
  className?: string;
  showOrderToggle?: boolean;
  persistPreference?: boolean;
  storageKey?: string;
}

/**
 * Generic Sort component for sorting lists
 */
export function Sort({
  sortBy,
  sortOrder,
  onSortChange,
  options,
  className,
  showOrderToggle = true,
  persistPreference = false,
  storageKey = 'sortOptions',
}: SortProps) {
  const [localSortBy, setLocalSortBy] = useState(sortBy);
  const [localSortOrder, setLocalSortOrder] = useState<'asc' | 'desc'>(
    sortOrder,
  );

  // Load preference from localStorage on mount if persistPreference is enabled
  useEffect(() => {
    if (persistPreference && typeof window !== 'undefined') {
      const stored = localStorage.getItem(storageKey);
      if (stored) {
        try {
          const parsed = JSON.parse(stored) as {
            sortBy: string;
            sortOrder: 'asc' | 'desc';
          };
          if (parsed.sortBy && parsed.sortOrder) {
            setLocalSortBy(parsed.sortBy);
            setLocalSortOrder(parsed.sortOrder);
            onSortChange(parsed.sortBy, parsed.sortOrder);
          }
        } catch (error) {
          logger.error('Error parsing stored sort options', {
            error: error instanceof Error ? error.message : String(error),
            stack: error instanceof Error ? error.stack : undefined,
          });
        }
      }
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Update local state when props change
  useEffect(() => {
    setLocalSortBy(sortBy);
    setLocalSortOrder(sortOrder);
  }, [sortBy, sortOrder]);

  // Persist preference to localStorage
  useEffect(() => {
    if (persistPreference && typeof window !== 'undefined') {
      localStorage.setItem(
        storageKey,
        JSON.stringify({ sortBy: localSortBy, sortOrder: localSortOrder }),
      );
    }
  }, [localSortBy, localSortOrder, persistPreference, storageKey]);

  const handleSortByChange = useCallback(
    (value: string | string[]) => {
      const newSortBy = Array.isArray(value) ? value[0] : value;
      setLocalSortBy(newSortBy);
      onSortChange(newSortBy, localSortOrder);
    },
    [localSortOrder, onSortChange],
  );

  const handleOrderToggle = useCallback(() => {
    const newOrder = localSortOrder === 'asc' ? 'desc' : 'asc';
    setLocalSortOrder(newOrder);
    onSortChange(localSortBy, newOrder);
  }, [localSortBy, localSortOrder, onSortChange]);

  const selectedOption = options.find((opt) => opt.value === localSortBy);
  const Icon = selectedOption?.icon || ArrowUpDown;

  return (
    <div
      className={cn('flex items-center gap-2', className)}
      role="group"
      aria-label="Options de tri"
    >
      {/* Sort field selector */}
      <div className="flex items-center gap-2">
        <Icon className="h-4 w-4 text-muted-foreground" />
        <Select
          options={options.map((opt) => ({
            value: opt.value,
            label: opt.label,
          }))}
          value={localSortBy}
          onChange={handleSortByChange}
          placeholder="Trier par"
          className="min-w-[150px]"
        />
      </div>

      {/* Sort order toggle */}
      {showOrderToggle && (
        <Button
          type="button"
          variant="outline"
          size="icon"
          onClick={handleOrderToggle}
          aria-label={`Trier par ordre ${localSortOrder === 'asc' ? 'décroissant' : 'croissant'}`}
          aria-pressed={localSortOrder === 'desc'}
        >
          {localSortOrder === 'asc' ? (
            <ArrowUp className="h-4 w-4" aria-hidden="true" />
          ) : (
            <ArrowDown className="h-4 w-4" aria-hidden="true" />
          )}
        </Button>
      )}
    </div>
  );
}
