import { useCallback, useMemo, useRef, useState } from "react";
import Select, { type StylesConfig } from "react-select";

import { BookingIcon } from "@/components/booking/BookingIcons";
import type { BookingRouteOption } from "@/config/booking-config";

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

type Props = {
  options: BookingRouteOption[];
  value: string;
  onChange: (routeId: string) => void;
};

function buildSelectStyles(menuWidth: number | null): StylesConfig<RouteOption, false> {
  return {
  container: (base) => ({
    ...base,
    width: "100%",
    flex: "1 1 auto",
    alignSelf: "stretch",
  }),
  control: (base, state) => ({
    ...base,
    width: "100%",
    minHeight: "38px",
    height: "38px",
    border: "none",
    boxShadow: "none",
    background: "transparent",
    cursor: "pointer",
    "&:hover": { border: "none" },
    ...(state.isFocused ? { boxShadow: "none", border: "none" } : {}),
  }),
  valueContainer: (base) => ({
    ...base,
    height: "38px",
    padding: "0 0.35rem",
  }),
  indicatorsContainer: (base) => ({
    ...base,
    height: "38px",
  }),
  dropdownIndicator: (base) => ({
    ...base,
    padding: "0 6px",
    color: "#6b7280",
  }),
  indicatorSeparator: () => ({ display: "none" }),
  singleValue: (base) => ({
    ...base,
    color: "var(--fb-blue, #002b97)",
    fontWeight: 600,
    fontSize: "13px",
  }),
  placeholder: (base) => ({
    ...base,
    color: "#6b7280",
    fontSize: "13px",
    fontWeight: 500,
  }),
  input: (base) => ({
    ...base,
    margin: 0,
    padding: 0,
    fontSize: "13px",
    color: "var(--fb-blue, #002b97)",
  }),
  menu: (base) => ({
    ...base,
    zIndex: 60,
    width: menuWidth ?? "100%",
    minWidth: menuWidth ?? "100%",
    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",
    fontWeight: state.isSelected ? 600 : 400,
    cursor: "pointer",
  }),
  menuPortal: (base) => ({ ...base, zIndex: 9999 }),
};
}

export function BookingRouteSelect({ options, value, onChange }: Props) {
  const shellRef = useRef<HTMLDivElement>(null);
  const [menuWidth, setMenuWidth] = useState<number | null>(null);
  const selectStyles = useMemo(() => buildSelectStyles(menuWidth), [menuWidth]);

  const syncMenuWidth = useCallback(() => {
    const width = shellRef.current?.getBoundingClientRect().width;
    setMenuWidth(width ? Math.round(width) : null);
  }, []);

  const routeOptions: RouteOption[] = options.map((route) => ({
    value: route.id,
    label: route.label,
  }));
  const selected = routeOptions.find((o) => o.value === value) ?? null;

  return (
    <div
      ref={shellRef}
      className="ferry-booking__route-select ferry-booking__control ferry-booking__search-route"
    >
      <span className="ferry-booking__control-addon" aria-hidden>
        <BookingIcon name="location" />
      </span>
      <div className="ferry-booking__control-body ferry-booking__control-body--select">
        <Select<RouteOption, false>
          aria-label="Chọn tuyến"
          classNamePrefix="fb-select"
          isClearable={false}
          isSearchable
          noOptionsMessage={() => "Không có tuyến phù hợp"}
          menuPlacement="auto"
          menuPortalTarget={typeof document !== "undefined" ? document.body : undefined}
          menuPosition="fixed"
          options={routeOptions}
          placeholder="Chọn tuyến"
          styles={selectStyles}
          value={selected}
          onChange={(opt) => onChange(opt?.value ?? "")}
          onMenuOpen={syncMenuWidth}
        />
      </div>
    </div>
  );
}
