/**
 * LocationSelector Component
 *
 * A reusable dropdown for selecting a business location.
 * Hidden when only one location exists.
 */

import React from 'react';
import { useLocations } from '../hooks/useLocations';
import { FormSelect, SelectOption } from './ui/FormSelect';
import { Location } from '../types';

interface LocationSelectorProps {
  /** Currently selected location ID */
  value?: number | null;
  /** Callback when location is selected */
  onChange: (locationId: number | null) => void;
  /** Label for the selector */
  label?: string;
  /** Error message */
  error?: string;
  /** Hint text */
  hint?: string;
  /** Placeholder text */
  placeholder?: string;
  /** Whether the field is required */
  required?: boolean;
  /** Whether to include inactive locations */
  includeInactive?: boolean;
  /** Whether the selector is disabled */
  disabled?: boolean;
  /** Force show even with single location (for admin purposes) */
  forceShow?: boolean;
  /** Container class name */
  className?: string;
}

/**
 * LocationSelector - Dropdown for selecting a business location
 *
 * Automatically hides when:
 * - Only one active location exists (unless forceShow is true)
 * - Locations are still loading
 *
 * The component auto-selects the only location when there's just one.
 */
export const LocationSelector: React.FC<LocationSelectorProps> = ({
  value,
  onChange,
  label = 'Location',
  error,
  hint,
  placeholder = 'Select a location',
  required = false,
  includeInactive = false,
  disabled = false,
  forceShow = false,
  className = '',
}) => {
  const { data: locations, isLoading, isError } = useLocations({ includeInactive });

  // Don't render if loading or error
  if (isLoading || isError) {
    return null;
  }

  // Filter to only active locations if not including inactive
  const availableLocations = locations ?? [];

  // Hide if only one location (unless forceShow)
  if (availableLocations.length <= 1 && !forceShow) {
    return null;
  }

  // Build options from locations
  const options: SelectOption<string>[] = availableLocations.map((loc: Location) => ({
    value: String(loc.id),
    label: loc.is_primary
      ? `${loc.name} (Primary)`
      : loc.is_active
        ? loc.name
        : `${loc.name} (Inactive)`,
    disabled: !loc.is_active && !includeInactive,
  }));

  const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedValue = e.target.value;
    onChange(selectedValue ? Number(selectedValue) : null);
  };

  return (
    <FormSelect
      label={label}
      value={value ? String(value) : ''}
      onChange={handleChange}
      options={options}
      error={error}
      hint={hint}
      placeholder={placeholder}
      required={required}
      disabled={disabled}
      containerClassName={className}
    />
  );
};

/**
 * Hook to determine if location selector should be shown
 */
export const useShouldShowLocationSelector = (includeInactive = false): boolean => {
  const { data: locations, isLoading } = useLocations({ includeInactive });

  if (isLoading) return false;
  return (locations?.length ?? 0) > 1;
};

/**
 * Hook to auto-select location when only one exists
 */
export const useAutoSelectLocation = (
  currentValue: number | null | undefined,
  onChange: (locationId: number | null) => void
) => {
  const { data: locations } = useLocations();

  React.useEffect(() => {
    // Auto-select if only one location and no value selected
    if (locations?.length === 1 && !currentValue) {
      onChange(locations[0].id);
    }
  }, [locations, currentValue, onChange]);
};

export default LocationSelector;
