import React, { useState } from "react";
import "./SectionHeader.css";
import { Link, useNavigate } from "react-router-dom";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import CDeviceSelect from "../../components/CDeviceSelect";
import { setSelectedDevice } from "../../stores/slices/deviceSlice";
import { BiArrowBack } from "react-icons/bi";
import { useTranslation } from "react-i18next";
import CButton from "../../components/CButton";
import CInfo from "../../components/CInfo";

interface SectionHeaderProps {
  to?: string;
}

const SectionHeader: React.FC<SectionHeaderProps> = ({ to }) => {
  const [isOpenInfoModal, setIsOpenInfoModal] = useState(false);
  const { devices, selectedDevice } = useAppSelector(
    (state: RootState) => state.device
  );
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const { t } = useTranslation();

  const handleNavigate = (e: React.MouseEvent) => {
    if (!to) {
      e.preventDefault();
      navigate(-1);
    }
  };

  const toggleInfoModal = () => {
    setIsOpenInfoModal((prev) => !prev);
  };

  return (
    <div className="sectionheader">
      <Link
        to={to || "#"}
        onClick={handleNavigate}
        className="sectionheader__link"
      >
        <BiArrowBack className="sectionheader__link__icon" />
      </Link>

      {devices.length > 0 ? (
        <CDeviceSelect
          devices={devices}
          selectedDevice={selectedDevice}
          onDeviceChange={(name) => dispatch(setSelectedDevice(name))}
          disabled={!devices.length}
          style={{ width: "220px" }}
          className="header__device-select"
          placeholder={t("common.selectDevice")}
        />
      ) : (
        <CButton
          title={t("help.howToStart")}
          onClick={toggleInfoModal}
          variant="primary"
          style={{ width: "114.66px", maxHeight: "52px" }}
        />
      )}

      <CInfo isOpen={isOpenInfoModal} onToggle={toggleInfoModal} />
    </div>
  );
};

export default SectionHeader;
