import React, { useState } from "react";

import { Button, Stack, TableBody, TableRow, Typography } from "@mui/material";
import { tableCellClasses } from "@mui/material/TableCell";

import Card from "../../../components/Card";
import Table from "../../../components/Table";
import { TableCell } from "../../../components/Table/TableCell";
import TableCardHeader from "../../../components/TableCardHeader";
import { useDialog } from "../../../contexts/DialogContext";
import { useI18n } from "../../../contexts/I18nContext";
import { useUser } from "../../../contexts/UserContext";
import { hasPermission } from "../../../util/has_permission";
import { Line, PurchaseDetail } from "../types/purchase";

import { ReceiptTable } from "./ReceiptTable";

export interface ReceiptCardProps {
  purchase: PurchaseDetail;
  refund?: (lines: Line[]) => void;
}

export interface ReceiptPriceRowProps {
  title: string;
  price: string;
  currency: string;
}

export const ReceiptPriceRow: React.FC<ReceiptPriceRowProps> = ({ title, price, currency }) => (
  <Stack direction="row" gap={1} justifyContent="flex-end" sx={{ minWidth: "max-content" }}>
    <Typography fontWeight={600} sx={{ minWidth: 42 }} variant="body2">
      {title}
    </Typography>
    <Typography sx={{ minWidth: 80 }} variant="body2">
      {price} {currency}
    </Typography>
  </Stack>
);

export const ReceiptCard: React.FC<ReceiptCardProps> = ({ purchase, refund }) => {
  const { t } = useI18n();
  const { user } = useUser();

  const [editing, setEditing] = useState(false);
  const [selected, setSelected] = useState<Line[]>([]);
  const openDialog = useDialog();

  return (
    <Card size={12}>
      <TableCardHeader
        isDisabled={(!purchase.accounts || purchase.accounts.captured === "0.00") && !editing}
        isEditable={hasPermission(user, "pos.change_receipt")}
        title={t("Receipt")}
        toggled={editing}
        onChange={setEditing}
      />

      <ReceiptTable
        currency={purchase.currency}
        editable={editing}
        lines={purchase.lines}
        onSelect={setSelected}
      />

      <Table
        count={0}
        tableProps={{ sx: { p: 0, [`& .${tableCellClasses.root}`]: { borderBottom: "none" } } }}
      >
        <TableBody sx={{ border: "none" }}>
          <TableRow>
            <TableCell align="left" sx={{ width: "100%" }}>
              {editing && (
                <Button
                  color="error"
                  disabled={selected.length === 0}
                  variant="contained"
                  onClick={async () => {
                    if (
                      await openDialog(
                        t("Are you sure?"),
                        t(
                          "This will refund the selected quantity / amount to the customer and cannot be reversed",
                        ),
                      )
                    ) {
                      refund?.(selected);
                      setEditing(false);
                    }
                  }}
                >
                  {t("Refund")}
                </Button>
              )}
            </TableCell>

            <TableCell align="right">
              {purchase.total_debit_amount != null && (
                <ReceiptPriceRow
                  currency={purchase.currency}
                  price={purchase.total_debit_amount}
                  title={t("Total")}
                />
              )}

              {Boolean(
                purchase.total_discount_amount != null && purchase.total_discount_amount !== "0.00",
              ) && (
                <ReceiptPriceRow
                  currency={purchase.currency}
                  price={purchase.total_discount_amount!}
                  title={t("Discount")}
                />
              )}

              {purchase.total_tax_amount && (
                <ReceiptPriceRow
                  currency={purchase.currency}
                  price={purchase.total_tax_amount}
                  title={t("Tax")}
                />
              )}

              {purchase.accounts != null && (
                <>
                  {purchase.accounts.reserved !== "0.00" && (
                    <ReceiptPriceRow
                      currency={purchase.currency}
                      price={purchase.accounts.reserved}
                      title={t("Reserved")}
                    />
                  )}

                  {purchase.accounts.captured !== "0.00" && (
                    <ReceiptPriceRow
                      currency={purchase.currency}
                      price={purchase.accounts.captured}
                      title={t("Captured")}
                    />
                  )}

                  {purchase.accounts.reverted !== "0.00" && (
                    <ReceiptPriceRow
                      currency={purchase.currency}
                      price={purchase.accounts.reverted}
                      title={t("Refunded/Cancelled")}
                    />
                  )}
                </>
              )}
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
    </Card>
  );
};
