import { FC, useContext } from 'react';
import {
  Button,
  Card,
  CardContent,
  createStyles,
  FormControl,
  InputLabel,
  makeStyles,
  MenuItem,
  Select,
  TextField,
} from '@material-ui/core';
import { useI18n } from 'mystique/hooks/useI18n';
import { CreateOrderContext } from '../CreateOrderContext';
import { Add, Close } from '@material-ui/icons';
import { FinancialTransaction } from '../CreateOrder';
import { useSettings } from 'mystique/hooks/useSettings';
import {
  paymentCardTypeSettingName,
  paymentCurrencySettingName,
  paymentMethodSettingName,
  paymentProviderSettingName,
} from '../../../../../constants/SettingNames';
import { useTemplateRender } from '../../../../../hooks/useTemplateRender';
import { v4 as uuidv4 } from 'uuid';

const CREDIT_CARD_METHOD = 'CREDITCARD';
const FINANCIAL_TRANSACTION_TYPE = 'PAYMENT';

interface FinancialTransactionsProps {
  onChange: (value: unknown, property: string) => void;
}

function correctAmount(amount: string): number {
  const correctAmount = parseFloat(amount);
  if (correctAmount <= 0) {
    return 1;
  }
  return parseFloat(correctAmount.toFixed(2));
}

