import { SelectHTMLAttributes, forwardRef, useId, useState } from 'react';
import styled from 'styled-components';
import type { SelectOption } from '@/shared/types/common.types';

export interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {
  label?: string;
  error?: string;
  hint?: string;
  options: SelectOption[];
  placeholder?: string;
  fullWidth?: boolean;
}

const SelectWrapper = styled.div<{ $fullWidth?: boolean }>`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.form.labelGap};
  width: ${({ $fullWidth }) => ($fullWidth ? '100%' : 'auto')};
`;

const Label = styled.label<{ $hasError?: boolean; $isFocused?: boolean }>`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  color: ${({ theme, $hasError, $isFocused }) => 
    $hasError ? theme.colors.error : 
    $isFocused ? theme.colors.primary : 
    theme.colors.gray[600]};
  transition: color ${({ theme }) => theme.transitions.fast};
`;

const SelectContainer = styled.div`
  position: relative;
  display: flex;
  align-items: center;

  &::after {
    content: '▼';
    position: absolute;
    right: 12px;
    pointer-events: none;
    color: ${({ theme }) => theme.colors.text.secondary};
    font-size: 10px;
  }

  html[dir='rtl'] &::after {
    right: auto;
    left: 12px;
  }
`;

const StyledSelect = styled.select<{ $hasError?: boolean }>`
  width: 100%;
  padding: 0.5rem ${({ theme }) => theme.spacing[3]};
  padding-right: ${({ theme }) => theme.spacing[10]};
  
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  font-family: inherit;
  
  background-color: ${({ theme }) => theme.colors.surfaceInset};
  color: ${({ theme }) => theme.colors.text.primary};
  
  border: 1px solid ${({ theme, $hasError }) =>
    $hasError ? theme.colors.error : theme.colors.border};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  
  cursor: pointer;
  appearance: none;
  
  transition: all ${({ theme }) => theme.transitions.fast};

  &:hover:not(:disabled) {
    border-color: ${({ theme, $hasError }) => 
      $hasError ? theme.colors.error : theme.colors.gray[300]};
  }

  &:focus {
    outline: none;
    border-width: 2px;
    border-color: ${({ theme, $hasError }) => 
      $hasError ? theme.colors.error : theme.colors.primary};
    padding: calc(0.5rem - 1px) calc(${({ theme }) => theme.spacing[3]} - 1px);
    padding-right: calc(${({ theme }) => theme.spacing[10]} - 1px);
  }

  &:disabled {
    background-color: ${({ theme }) => theme.colors.background};
    border-color: ${({ theme }) => theme.colors.border};
    color: ${({ theme }) => theme.colors.text.disabled};
    cursor: not-allowed;
  }

  html[dir='rtl'] & {
    padding-right: ${({ theme }) => theme.spacing[3]};
    padding-left: ${({ theme }) => theme.spacing[10]};
  }

  html[dir='rtl'] &:focus {
    padding-right: calc(${({ theme }) => theme.spacing[3]} - 1px);
    padding-left: calc(${({ theme }) => theme.spacing[10]} - 1px);
  }
`;

const HintText = styled.span<{ $isError?: boolean }>`
  margin-top: ${({ theme }) => theme.form.hintGap};
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.normal};
  color: ${({ theme, $isError }) =>
    $isError ? theme.colors.error : theme.colors.text.tertiary};
`;

export const Select = forwardRef<HTMLSelectElement, SelectProps>(
  ({ label, error, hint, options, placeholder, fullWidth, id, ...props }, ref) => {
    const [isFocused, setIsFocused] = useState(false);
    const generatedId = useId();
    const selectId = id ?? generatedId;

    return (
      <SelectWrapper $fullWidth={fullWidth}>
        {label && (
          <Label htmlFor={selectId} $hasError={!!error} $isFocused={isFocused}>
            {label}
          </Label>
        )}
        <SelectContainer>
          <StyledSelect 
            ref={ref} 
            id={selectId}
            $hasError={!!error} 
            onFocus={(e) => {
              setIsFocused(true);
              props.onFocus?.(e);
            }}
            onBlur={(e) => {
              setIsFocused(false);
              props.onBlur?.(e);
            }}
            {...props}
          >
            {placeholder && (
              <option value="" disabled>
                {placeholder}
              </option>
            )}
            {options.map((option) => (
              <option
                key={option.value}
                value={option.value}
                disabled={option.disabled}
              >
                {option.label}
              </option>
            ))}
          </StyledSelect>
        </SelectContainer>
        {(error || hint) && (
          <HintText $isError={!!error}>{error || hint}</HintText>
        )}
      </SelectWrapper>
    );
  }
);

Select.displayName = 'Select';
