import React, { useState } from "react";

import ShoppingCartOutlinedIcon from "@mui/icons-material/ShoppingCartOutlined";
import Button from "@mui/material/Button";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import CardHeader from "@mui/material/CardHeader";
import Stack from "@mui/material/Stack";
import { useTheme } from "@mui/material/styles";
import Typography from "@mui/material/Typography";
import { AdapterLuxon } from "@mui/x-date-pickers/AdapterLuxon";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";

import { DateTime } from "luxon";
import { useSnackbar } from "notistack";

import { useApi } from "../../../contexts/ApiContext";

export const PurchaseCard: React.FC = () => {
  const theme = useTheme();
  const api = useApi();
  const { enqueueSnackbar } = useSnackbar();
  const [startDate, setStartDate] = useState<DateTime | null>(null);
  const [endDate, setEndDate] = useState<DateTime | null>(null);

  const generateReport = () => {
    if (startDate === null || endDate === null) {
      enqueueSnackbar("You need to enter both a start date and an end date to generate a report", {
        variant: "error",
      });
      return;
    }

    const operation = api.operations["report.purchase:create"];
    const url = new URL(operation.server + operation.endpoint);
    url.searchParams.set("start_date", startDate.toISODate()!);
    url.searchParams.set("end_date", endDate.toISODate()!);

    const a = document.createElement("a");
    a.href = url.toString();
    a.click();
    a.remove();

    enqueueSnackbar(`Downloading report...`, { variant: "success" });
  };

  return (
    <Card
      sx={{
        maxWidth: 450,
      }}
    >
      <CardHeader
        avatar={<ShoppingCartOutlinedIcon />}
        sx={{
          borderBottomWidth: 1,
          borderBottomStyle: "solid",
          borderBottomColor: theme.palette.divider,
        }}
        title={
          <Typography variant="h6">
            <b>Export Purchases</b>
          </Typography>
        }
      />
      <CardContent>
        <LocalizationProvider adapterLocale="sv-SE" dateAdapter={AdapterLuxon}>
          <Stack gap={2}>
            <Typography>
              Generate and download a report of all confirmed purchases between the two selected
              dates.
            </Typography>
            <Stack alignItems="center" direction="row" gap={2}>
              <DatePicker label="Start" onChange={(date) => setStartDate(date as DateTime)} />
              -
              <DatePicker label="End" onChange={(date) => setEndDate(date as DateTime)} />
            </Stack>
            <Button color="success" variant="contained" onClick={generateReport}>
              Download
            </Button>
          </Stack>
        </LocalizationProvider>
      </CardContent>
    </Card>
  );
};

export default PurchaseCard;
