/** @jsxRuntime classic */
/** @jsx jsx */
import React, { Fragment, useEffect, useRef, useState } from 'react';
import { css, jsx } from '@emotion/react';
import { oldThemeColors as colors } from '../../../../styles/theme';

import { Button, getIcon, ModalWindow, useModal } from '../../../index';
// import { Pricify } from 'app/react/lib/form';
// import { TranslationEn } from 'assets/i18n/en';
// import { usePayments } from '../../payments';
// import { paymentApi } from '../../../lib/api/paymentApi';
// import { useErrorModal } from '../Error';
import { BnForward } from '../../../../icons';

export const Pricify = (price?: number) => {
  if (price || price === 0) {
    if (price >= 0) {
      return `$${price.toFixed(2)}`;
    } else {
      return `-$${(price * -1).toFixed(2)}`;
    }
  } else {
    return '-';
  }
};

const Item = () => {
  return <div></div>;
};

const flex = css`
  display: flex;
`;

const containerCss = (isExpand: boolean) => css`
  position: relative;
  z-index: 100;
  top: 0;
  bottom: 0;
  margin-right: ${isExpand ? '0' : '-300px'};

  min-width: 100px;
  background: ${colors.white};
  box-shadow: 0px 2px 22px rgba(21, 93, 148, 0.0749563);
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 600ms;
`;

const collapseExpandCss = css`
  background: linear-gradient(
    270deg,
    ${colors.brandSecondaryLight} 0%,
    ${colors.brandSecondaryLight} 100%
  );
  height: 28px;
  width: 28px;
  box-shadow: 0px 2px 22px 8px rgba(21, 93, 148, 0.0749563);
  border-radius: 100px;
  top: 50%;
  left: 0;
  transform: translate(-50%, -50%);
  border: none;
  cursor: pointer;
  color: ${colors.white};
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
`;

const cartHeaderTitle = css`
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-bottom: 20px;
  h1 {
    font-family: Montserrat;
    font-style: normal;
    font-weight: bold;
    font-size: 20px;
    line-height: 24px;
    text-align: center;
    color: ${colors.brandPrimary};
    margin: 0;
  }
`;

const headerCss = css`
  box-shadow: 0px 2px 22px 8px rgba(21, 93, 148, 0.0749563);
  border-radius: 0px 0px 5px 5px;
  padding: 16px;
`;

const iconCss = css`
  display: flex;
  align-items: center;
  justify-content: center;
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 600ms;
  div {
    display: flex;
    align-items: center;
    justify-content: center;
  }
`;

const iconRotatedCss = css`
  ${iconCss};
  transform: rotate(180deg);
`;

const checkoutCss = css`
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
`;

const chargeButton = css`
  width: 100%;
  text-align: center;
  justify-content: center;
  margin-left: 10px !important;
`;

const buttonContainer = css`
  ${flex};
  justify-content: space-between;
  button {
    margin-left: 0px;
    padding: 14px;
  }
`;

const totalContainer = css`
  label {
    font-family: Montserrat;
    font-style: normal;
    font-weight: 600;
    font-size: 16px;
    line-height: 20px;
    color: ${colors.brandPrimary};
  }
  padding: 8px 0;
  justify-content: space-between;
  ${flex};
`;

const subTotalContainer = css`
  label {
    font-family: Montserrat;
    font-style: normal;
    font-weight: 500;
    font-size: 12px;
    line-height: 15px;
    color: ${colors.formInputBg};
  }
  padding-bottom: 8px;
  justify-content: space-between;
  ${flex};
`;

const borderBottomCss = css`
  border-bottom: 1px solid ${colors.borderSeperator};
`;

const userButton = css`
  background: ${colors.lightGray};
  border: 1px solid ${colors.borderPrimary};
  box-sizing: border-box;
  border-radius: 3px;
  padding: 6px 12px;
  min-width: 300px;
  ${flex};
  align-items: center;
  justify-content: space-between;
  img {
    width: 36px;
    height: 36px;
    border-radius: 100px;
  }
  label {
    margin-left: 12px;
    font-family: Montserrat;
    font-style: normal;
    font-weight: 500;
    font-size: 14px;
    line-height: 17px;
    margin-bottom: 0;
    margin-right: 5px;
    color: ${colors.brandPrimary};
  }
  span {
    font-family: Montserrat;
    font-style: normal;
    font-weight: 400;
    font-size: 12px;
    line-height: 14px;
    color: ${colors.brandPrimary};
  }
  button {
    border: none;
    background: none;
    ${flex};
    align-items: center;
    justify-content: center;
    &:hover {
      svg {
        path {
          fill: ${colors.brandPrimary};
        }
      }
    }
  }
`;

const trashButton = css`
  ${flex};
  align-items: center;
  border: none;
  background: none;
  font-family: Montserrat;
  font-style: normal;
  font-weight: 500;
  font-size: 12px;
  line-height: 15px;
  color: ${colors.formInputBg};
  position: absolute;
  left: 0;
  cursor: pointer;
  top: 50%;
  transform: translateY(-50%);
  &:hover {
    color: ${colors.brandPrimary};
    svg {
      path {
        fill: ${colors.brandPrimary};
      }
    }
  }
`;

