import React from "react";

import { Chip, Grid2 as Grid } from "@mui/material";

import Card from "../../../components/Card";
import CardHeader from "../../../components/Card/CardHeader";
import { useUser } from "../../../contexts/UserContext";
import { ContribComponent, LimitOffset } from "../../../types";
import { hasPermission } from "../../../util/has_permission";
import SubscriptionsCardContent from "../components/SubscriptionsCardContent";
import { Subscription } from "../types/subscription";

const SubscriptionsCard: ContribComponent<LimitOffset<Subscription>> = ({
  data: { next: _next, previous: _previous, results },
  params,
  refresh,
}) => {
  const { user } = useUser();
  const { membership_number } = params as { membership_number?: number };

  return (
    <Grid container columns={12} spacing={3} width={"100%"}>
      {results.map((subscription, index) => (
        <Card
          key={subscription.id}
          isCollapsible
          isEditable={
            hasPermission(user, "subscription.change_subscription") &&
            subscription.membership_number === membership_number
          }
          isOpen={index === 0 && subscription.state !== "ENDED"}
          sx={{ overflow: "hidden" }}
        >
          <CardHeader title={subscription.name}>
            {!subscription.is_cancelled &&
              subscription.state !== "ENDED" &&
              subscription.state !== "PENDING" && (
                <Chip color="success" label={subscription.state} size="small" />
              )}

            {subscription.is_cancelled && subscription.state !== "ENDED" && (
              <Chip color="warning" label={subscription.state} size="small" />
            )}

            {subscription.state === "ENDED" && (
              <Chip color="default" label={subscription.state} size="small" />
            )}

            {subscription.state === "PENDING" && (
              <Chip color="info" label={subscription.state} size="small" />
            )}
          </CardHeader>

          <SubscriptionsCardContent
            membership_number={membership_number}
            refresh={refresh}
            subscription={subscription}
          />
        </Card>
      ))}
    </Grid>
  );
};

export default SubscriptionsCard;
