import React, { useState } from "react";
import PropTypes from "prop-types";
import { Accordion, AccordionSummary, AccordionDetails } from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ReleaseNoteSummary from "./ReleaseNoteSummary";
import ReleaseNote from "./ReleaseNote";

const ReleaseNotesList = ({ releases }) => {
  const [flags, setFlags] = useState({});

  const handleToggle = key => (_, expanded) => {
    setFlags(prev => ({
      ...prev,
      [key]: expanded
    }));
  };

  const isCollapsed = key => {
    const expanded = flags[key];
    const collapsed = !expanded || expanded === false;
    return collapsed;
  };

  return (
    <>
      {releases.map(release => {
        return (
          <Accordion key={release.version} onChange={handleToggle(release.version)}>
            <AccordionSummary expandIcon={<ExpandMoreIcon />} id={`panel-${release.version}-header`}>
              <ReleaseNoteSummary releaseNote={release} collapsed={isCollapsed(release.version)} />
            </AccordionSummary>
            <AccordionDetails>
              <ReleaseNote releaseNote={release} />
            </AccordionDetails>
          </Accordion>
        );
      })}
    </>
  );
};

ReleaseNotesList.propTypes = {
  releases: PropTypes.array.isRequired
};

export default ReleaseNotesList;