const addCustomerButtonCss = (width: number) => css`
  min-width: ${width}px;
  padding: 14px;
  margin-left: 0;
  justify-content: center;
  svg {
    margin-right: 8px;
  }
`;

export const Cart = ({
  isCart: isExpand,
  setCart: setExpand,

  cartObj,
  items = [],
  purchaseUser = { name: '' },
  organizationId,
}: {
  isCart: boolean;
  setCart: (val: boolean) => void;

  cartObj?: any;
  items?: any;
  purchaseUser?: {
    name: string;
  };
  organizationId?: any;
}) => {
  const [billedToUser, setBilledUser] = useState(purchaseUser);
  // const [isExpand, setExpand] = useState<boolean>(true);
  const [customer, setCustomer] = useState<boolean>(true);
  const [buttonWidth, setButtonWidth] = useState<number>(315);
  const [price, setPrice] = useState<number>(0);
  const [cartItems, setCartItems] = useState(items);

  //   const { ComingSoonModal, ComingSoonToggle } = useComingSoonPopUp();

  const { isShowing, toggle } = useModal();

  const [error, setError] = useState('');
  const ref = useRef(null);

  useEffect(() => {
    // setBilledUser(purchaseUser);
  }, [purchaseUser]);

  useEffect(() => {
    //   @ts-ignore
    document.getElementsByTagName('BODY')[0].style.overflowX = 'hidden';
  }, []);

  const removeCustomer = () => {
    // if (ref.current) {
    //   setButtonWidth(ref.current.offsetWidth);
    // }
    // setCustomer(false);
  };

  const clearCart = () => {
    setCartItems([]);
    removeCustomer();
  };

  const handlePay = ({ token, type, isNewCard, amount, handleCompleted }) => {};
  useEffect(() => {
    // let calculatedPrice = 0;
    // cartItems.forEach((item) => {
    //   calculatedPrice += Number(item.paidAmount);
    // });
    // setPrice(calculatedPrice);
  }, [cartItems]);

  useEffect(() => {
    // setCartItems(items);
  }, [items]);

  const handleRemoveItem = (id: number) => {
    setCartItems(items.filter((item) => item.id !== id));
  };

  return (
    <Fragment>
      <div css={containerCss(isExpand)}>
        <div css={headerCss}>
          <div css={cartHeaderTitle}>
            <button css={trashButton} onClick={() => setCartItems([])}>
              {getIcon('remove')}
              clear cart
            </button>
            <h1>
              Cart
              {cartItems.length !== 0 && `(${cartItems.length})`}
            </h1>
          </div>
          {customer ? (
            <div css={userButton} ref={ref}>
              <div css={flex}>
                {/* <img src="https://thispersondoesnotexist.com/image" /> */}
                {getIcon('profile_filled')}
                <label>{billedToUser.name}</label>
                <span> (billed to)</span>
              </div>
              <button onClick={() => removeCustomer()}>
                {getIcon('remove')}
              </button>
            </div>
          ) : (
            <Button
              css={addCustomerButtonCss(buttonWidth)}
              sizer="L"
              theme="secondary"
              onClick={
                () => {}
                // setCustomer(true)
              }
            >
              {getIcon('profile-filled')}
              Add Customer
            </Button>
          )}
        </div>
        <div>
          {cartItems.map((item, index) => {
            return (
              <Item
              // type={item.type}
              // handleRemoveItem={handleRemoveItem}
              // customer={cartObj.customer}
              // state={item}
              // key={index}
              />
            );
          })}
        </div>
        <div css={checkoutCss}>
          <div css={borderBottomCss}>
            <div css={subTotalContainer}>
              <label>Sub Total</label>
              <label>{Pricify(price)}</label>
            </div>
            {/* <div css={subTotalContainer}>
            <label>{TranslationEn.customers.paymentsInvoices.tax} (0)</label>
            <label>{Pricify(10.9)}</label>
          </div> */}
          </div>
          <div css={totalContainer}>
            <label>Total</label>
            <label>{Pricify(price)}</label>
          </div>
          <div css={buttonContainer}>
            <Button sizer="L" theme="secondary">
              Discount
            </Button>

            <Button
              sizer="L"
              theme="primary"
              css={chargeButton}
              onClick={toggle}
            >
              Charge
            </Button>
          </div>
        </div>

        <button css={collapseExpandCss} onClick={() => setExpand(!isExpand)}>
          <div css={isExpand ? iconCss : iconRotatedCss}>
            <BnForward />
          </div>
        </button>
      </div>
      <ModalWindow isShowing={isShowing} toggle={toggle}>
        {/* <Charge
          alternativeHandleCharge={handlePay}
          isAmountEditable={false}
          toggle={toggle}
          totalAmount={price}
          userId={
            billedToUser.userInFamilyAccounts
              ? billedToUser.id
              : billedToUser.entityId
          }
          organizationId={organizationId}
        /> */}
        charge
      </ModalWindow>
    </Fragment>
  );
};
