import React, { useState, useEffect } from 'react';
import Select, { components, StylesConfig } from 'react-select';

type OptionType = {
  label: string;
  value: string;
  link: string;
};

type Props = {
  options: OptionType[];
  placeholder?: string;
};

const CustomOption = (props: any) => {
  const { data, innerRef, innerProps, isFocused } = props;

  return (
    <div ref={innerRef} {...innerProps}>
      <a
        href={data.link}
        //  target="_blank"
        rel="noopener noreferrer"
        style={{
          display: 'block',
          padding: '8px 12px',
          backgroundColor: isFocused ? 'rgba(255,255,255,0.1)' : 'transparent',
          color: '#F5F2E8',
          textDecoration: 'none',
          fontFamily: '"Barlow", sans-serif',
          fontSize: '14px',
          fontWeight: 500
        }}
      >
        {data.label}
      </a>
    </div>
  );
};

const LinkSelect: React.FC<Props> = ({ options, placeholder = 'Seleccionar ciudad' }) => {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };

    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  const customStyles: StylesConfig<OptionType, false> = {
    control: (base) => ({
      ...base,
      backgroundColor: 'transparent',
      border: 'none',
      boxShadow: 'none',
      color: '#F5F2E8',
      minHeight: 'auto',
      fontFamily: '"Barlow", sans-serif',
      fontSize: '14px',
      fontWeight: 500
    }),
    singleValue: (base) => ({
      ...base,
      color: '#F5F2E8',
      fontFamily: '"Barlow", sans-serif',
      fontSize: '14px',
      fontWeight: 500
    }),
    input: (base) => ({
      ...base,
      color: '#F5F2E8',
      fontFamily: '"Barlow", sans-serif',
      fontSize: '14px',
      fontWeight: 500
    }),
    placeholder: (base) => ({
      ...base,
      color: '#F5F2E8',
      fontFamily: '"Barlow", sans-serif',
      fontSize: '14px',
      fontWeight: 500
    }),
    indicatorSeparator: () => ({
      display: 'none'
    }),
    dropdownIndicator: (base) => ({
      ...base,
      color: '#F5F2E8',
      padding: 4,
      '&:hover': {
        color: '#F5F2E8'
      }
    }),
    menu: (base) => ({
      ...base,
      backgroundColor: '#3A3A3A',
      boxShadow: 'none',
      border: '1px solid rgba(245, 242, 232, 0.2)',
      fontFamily: '"Barlow", sans-serif'
    }),
    menuList: (base) => ({
      ...base,
      maxHeight: isMobile ? '120px' : '180px',
      overflowY: 'auto'
    }),
    option: () => ({})
  };

  return (
    <Select
      options={options}
      placeholder={placeholder}
      isSearchable
      components={{ Option: CustomOption }}
      styles={customStyles}
    />
  );
};

export default LinkSelect;
