import { useState, useMemo, type FC } from "react";
import { buildCountryCityRows } from "./buildCountryCityRows.js";
import type { IAirport, IDictionaries } from "@/shared/dictionaries/index.js";
import "./CityPickerPopup.scss";

export interface CityPickerPopupProps {
  dictionaries: IDictionaries;
  selectedCode?: string;
  onSelect: (code: string) => void;
  onLocate?: () => void | Promise<void>;
}

export const CityPickerPopup: FC<CityPickerPopupProps> = ({
  dictionaries,
  selectedCode,
  onSelect,
  onLocate,
}) => {
  const regions = dictionaries.regions;
  const [activeRegionId, setActiveRegionId] = useState<number>(
    regions[0]?.id ?? 0,
  );

  const rows = useMemo(
    () => buildCountryCityRows(dictionaries, activeRegionId),
    [dictionaries, activeRegionId],
  );

  return (
    <div className="city-autocomplete-popup" data-testid="city-picker-popup">
      <div className="tabs">
        {regions.map((r) => (
          <button
            key={r.id}
            type="button"
            role="tab"
            aria-selected={r.id === activeRegionId}
            className={`tab-button${r.id === activeRegionId ? " active" : ""}`}
            onClick={() => setActiveRegionId(r.id)}
            data-testid={`city-picker-tab-${r.id}`}
          >
            {r.name}
          </button>
        ))}
      </div>

      <div className="content">
        <div className="content--scroll-panel">
          {rows.map((row, idx) => {
            const rowKey = `${row.countryName ?? ""}-${row.city1?.code ?? ""}-${idx}`;
            const isMulti = Boolean(row.city1Airports);
            return (
              <div
                key={rowKey}
                className={`row${row.countryName ? " country-start-row" : ""}`}
              >
                <div className="cell contry">
                  <div>{row.countryName ?? ""}</div>
                </div>

                {!isMulti && row.city1 && (
                  <>
                    <div
                      className={`cell city${row.city1.code === selectedCode ? " city-active" : ""}`}
                      data-testid={`city-name-cell-${row.city1.name}`}
                    >
                      <div
                        className="city--item"
                        role="button"
                        tabIndex={0}
                        onClick={() => onSelect(row.city1!.code)}
                        onKeyDown={(e) => {
                          if (e.key === "Enter" || e.key === " ") onSelect(row.city1!.code);
                        }}
                      >
                        {row.city1.name}
                      </div>
                    </div>
                    <div className={`cell city${row.city2?.code === selectedCode ? " city-active" : ""}`}>
                      {row.city2 && (
                        <div
                          className="city--item"
                          role="button"
                          tabIndex={0}
                          data-testid={`city-name-cell-${row.city2.name}`}
                          onClick={() => onSelect(row.city2!.code)}
                          onKeyDown={(e) => {
                            if (e.key === "Enter" || e.key === " ") onSelect(row.city2!.code);
                          }}
                        >
                          {row.city2.name}
                        </div>
                      )}
                    </div>
                  </>
                )}

                {isMulti && row.city1 && (
                  <div className={`cell city${row.city1.code === selectedCode ? " city-active" : ""}`}>
                    <div
                      className="city--item"
                      role="button"
                      tabIndex={0}
                      data-testid={`city-name-cell-${row.city1.name}`}
                      onClick={() => onSelect(row.city1!.code)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter" || e.key === " ") onSelect(row.city1!.code);
                      }}
                    >
                      {row.city1.name}
                    </div>
                    <div className="airports-column">
                      {row.city1Airports!.map((ap: IAirport) => (
                        <div
                          key={ap.code}
                          title={ap.name}
                          className="city--item"
                          role="button"
                          tabIndex={0}
                          data-testid={`airport-name-cell-${ap.name}`}
                          onClick={() => onSelect(ap.code)}
                          onKeyDown={(e) => {
                            if (e.key === "Enter" || e.key === " ") onSelect(ap.code);
                          }}
                        >
                          {ap.name}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {onLocate && (
        <div className="city-autocomplete-popup-footer">
          <div className="gps-contaner">
            <button
              type="button"
              className="gps-button color blue-light"
              onClick={() => void onLocate()}
              data-testid="city-picker-locate"
            >
              GPS
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
