/**
 * Search history sidebar — `Ранее искали` accordion (TIRREDESIGN-5).
 *
 * Mirrors Angular's `search-history` component: a collapsible frame
 * with a `Ранее искали` header and a list of recent searches. Each
 * row shows a plane icon (online-board) or alarm-clock icon
 * (schedule), the city pair (`Москва — Самара`) and a date row
 * (`20.04.2026 - 26.04.2026`, plus inbound dates for round-trip).
 *
 * @module
 */

import { type FC, useState, useCallback } from "react";
import { useNavigate } from "@modern-js/runtime/router";
import { useTranslation } from "@/i18n/provider.js";
import { useLocale } from "@/i18n/useLocale.js";
import { useDictionaries } from "@/shared/dictionaries/index.js";
import {
  useSearchHistory,
  type SearchHistoryItem,
} from "@/shared/hooks/useSearchHistory.js";
import "./SearchHistory.scss";

/** yyyyMMdd → dd.MM.yyyy. */
function formatDate(yyyymmdd?: string): string {
  if (!yyyymmdd || yyyymmdd.length !== 8) return "";
  return `${yyyymmdd.slice(6, 8)}.${yyyymmdd.slice(4, 6)}.${yyyymmdd.slice(0, 4)}`;
}

export const SearchHistory: FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { language } = useLocale();
  const { dictionaries } = useDictionaries(language);

  const { items } = useSearchHistory(language);
  const [expanded, setExpanded] = useState(false);

  const cityName = (code?: string): string => {
    if (!code) return "";
    if (!dictionaries) return code;
    const upper = code.toUpperCase();
    const city = dictionaries.cityByCode.get(upper);
    if (city) return city.name;
    const airport = dictionaries.airportByCode.get(upper);
    if (airport) return airport.name;
    return code;
  };

  const handleItemClick = useCallback(
    (item: SearchHistoryItem) => {
      void navigate(item.url);
    },
    [navigate],
  );

  if (items.length === 0) return null;

  const toggle = (): void => setExpanded((v) => !v);

  return (
    <section className="frame search-history" data-testid="search-history">
      <div className="p-accordion">
        <div
          className={`p-accordion-tab${
            expanded ? " p-accordion-tab--active" : ""
          }`}
        >
          <div
            className={`p-accordion-header${expanded ? " p-highlight" : ""}`}
          >
            <a
              role="button"
              tabIndex={0}
              aria-expanded={expanded}
              onClick={toggle}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  toggle();
                }
              }}
            >
              <span className="p-header">
                <span>{t("BOARD.YOU_SEARCH")}</span>
                <span
                  className={`arrow-icon${
                    expanded ? " arrow-icon--rotated" : ""
                  }`}
                  aria-hidden="true"
                >
                  <svg viewBox="0 0 12 8" width="12" height="8">
                    <path
                      d="M1 1L6 6L11 1"
                      stroke="currentColor"
                      strokeWidth="1.5"
                      fill="none"
                    />
                  </svg>
                </span>
              </span>
            </a>
          </div>
          {expanded && (
            <div className="p-accordion-content">
              <div className="search-history__content">
                {items.map((item) => {
                  const params = item.params ?? {};
                  const isSchedule = item.type === "schedule-route";
                  const isFlightNumber = item.type === "flight-number";
                  const dep = cityName(params.departure);
                  const arr = cityName(params.arrival);
                  const dateLine = isSchedule
                    ? [
                        formatDate(params.dateFrom),
                        formatDate(params.dateTo),
                      ]
                        .filter(Boolean)
                        .join(" - ")
                    : formatDate(params.dateFrom);
                  const inboundLine = isSchedule
                    ? [
                        formatDate(params.inboundDateFrom),
                        formatDate(params.inboundDateTo),
                      ]
                        .filter(Boolean)
                        .join(" - ")
                    : "";
                  const titleParts: string[] = [];
                  if (isSchedule) {
                    titleParts.push(t("SCHEDULE.TITLE"));
                    titleParts.push(
                      params.inboundDateFrom
                        ? t("SHARED.THERE_AND_BACK")
                        : t("SHARED.PART_ONE_WAY"),
                    );
                    if (params.directOnly) titleParts.push(t("SHARED.ONLY_DIRECT"));
                  }
                  return (
                    <div
                      key={item.url}
                      className="search-history-item"
                      role="button"
                      tabIndex={0}
                      aria-label={item.label}
                      onClick={() => handleItemClick(item)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter" || e.key === " ") {
                          e.preventDefault();
                          handleItemClick(item);
                        }
                      }}
                      data-testid="search-history-item"
                    >
                      <div
                        className="search-history-item__icon"
                        aria-hidden="true"
                        title={
                          isSchedule
                            ? t("SHARED.LAST-SEARCH-SCHEDULE")
                            : t("SHARED.LAST-SEARCH-BOARD")
                        }
                      >
                        <svg viewBox="0 0 24 24" width="18" height="18">
                          {isSchedule ? (
                            <path
                              d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm0 18a8 8 0 1 1 8-8 8 8 0 0 1-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"
                              fill="currentColor"
                            />
                          ) : (
                            <path
                              d="M21 14l-9-4V5a1.5 1.5 0 0 0-3 0v5l-9 4v2l9-3v5l-2 1.5V20l3.5-1L14 20v-1.5L12 17v-5l9 3z"
                              fill="currentColor"
                            />
                          )}
                        </svg>
                      </div>
                      <div className="search-history-item__data">
                        {isSchedule && titleParts.length > 0 && (
                          <div className="search-history-item__title">
                            {titleParts.join(", ")}
                          </div>
                        )}
                        {isFlightNumber ? (
                          <div className="search-history-item__city">
                            {params.flightNumber || item.label}
                          </div>
                        ) : (
                          <div className="search-history-item__city">
                            {dep && arr ? `${dep} — ${arr}` : item.label}
                          </div>
                        )}
                        {(dateLine || inboundLine) && (
                          <div className="search-history-item__date">
                            {dateLine}
                            {inboundLine ? ` / ${inboundLine}` : ""}
                            {params.timeRange ? ` ${params.timeRange}` : ""}
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
};
