/* eslint-disable no-param-reassign */
import React, { useMemo, useState } from "react";
import PropTypes from "prop-types";
import { useSelector } from "react-redux";
import { makeStyles } from "@mui/styles";
import { Feature } from "ol";
import { Divider, MenuItem, Tab, Tabs, Typography } from "@mui/material";
import useTranslation from "../../utils/useTranslation";
import Select from "../../components/Select/Select";
import Link from "../../components/Link";
import { energieleitungenColorMapping } from "../../utils/constants";
import capitalizeFirstLetter from "../../utils/capitalizeFirstLetter";
import formatPhone from "../../utils/formatPhone";
import PersonCard from "../../components/PersonCard";
import safeJsonParse from "../../utils/safeJsonParse";
const useStyles = makeStyles(theme => {
  return {
    title: {
      padding: "8px 0",
      fontFamily: ["SBBWeb-Bold", "Arial", "sans-serif"],
      display: "flex",
      alignItems: "baseline",
      gap: 10
    },
    subtitle: {
      color: theme.palette.text.secondary
    },
    icon: {
      backgroundColor: "black",
      display: "inline-block"
    },
    unterwerk: {
      backgroundColor: "black",
      width: "10px",
      height: "10px",
      display: "inline-block",
      flex: "0 0 10px"
    },
    produktionsanlage: {
      width: "7px",
      height: "7px",
      borderRadius: "8px",
      border: "2px solid white",
      outline: "1.5px solid black",
      flex: "0 0 7px"
    },
    divider: {
      margin: "10px 0"
    },
    tabPanel: {
      paddingTop: theme.spacing(2),
      paddingBottom: theme.spacing(2),
      paddingRight: theme.spacing(1),
      paddingLeft: theme.spacing(1),
      borderTop: "1px solid #dddddd",
      marginTop: -4
    },
    tab: {
      minWidth: 0
    },
    segmentIcon: {
      "&::before": {
        position: "absolute",
        content: '"•"',
        top: 3,
        left: -2
      },
      "&::after": {
        position: "absolute",
        content: '"•"',
        top: 3,
        right: -2
      },
      fontSize: 18,
      position: "relative",
      borderBottom: "1px solid black",
      width: "60%",
      height: "52%",
      transform: "rotate(-45deg)",
      marginLeft: 6,
      marginTop: -2,
      transformOrigin: "bottom"
    },
    menuItem: {
      width: props => props.selectWidth - 40,
      textOverflow: "ellipsis",
      whiteSpace: "nowrap",
      display: "block"
    }
  };
});
const TABS = ["asset_management", "intervention", "sicherheitsrelevant"];
const SICHERHEITSRELEVANT_CATEGORIES = ["schalt_erd_berechtigt", "sachverstaendig", "instruiert"];
export function EnergiePopupSubtitle(_ref) {
  let {
    kategorie,
    unterkategorie,
    label
  } = _ref;
  const classes = useStyles();
  const {
    t
  } = useTranslation();
  return kategorie ? /*#__PURE__*/React.createElement("div", {
    className: classes.title
  }, kategorie === "UW" && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classes.unterwerk, " ").concat(classes.icon)
  }), /*#__PURE__*/React.createElement("div", {
    className: classes.label
  }, capitalizeFirstLetter(label || t("Unterwerk")), unterkategorie ? /*#__PURE__*/React.createElement("span", {
    className: classes.subtitle
  }, " - ", t("".concat(unterkategorie.trim()))) : "")), kategorie === "KW" && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "".concat(classes.produktionsanlage, " ").concat(classes.icon)
  }), /*#__PURE__*/React.createElement("div", {
    className: classes.label
  }, capitalizeFirstLetter(label || t("Produktionsanlage")), unterkategorie ? /*#__PURE__*/React.createElement("span", {
    className: classes.subtitle
  }, " - ", t("".concat(unterkategorie.trim()))) : ""))) : null;
}
EnergiePopupSubtitle.propTypes = {
  kategorie: PropTypes.string,
  unterkategorie: PropTypes.string,
  label: PropTypes.string
};
function InterventionPersonCard(_ref2) {
  let {
    person,
    segments = []
  } = _ref2;
  const {
    t
  } = useTranslation();
  const classes = useStyles();
  return /*#__PURE__*/React.createElement(PersonCard, {
    name: person.name,
    phone: person.phone,
    division: person.division,
    otherDetails: segments && segments.length && [{
      id: "segments",
      label: segments.join(", "),
      icon: /*#__PURE__*/React.createElement("div", {
        title: t("Liniensegmente"),
        className: classes.segmentIcon
      })
    }]
  });
}
InterventionPersonCard.propTypes = {
  person: PropTypes.shape(PersonCard.propTypes).isRequired,
  segments: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number]))
};
const validatedParseProperty = (feature, property) => {
  return feature.get(property) && safeJsonParse(feature.get(property));
};
const renderSicherheitsrelevantPersons = (sbbPersons, externalPersons) => {
  return [...(sbbPersons || []), ...(externalPersons || [])].map(person => /*#__PURE__*/React.createElement(PersonCard, {
    key: person.name,
    name: person.name,
    email: person.email,
    phone: person.phone,
    division: person.division
  }));
};
function EnergiePopup(_ref3) {
  let {
    feature
  } = _ref3;
  const {
    t
  } = useTranslation();
  const activeTopic = useSelector(state => state.app.activeTopic);
  const permissionInfos = useSelector(state => state.app.permissionInfos);
  const [tab, setTab] = useState(TABS[0]);
  const [selectWidth, setSelectWidth] = useState(0);
  const [sicherheitActiveCat, setSicherheitActiveCat] = useState(SICHERHEITSRELEVANT_CATEGORIES[0]);
  const handleChange = (event, newTab) => setTab(TABS[newTab]);
  const classes = useStyles({
    selectWidth
  });
  // General Info
  const kategorie = feature.get("kategorie");
  const unterkategorie = feature.get("unterkategorie");
  const trassennummer = feature.get("trassennummer");
  const losNr = feature.get("los_nr");
  const description = useMemo(() => feature.getGeometry().getType() === "Point" ? "".concat(feature.get("bezeichnung"), " (").concat(feature.get("anlage_id"), ")") : feature.get("bezeichnung"), [feature]);
  const adresse = feature.get("adresse");

  // Asset management
  const anlagenverantwortlicher = useMemo(() => feature.get("anlagebetreuer") && safeJsonParse(feature.get("anlagebetreuer")), [feature]);
  const anlagenverantwortlicherExtern = useMemo(() => feature.get("anlagebetreuer_extern") && safeJsonParse(feature.get("anlagebetreuer_extern")), [feature]);
  const betriebInstandhaltung = useMemo(() => feature.get("betrieb_instandhaltung") && safeJsonParse(feature.get("betrieb_instandhaltung")), [feature]);
  const lifeCycleManager = useMemo(() => feature.get("life_cycle_manager") && safeJsonParse(feature.get("life_cycle_manager")), [feature]);

  // Intervention
  const interventionPikettNummerTag = formatPhone(feature.get("intervention_pikettnummer_tag"));
  const interventionPikettNummerNacht = formatPhone(feature.get("intervention_pikettnummer_nacht"));
  const interventionPikettNummerDetail = feature.get("intervention_pikettnummer_detail");
  const interventionMail = feature.get("intervention_mail");
  const interventionMailDetail = feature.get("intervention_mail_detail");
  const interventionBemerkungen = feature.get("intervention_bemerkungen");
  const interventionExternePersonen = validatedParseProperty(feature, "intervention_energie_persons");
  const interventionSbbPersonen = validatedParseProperty(feature, "intervention_persons");

  // Sicherheitsrelevant
  const sicherheitsrelevantLink = feature.get("sicherheitsrelevant_link");
  const sicherheitsrelevantBemerkungen = feature.get("sicherheitsrelevant_bemerkungen");
  const sicherheitsrelevantInstruiertExternalPersons = validatedParseProperty(feature, "sicherheitsrelevant_instruiert_energie_persons");
  const sicherheitsrelevantInstruiertSbbPersons = validatedParseProperty(feature, "sicherheitsrelevant_instruiert_persons");
  const sicherheitsrelevantSachverstaendigExternalPersons = validatedParseProperty(feature, "sicherheitsrelevant_sachverstaendige_energie_persons");
  const sicherheitsrelevantSachverstaendigSbbPersons = validatedParseProperty(feature, "sicherheitsrelevant_sachverstaendige_persons");
  const sicherheitsrelevantSchaltErdExternalPersons = validatedParseProperty(feature, "sicherheitsrelevant_schalt_erd_berechtigt_energie_persons");
  const sicherheitsrelevantSchaltErdSbbPersons = validatedParseProperty(feature, "sicherheitsrelevant_schalt_erd_berechtigt_persons");
  const mainInfo = useMemo(() => {
    return /*#__PURE__*/React.createElement(React.Fragment, null, kategorie ? /*#__PURE__*/React.createElement(EnergiePopupSubtitle, {
      kategorie: kategorie,
      unterkategorie: unterkategorie
    }) : /*#__PURE__*/React.createElement(Typography, {
      className: classes.title
    }, /*#__PURE__*/React.createElement("b", null, t("Übertragungsleitung"))), /*#__PURE__*/React.createElement(Divider, {
      className: classes.divider
    }), /*#__PURE__*/React.createElement(Typography, null, trassennummer ? /*#__PURE__*/React.createElement("b", {
      style: {
        color: energieleitungenColorMapping["los".concat(losNr)]
      }
    }, trassennummer, " ") : "", description), adresse && /*#__PURE__*/React.createElement("div", {
      "data-testid": "energie-address"
    }, /*#__PURE__*/React.createElement(Typography, null, adresse)));
  }, [kategorie, unterkategorie, classes, t, trassennummer, losNr, description, adresse]);
  return /*#__PURE__*/React.createElement("div", null, permissionInfos !== null && permissionInfos !== void 0 && permissionInfos.user && activeTopic.permission === "sbb" ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Tabs, {
    value: TABS.indexOf(tab),
    onChange: handleChange,
    variant: "fullWidth",
    className: classes.tabs
  }, /*#__PURE__*/React.createElement(Tab, {
    className: classes.tab,
    label: t("asset_management")
  }), /*#__PURE__*/React.createElement(Tab, {
    className: classes.tab,
    label: t("intervention")
  }), /*#__PURE__*/React.createElement(Tab, {
    className: classes.tab,
    label: t("sicherheitsrelevant")
  })), /*#__PURE__*/React.createElement("div", {
    className: classes.tabPanel,
    ref: el => setSelectWidth(el === null || el === void 0 ? void 0 : el.clientWidth)
  }, mainInfo, /*#__PURE__*/React.createElement("br", null), tab === TABS[0] && /*#__PURE__*/React.createElement(React.Fragment, null, anlagenverantwortlicher && /*#__PURE__*/React.createElement(PersonCard, {
    title: t("ch.sbb.energie.anlagenverantwortlich"),
    name: anlagenverantwortlicher.name,
    email: anlagenverantwortlicher.email,
    phone: anlagenverantwortlicher.phone,
    division: anlagenverantwortlicher.division
  }), anlagenverantwortlicherExtern && /*#__PURE__*/React.createElement(PersonCard, {
    title: t("ch.sbb.energie.anlagenverantwortlich.extern"),
    name: anlagenverantwortlicherExtern.name,
    email: anlagenverantwortlicherExtern.email,
    phone: anlagenverantwortlicherExtern.phone
  }), betriebInstandhaltung && /*#__PURE__*/React.createElement(PersonCard, {
    title: t("ch.sbb.energie.betrieb_instandhaltung"),
    name: betriebInstandhaltung.name,
    email: betriebInstandhaltung.email,
    phone: betriebInstandhaltung.phone,
    division: betriebInstandhaltung.division
  }), lifeCycleManager && /*#__PURE__*/React.createElement(PersonCard, {
    title: t("ch.sbb.energie.life_cycle_manager"),
    name: lifeCycleManager.name,
    email: lifeCycleManager.email,
    phone: lifeCycleManager.phone,
    division: lifeCycleManager.division
  })), tab === TABS[1] && /*#__PURE__*/React.createElement(React.Fragment, null, (interventionPikettNummerTag || interventionPikettNummerNacht) && /*#__PURE__*/React.createElement(Typography, {
    paragraph: true
  }, /*#__PURE__*/React.createElement("b", null, t("Pikettnummern"), ": "), interventionPikettNummerTag && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("br", null), "".concat(interventionPikettNummerTag, " (").concat(t("Tag"), ")")), interventionPikettNummerNacht && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("br", null), "".concat(interventionPikettNummerNacht, " (").concat(t("Nacht"), ")")), interventionPikettNummerDetail && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("br", null), /*#__PURE__*/React.createElement("br", null), interventionPikettNummerDetail)), interventionMail && /*#__PURE__*/React.createElement(Typography, {
    paragraph: true
  }, /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement("b", null, t("E-Mail"), ": "), /*#__PURE__*/React.createElement("a", {
    href: "mailto:".concat(interventionMail)
  }, interventionMail)), interventionMailDetail && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("br", null), /*#__PURE__*/React.createElement("br", null), interventionMailDetail)), interventionBemerkungen && /*#__PURE__*/React.createElement(Typography, {
    paragraph: true
  }, /*#__PURE__*/React.createElement("i", null, interventionBemerkungen)), interventionSbbPersonen === null || interventionSbbPersonen === void 0 ? void 0 : interventionSbbPersonen.map(sbbPerson => {
    const {
      person,
      linienabschnitte
    } = sbbPerson;
    return /*#__PURE__*/React.createElement(InterventionPersonCard, {
      key: person.name,
      person: person,
      segments: linienabschnitte
    });
  }), interventionExternePersonen === null || interventionExternePersonen === void 0 ? void 0 : interventionExternePersonen.map(externalPerson => {
    const {
      energie_person: person,
      linienabschnitte
    } = externalPerson;
    return /*#__PURE__*/React.createElement(InterventionPersonCard, {
      key: person.name,
      person: person,
      segments: linienabschnitte
    });
  })), tab === TABS[2] && /*#__PURE__*/React.createElement(React.Fragment, null, sicherheitsrelevantLink && /*#__PURE__*/React.createElement(Typography, {
    paragraph: true
  }, /*#__PURE__*/React.createElement(Link, {
    href: sicherheitsrelevantLink
  }, t("Mehr Information"))), sicherheitsrelevantBemerkungen && /*#__PURE__*/React.createElement(Typography, {
    paragraph: true
  }, /*#__PURE__*/React.createElement("i", null, sicherheitsrelevantBemerkungen)), /*#__PURE__*/React.createElement(Select, {
    value: sicherheitActiveCat,
    onChange: evt => setSicherheitActiveCat(evt.target.value),
    fullWidth: true,
    MenuProps: {
      marginThreshold: 0
    },
    "data-cy": "sicherheitsrelevant-category-select"
  }, [...SICHERHEITSRELEVANT_CATEGORIES].map(value => {
    return /*#__PURE__*/React.createElement(MenuItem, {
      key: value,
      value: value,
      className: classes.menuItem,
      title: t(value),
      "data-cy": "av-role-option-".concat(value)
    }, t(value));
  })), sicherheitActiveCat === SICHERHEITSRELEVANT_CATEGORIES[0] // Schalt- erdberechtigt
  ? renderSicherheitsrelevantPersons(sicherheitsrelevantSchaltErdSbbPersons, sicherheitsrelevantSchaltErdExternalPersons) : null, sicherheitActiveCat === SICHERHEITSRELEVANT_CATEGORIES[1] // Sachverständig
  ? renderSicherheitsrelevantPersons(sicherheitsrelevantSachverstaendigSbbPersons, sicherheitsrelevantSachverstaendigExternalPersons) : null, sicherheitActiveCat === SICHERHEITSRELEVANT_CATEGORIES[2] // Instruiert
  ? renderSicherheitsrelevantPersons(sicherheitsrelevantInstruiertSbbPersons, sicherheitsrelevantInstruiertExternalPersons) : null))) : /*#__PURE__*/React.createElement(React.Fragment, null, mainInfo, /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement("a", {
    href: "mailto:trassensicherung-energie@sbb.ch",
    rel: "noopener noreferrer",
    target: "_blank"
  }, "trassensicherung-energie@sbb.ch"))));
}
EnergiePopup.propTypes = {
  feature: PropTypes.instanceOf(Feature).isRequired
};
EnergiePopup.renderTitle = (feat, layer, t) => t("Detailinformationen");
export default EnergiePopup;
//# sourceMappingURL=EnergiePopup.js.map