import Select, { type StylesConfig } from "react-select";

type Option = { value: string; label: string };

type Props = {
  inputId: string;
  options: Option[];
  value: string;
  invalid?: boolean;
  onChange: (value: string) => void;
};

const formSelectStyles: StylesConfig<Option, false> = {
  container: (base) => ({
    ...base,
    width: "100%",
  }),
  control: (base, state) => ({
    ...base,
    minHeight: "40px",
    height: "40px",
    border: "1px solid #c4c4c4",
    borderRadius: "3px",
    boxShadow: "none",
    background: "#fff",
    cursor: "pointer",
    "&:hover": { borderColor: "#c4c4c4" },
    ...(state.isFocused ? { borderColor: "var(--fb-blue, #002b97)", boxShadow: "none" } : {}),
  }),
  valueContainer: (base) => ({
    ...base,
    height: "38px",
    padding: "0 0.55rem",
  }),
  indicatorsContainer: (base) => ({
    ...base,
    height: "38px",
  }),
  dropdownIndicator: (base) => ({
    ...base,
    padding: "0 6px",
    color: "#6b7280",
  }),
  indicatorSeparator: () => ({ display: "none" }),
  singleValue: (base) => ({
    ...base,
    color: "var(--fb-ink, #070614)",
    fontSize: "13px",
  }),
  placeholder: (base) => ({
    ...base,
    color: "#6b7280",
    fontSize: "13px",
  }),
  input: (base) => ({
    ...base,
    margin: 0,
    padding: 0,
    fontSize: "13px",
  }),
  menu: (base) => ({
    ...base,
    zIndex: 40,
    fontSize: "13px",
    border: "1px solid #c4c4c4",
    boxShadow: "0 8px 24px rgba(0, 43, 151, 0.12)",
  }),
  option: (base, state) => ({
    ...base,
    fontSize: "13px",
    padding: "0.45rem 0.65rem",
    backgroundColor: state.isSelected ? "#002b97" : state.isFocused ? "#eef3ff" : "#fff",
    color: state.isSelected ? "#fff" : "#070614",
    cursor: "pointer",
  }),
  menuPortal: (base) => ({ ...base, zIndex: 9999 }),
};

export function BookingNationalitySelect({
  inputId,
  options,
  value,
  invalid = false,
  onChange,
}: Props) {
  const selected = options.find((o) => o.value === value) ?? null;

  return (
    <div className={`ferry-booking__select-wrap${invalid ? " is-invalid" : ""}`}>
    <Select<Option, false>
      inputId={inputId}
      aria-label="Quốc tịch"
      classNamePrefix="fb-form-select"
      isClearable={false}
      isSearchable
      menuPlacement="auto"
      menuPortalTarget={typeof document !== "undefined" ? document.body : undefined}
      menuPosition="fixed"
      noOptionsMessage={() => "Không tìm thấy quốc gia"}
      options={options}
      placeholder="Chọn quốc tịch"
      styles={formSelectStyles}
      value={selected}
      onChange={(opt) => onChange(opt?.value ?? "")}
    />
    </div>
  );
}
