import React 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";

interface SectionHeaderProps {
  to?: string;
}

const SectionHeader: React.FC<SectionHeaderProps> = ({ to }) => {
  const { devices, selectedDevice } = useAppSelector(
    (state: RootState) => state.device
  );
  const dispatch = useAppDispatch();
  const navigate = useNavigate();

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

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

      <CDeviceSelect
        devices={devices}
        selectedDevice={selectedDevice}
        onDeviceChange={(name) => dispatch(setSelectedDevice(name))}
        disabled={!devices.length}
        style={{ width: "220px" }}
        className="header__device-select"
      />
    </div>
  );
};

export default SectionHeader;
