'use client';

import { Button, Icon, LoaderSpinner, Select } from '@theme/components';
import clsx from 'clsx';
import { useMemo } from 'react';

type QuantityDisplayType = 'buttons' | 'dropdown';

type QuantityStyles = {
  width?: string;
  height?: string;
  color?: string;
  'background-color'?: string;
  'border-color'?: string;
  'border-width'?: string;
  'border-radius'?: string;
  'font-size'?: string;
  'font-weight'?: string | number;
  'button-color'?: string;
  'button-hover-color'?: string;
};

interface QuantitySelectorProps {
  quantity: number;
  onChange?: (newQuantity: number) => void;
  min?: number;
  max?: number;
  isLoading?: boolean;
  disabled?: boolean;
  className?: string;
  displayType?: QuantityDisplayType;
  maxDropdownOptions?: number;
  styles?: QuantityStyles;
  isSelected?: boolean;
  onDesignerClick?: () => void;
}

/**
 * QuantitySelector Component
 *
 * Supports two display modes:
 * - 'buttons': Plus/minus buttons with number display (default)
 * - 'dropdown': Select dropdown with quantity options
 *
 * Styles can be customized via Theme Editor through the styles prop.
 */
export const QuantitySelector = ({
  quantity,
  onChange,
  min = 1,
  max = 999,
  isLoading = false,
  disabled = false,
  className = '',
  displayType = 'buttons',
  maxDropdownOptions = 10,
  styles = {},
  isSelected = false,
  onDesignerClick
}: QuantitySelectorProps) => {
  const handleDecrease = () => {
    if (quantity > min && onChange) {
      onChange(quantity - 1);
    }
  };

  const handleIncrease = () => {
    if (quantity < max && onChange) {
      onChange(quantity + 1);
    }
  };

  const handleDropdownChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newQuantity = parseInt(e.target.value, 10);
    if (!isNaN(newQuantity) && onChange) {
      onChange(newQuantity);
    }
  };

  // Generate dropdown options
  const dropdownOptions = useMemo(() => {
    const optionCount = Math.min(max - min + 1, maxDropdownOptions);
    return Array.from({ length: optionCount }, (_, i) => ({
      value: String(min + i),
      label: String(min + i)
    }));
  }, [min, max, maxDropdownOptions]);

  // Handle designer click for section selection
  const handleContainerClick = (e: React.MouseEvent) => {
    if (onDesignerClick) {
      e.preventDefault();
      e.stopPropagation();
      onDesignerClick();
    }
  };

  if (displayType === 'dropdown') {
    return (
      <div
        className={clsx(
          isSelected && 'ring-2 ring-blue-500 ring-offset-2',
          className
        )}
        onClick={handleContainerClick}
      >
        {isLoading ? (
          <div
            className="flex items-center justify-center border"
            style={{
              width: styles.width || '138px',
              height: styles.height || '44px'
            }}
          >
            <LoaderSpinner className="w-4 h-4" />
          </div>
        ) : (
          <Select
            value={String(quantity)}
            onChange={handleDropdownChange}
            options={dropdownOptions}
            disabled={disabled}
            labelClassName="inline-block"
            className="cursor-pointer w-full"
            style={{
              width: styles.width || '138px',
              height: styles.height || '44px',
              backgroundColor: styles['background-color'],
              borderColor: styles['border-color'],
              borderWidth: styles['border-width'],
              borderRadius: styles['border-radius'],
              fontSize: styles['font-size'],
              fontWeight: styles['font-weight'],
              color: styles.color
            }}
          />
        )}
      </div>
    );
  }

  // Default: Buttons mode
  return (
    <div
      className={clsx(
        'quantity-selector flex items-center justify-between border p-4',
        isSelected && 'ring-2 ring-blue-500 ring-offset-2',
        className
      )}
      style={
        {
          width: styles.width || '138px',
          height: styles.height || '44px',
          backgroundColor: styles['background-color'],
          borderColor: styles['border-color'],
          borderWidth: styles['border-width'],
          borderRadius: styles['border-radius'],
          borderStyle: styles['border-width'] ? 'solid' : undefined,
          '--quantity-button-color': styles['button-color'],
          '--quantity-button-hover-color': styles['button-hover-color']
        } as React.CSSProperties
      }
      onClick={handleContainerClick}
    >
      <Button
        className={clsx(
          'quantity-btn h-auto p-0 hover:bg-transparent',
          styles['button-color'] ? '' : 'hover:text-black'
        )}
        style={{
          color: styles['button-color'] || undefined
        }}
        appearance="ghost"
        onClick={disabled ? undefined : handleDecrease}
        disabled={disabled || isLoading || quantity <= min}
      >
        <Icon name="minus" size={12} />
      </Button>
      <div
        style={{
          color: styles.color,
          fontSize: styles['font-size'],
          fontWeight: styles['font-weight']
        }}
      >
        {isLoading ? (
          <LoaderSpinner className="w-4 h-4" />
        ) : (
          <span>{quantity}</span>
        )}
      </div>
      <Button
        className={clsx(
          'quantity-btn h-auto p-0 hover:bg-transparent',
          styles['button-color'] ? '' : 'hover:text-black'
        )}
        style={{
          color: styles['button-color'] || undefined
        }}
        appearance="ghost"
        onClick={disabled ? undefined : handleIncrease}
        disabled={disabled || isLoading || quantity >= max}
      >
        <Icon name="plus" size={12} />
      </Button>

      {/* Inline style for hover states */}
      <style jsx>{`
        .quantity-selector .quantity-btn:hover:not(:disabled) {
          color: var(--quantity-button-hover-color, inherit) !important;
        }
      `}</style>
    </div>
  );
};