const FinancialTransactions: FC<FinancialTransactionsProps> = ({
  onChange,
}) => {
  const { createOrderInf } = useContext(CreateOrderContext);

  const { translate } = useI18n();
  const templateRender = useTemplateRender();
  const classes = useStyles();

  const paymentCardTypeSetting = useSettings({
    query: paymentCardTypeSettingName,
  });
  const paymentCardTypes: string[] =
    (paymentCardTypeSetting.query.status === 'ok' &&
      paymentCardTypeSetting.query.result?.value?.map((type: any) => {
        return type.name;
      })) ||
    [];

  const paymentMethodSetting = useSettings({ query: paymentMethodSettingName });
  const paymentMethods: string[] =
    (paymentMethodSetting.query.status === 'ok' &&
      paymentMethodSetting.query.result?.value?.map((type: any) => {
        return type.name;
      })) ||
    [];

  const paymentProviderSetting = useSettings({
    query: paymentProviderSettingName,
  });
  const paymentProviders: string[] =
    (paymentProviderSetting.query.status === 'ok' &&
      paymentProviderSetting.query.result?.value?.map((type: any) => {
        return type.name;
      })) ||
    [];

  const paymentCurrencySetting = useSettings({
    query: paymentCurrencySettingName,
  });
  const paymentCurrencies: string[] =
    (paymentCurrencySetting.query.status === 'ok' &&
      paymentCurrencySetting.query.result?.value?.map((type: any) => {
        return type.name;
      })) ||
    [];

  const changeFinancialTransaction = (
    index: number,
    name: string,
    value: any,
  ) => {
    const copyFinancialTransactions = createOrderInf?.financialTransactions && [
      ...createOrderInf?.financialTransactions,
    ];
    if (copyFinancialTransactions) {
      // @ts-ignore
      copyFinancialTransactions[index][name] = value;
    }
    onChange(copyFinancialTransactions, 'financialTransactions');
  };

  const removeFinancialTransaction = (index: number) => {
    const copyFinancialTransactions = createOrderInf?.financialTransactions && [
      ...createOrderInf?.financialTransactions,
    ];
    copyFinancialTransactions?.splice(index, 1);
    onChange(copyFinancialTransactions, 'financialTransactions');
  };

  const addNewFinancialTransaction = () => {
    const copyFinancialTransactions = createOrderInf?.financialTransactions && [
      ...createOrderInf?.financialTransactions,
    ];

    let amount: number =
      (createOrderInf?.totalPrice || 0) +
      (createOrderInf?.totalTaxPrice || 0);
    copyFinancialTransactions?.forEach((value) => {
      amount -= value?.amount || 0;
    });

    const emptyFinancialTransaction: FinancialTransaction = {
      amount: correctAmount(amount.toString()),
      paymentMethod: paymentMethods[0],
      ref: uuidv4(),
      type: FINANCIAL_TRANSACTION_TYPE,
      currency:
        createOrderInf?.products[0]?.prices[0]?.currency ||
        paymentCurrencies[0],
      cardType:
        paymentMethods[0] == CREDIT_CARD_METHOD ? paymentCardTypes[0] : null,
      externalTransactionId: '',
      externalTransactionCode: '',
      paymentProvider: '',
    };
    onChange(
      copyFinancialTransactions
        ? [...copyFinancialTransactions, { ...emptyFinancialTransaction }]
        : [{ ...emptyFinancialTransaction }],
      'financialTransactions',
    );
  };

  return (
    <>
      <Button
        variant="text"
        size="small"
        color="primary"
        endIcon={<Add />}
        onClick={addNewFinancialTransaction}
      >
        {translate(
          'fc.se.field.create.order.fifth.step.financial.transaction.add.button',
        )}
      </Button>
      {createOrderInf?.financialTransactions &&
        createOrderInf?.financialTransactions.map(
          (financialTransaction: FinancialTransaction, idx: number) => {
            return (
              <Card key={idx} className={classes.target}>
                <CardContent className={classes.targetContent}>
                  <div className={classes.contentTitle}>
                    <Button
                      className={classes.targetBtn}
                      onClick={() => removeFinancialTransaction(idx)}
                    >
                      <Close fontSize="small" />{' '}
                      {translate(
                        'fc.se.field.create.order.fifth.step.financial.transaction.remove.button',
                      )}
                    </Button>
                  </div>
                  <FormControl fullWidth>
                    <TextField
                      fullWidth
                      label={`${translate(
                        'fc.se.field.create.order.fifth.step.financial.transaction.amount',
                      )} *`}
                      type="number"
                      InputProps={{ inputProps: { min: 1, step: '.01' } }}
                      value={financialTransaction.amount}
                      onChange={(event) => {
                        changeFinancialTransaction(
                          idx,
                          'amount',
                          correctAmount(event.target.value),
                        );
                      }}
                    />
                  </FormControl>
                  <FormControl fullWidth>
                    <InputLabel id="select-currency">
                      {`${translate(
                        'fc.se.field.create.order.fifth.step.financial.transaction.currency',
                      )} *`}{' '}
                    </InputLabel>
                    <Select
                      value={financialTransaction.currency}
                      onChange={(_e, opt: any) => {
                        changeFinancialTransaction(
                          idx,
                          'currency',
                          opt?.props.value,
                        );
                      }}
                      labelId="select-currency"
                    >
                      {paymentCurrencies.map((option) => {
                        return (
                          <MenuItem key={option} value={option}>
                            {templateRender(`{{currencySymbol '${option}'}}`)
                              .replace(/\d/g, '')
                              .trim()}{' '}
                            ({option})
                          </MenuItem>
                        );
                      })}
                    </Select>
                  </FormControl>
                  <FormControl fullWidth>
                    <InputLabel id="select-payment-method">
                      {`${translate(
                        'fc.se.field.create.order.fifth.step.financial.transaction.payment.method',
                      )} *`}{' '}
                    </InputLabel>
                    <Select
                      value={financialTransaction.paymentMethod}
                      onChange={(_e, opt: any) => {
                        changeFinancialTransaction(
                          idx,
                          'paymentMethod',
                          opt?.props.value,
                        );
                      }}
                      labelId="select-payment-method"
                    >
                      {paymentMethods &&
                        paymentMethods.map((option) => (
                          <MenuItem value={option} key={option}>
                            {option}
                          </MenuItem>
                        ))}
                    </Select>
                  </FormControl>
                  <FormControl
                    fullWidth
                    disabled={
                      financialTransaction.paymentMethod != CREDIT_CARD_METHOD
                    }
                  >
                    <InputLabel id="select-card-type">
                      {translate(
                        'fc.se.field.create.order.fifth.step.financial.transaction.card.type',
                      )}
                    </InputLabel>
                    <Select
                      value={financialTransaction.cardType}
                      onChange={(_e, opt: any) => {
                        changeFinancialTransaction(
                          idx,
                          'cardType',
                          opt?.props.value,
                        );
                      }}
                      labelId="select-card-type"
                    >
                      {paymentCardTypes &&
                        paymentCardTypes.map((option) => (
                          <MenuItem value={option} key={option}>
                            {option}
                          </MenuItem>
                        ))}
                    </Select>
                  </FormControl>
                  <FormControl fullWidth>
                    <InputLabel id="select-payment-provider">
                      {translate(
                        'fc.se.field.create.order.fifth.step.financial.transaction.payment.provider',
                      )}
                    </InputLabel>
                    <Select
                      value={financialTransaction.paymentProvider}
                      onChange={(_e, opt: any) => {
                        changeFinancialTransaction(
                          idx,
                          'paymentProvider',
                          opt?.props.value,
                        );
                      }}
                      labelId="select-payment-provider"
                    >
                      <MenuItem
                        className={classes.emptyMenuItem}
                        value={''}
                        key="empty"
                      >
                        {' '}
                      </MenuItem>
                      {paymentProviders &&
                        paymentProviders.map((option) => (
                          <MenuItem value={option} key={option}>
                            {option}
                          </MenuItem>
                        ))}
                    </Select>
                  </FormControl>
                  <FormControl fullWidth>
                    <TextField
                      fullWidth
                      label={`${translate(
                        'fc.se.field.create.order.fifth.step.financial.transaction.ref',
                      )} *`}
                      value={financialTransaction.ref}
                      onChange={(event) => {
                        changeFinancialTransaction(
                          idx,
                          'ref',
                          event.target.value,
                        );
                      }}
                    />
                  </FormControl>
                </CardContent>
              </Card>
            );
          },
        )}
    </>
  );
};

const useStyles = makeStyles(() =>
  createStyles({
    target: {
      width: '100%',
      marginTop: '5px',
    },
    targetContent: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'flex-start',
      gap: '15px',
      width: '100%',
      boxSizing: 'border-box',
      '&:not(:first-child)': {
        marginTop: '15px',
      },
    },
    contentTitle: {
      width: '100%',
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
    },
    targetBtn: {
      marginRight: '-8px',
      marginLeft: 'auto',
      textTransform: 'capitalize',
    },
    emptyMenuItem: {
      minHeight: '34px',
    },
  }),
);

export default FinancialTransactions;
