import { FC, useEffect, useState } from 'react';
import { FormFieldProps } from 'mystique/registry/FieldRegistry';
import {
  FormControlLabel,
  Grid,
  makeStyles,
  Paper,
  Switch,
  Typography,
} from '@material-ui/core';
import AddProductItems from '../../../components/AddProductItems/AddProductItems';
import { useSettings } from 'mystique/hooks/useSettings';
import { useActiveRetailer } from '../../../hooks/useActiveRetailer';
import { defaultTaxTypeSettingName } from '../../../constants/SettingNames';
import { useI18n } from 'mystique/hooks/useI18n';
import PriceDifference from '../../../components/price/PriceDifference';
import { OrderItem } from '../../../constants/Interfaces';

export const ExchangeItems: FC<FormFieldProps<any>> = ({ label, onChange }) => {
  const [useProductItems, setUseProductItems] = useState(false);
  const [evenExchange, setEvenExchange] = useState(true);
  const [products, setProducts] = useState<OrderItem[]>([]);
  const [difference, setDifference] = useState<number>(0);
  const [currency, setCurrency] = useState<string>('USD');

  const classes = useStyles();
  const activeRetailer = useActiveRetailer();

  const { translate } = useI18n();

  const defaultTaxTypeSetting = useSettings({
    query: defaultTaxTypeSettingName,
  });

  const defaultTaxType =
    defaultTaxTypeSetting.query.status === 'ok' &&
    defaultTaxTypeSetting.query.result?.value;

  useEffect(() => {
    fixDifference();
    setCurrency(window.sessionStorage.getItem('RETURNS_CURRENCY') ?? 'USD');
  }, [window.sessionStorage.getItem('RETURNS_AMOUNT')]);

  const fixDifference = () => {
    const returnsAmount = parseFloat(
      window.sessionStorage.getItem('RETURNS_AMOUNT') ?? '0',
    );
    let exchangesAmount = 0;
    products?.forEach((product: any) => {
      exchangesAmount += product.price.toFixed(2) * product.quantity;
    });
    const diff = exchangesAmount - returnsAmount;
    setDifference(diff);
  };

  useEffect(() => {
    fixDifference();
    setCurrency(products[0]?.prices[0]?.currency || 'USD');
    onChange({
      items: products.map((product) => {
        return {
          ref: product.ref,
          quantity: product.quantity,
          price: product.price.toFixed(2),
          currency: product.prices[0].currency,
          taxType: product.prices[0]?.taxType || defaultTaxType.tariff,
          productCatalogueRef: `DEFAULT:${activeRetailer}`,
        };
      }),
      even: evenExchange,
    });
  }, [products, evenExchange]);

  return (
    <Paper className={classes.container}>
      <FormControlLabel
        checked={useProductItems}
        onChange={(_e, value) => {
          setUseProductItems(value);
          setProducts([]);
        }}
        control={<Switch color="primary" />}
        label={label}
        labelPlacement="end"
      />
      {useProductItems && (
        <Grid container direction="row">
          <Grid item className={classes.evenExchange}>
            <Typography>
              {translate(
                'fc.sf.ui.returns.orders.createReturnOrder.exchangeItems.even',
              )}
            </Typography>
          </Grid>
          <Grid item>
            <FormControlLabel
              checked={!evenExchange}
              onChange={(_e, value) => {
                setEvenExchange(!value);
              }}
              control={<Switch color="primary" />}
              label={translate(
                'fc.sf.ui.returns.orders.createReturnOrder.exchangeItems.uneven',
              )}
              labelPlacement="end"
            />
          </Grid>
        </Grid>
      )}
      <PriceDifference
        difference={difference}
        currency={currency}
        zeroPayment={useProductItems && products.length > 0 && evenExchange}
      />
      {useProductItems && (
        <AddProductItems
          products={products}
          onChange={(value, property) => {
            if (property === 'products') {
              setProducts(value as OrderItem[]);
            }
          }}
          tableView={true}
        />
      )}
    </Paper>
  );
};

const useStyles = makeStyles(() => ({
  container: {
    width: '100%',
    padding: '20px',
    boxSizing: 'border-box',
    display: 'flex',
    flexWrap: 'wrap',
    flexDirection: 'column',
    gap: '5px',
    alignItems: 'flex-start',
  },
  evenExchange: {
    alignContent: 'center',
    marginRight: '10px',
  },
  diffTax: {
    marginLeft: '10px',
    alignContent: 'center',
  },
  payment: {
    display: 'flow',
    marginLeft: '5px',
    marginRight: '5px',
    marginBottom: '5px',
  },
}));