import { FC, useEffect } from 'react';
import { Loading } from 'mystique/components/Loading';
import { Autocomplete } from '@material-ui/lab';
import { humanifyV2 } from '../../../../../utils/StringUtils';
import {
  Card,
  CardContent,
  FormControl,
  FormControlLabel,
  Grid,
  makeStyles,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from '@material-ui/core';
import { MdLocalShipping } from 'react-icons/md';
import { FaShippingFast } from 'react-icons/fa';
import { useI18n } from 'mystique/hooks/useI18n';
import Moment from 'moment';
import { getLocaleDateString } from '../../../../../utils/DateUtils';
import {
  FulfilmentCCPlanInterface,
  FulfilmentHDPlanInterface,
} from 'interfaces/fulfilmentPlans';
import { Location } from 'interfaces/locations';

interface FulfilmentPlansProps {
  onChange: (value: unknown, property: string) => void;
  fulfilmentPlans: FulfilmentHDPlanInterface[] | FulfilmentCCPlanInterface[];
  orderType: 'HD' | 'CC';
  locations?: Location[];
  deliveryType?: string;
  fulfilmentPlanRef?: string;
  locationRef?: string;
}

const FulfilmentPlans: FC<FulfilmentPlansProps> = ({
  fulfilmentPlans,
  orderType,
  locations,
  deliveryType,
  onChange,
  fulfilmentPlanRef,
  locationRef,
}) => {
  const { translate } = useI18n();
  const currentLanguage = useI18n().language?.current;
  const classes = useStyles();

  useEffect(() => {
    if (orderType === 'HD') {
      const plan = (fulfilmentPlans as FulfilmentHDPlanInterface[]).find(
        (plan: FulfilmentHDPlanInterface) => plan.deliveryType === deliveryType,
      );
      if (plan && plan?.ref !== fulfilmentPlanRef) {
        onChange(plan.ref, 'fulfilmentPlanRef');
        const carrierName = (fulfilmentPlans as any[])?.find(
          (fp) => fp.ref == plan.ref,
        )?.carrier;
        onChange(carrierName, 'carrier');
      }
    }
  }, [deliveryType, fulfilmentPlans, orderType]);

  const availableLocations =
    orderType === 'CC' && !!fulfilmentPlans.length
      ? locations?.filter((location) =>
        (fulfilmentPlans as FulfilmentCCPlanInterface[])
          .find((plan) => plan.deliveryType === 'EXPRESS')
          ?.locations?.some((typeLocation) => typeLocation === location.ref),
      )
      : [];

  const handleChangeDelivery = (event: any) => {
    onChange(event.target.value, 'fulfilmentPlanRef');

    const carrierName = (fulfilmentPlans as any[])?.find(
      (fp) => fp.ref == event.target.value,
    )?.carrier;
    onChange(carrierName, 'carrier');
  };

  const showEta = (eta: string) => {
    const etaDate = new Date(eta);
    const currentDate = new Date();

    if (etaDate.toDateString() === currentDate.toDateString()) {
      const hours = Math.floor(
        Math.abs(etaDate.valueOf() - currentDate.valueOf()) / 36e5,
      );
      return `${hours} ${
        hours === 1
          ? translate('fc.se.field.create.order.fulfilment.plans.hour')
          : translate('fc.se.field.create.order.fulfilment.plans.hours')
      }`;
    }
    return Moment(etaDate).format(
      getLocaleDateString(currentLanguage).toUpperCase(),
    );
  };

  return (
    <>
      {!fulfilmentPlans.length && <Loading />}
      {!!fulfilmentPlans.length && (
        <Autocomplete
          fullWidth
          options={[
            ...new Set(
              fulfilmentPlans.map((plan) => humanifyV2(plan.deliveryType)),
            ).values(),
          ]}
          value={deliveryType ? humanifyV2(deliveryType) : null}
          onChange={(_e, value) => {
            onChange(value ? value.toUpperCase() : undefined, 'deliveryType');
          }}
          renderInput={(params) => (
            <TextField
              {...params}
              variant="standard"
              label={`${translate(
                'fc.se.field.create.order.fulfilment.plans.delivery.type',
              )} *`}
            />
          )}
        />
      )}
      {deliveryType && orderType == 'HD' && (
        <FormControl fullWidth>
          <RadioGroup
            aria-label="Delivery Options"
            name="deliveryOptions"
            value={`${fulfilmentPlanRef}`}
            onChange={handleChangeDelivery}
          >
            {(fulfilmentPlans as FulfilmentHDPlanInterface[])
              .filter((plan) => plan.deliveryType === deliveryType)
              .map((option) => {
                return (
                  <Card square={true} variant="outlined" key={option.ref}>
                    <CardContent
                      classes={{
                        root: classes.cardContent,
                      }}
                    >
                      <FormControlLabel
                        classes={{
                          root: `${classes.root} ${classes.fullWidth}`,
                          label: classes.fullWidth,
                        }}
                        value={`${option.ref}`}
                        control={
                          <Radio
                            classes={{
                              root: classes.radio,
                            }}
                          ></Radio>
                        }
                        label={
                          <Grid container alignItems="center">
                            <Grid item xs={2}>
                              <Typography align="left" className={classes.icon}>
                                {option.deliveryType === 'STANDARD' ? (
                                  <MdLocalShipping size="30"></MdLocalShipping>
                                ) : (
                                  <FaShippingFast size="30"></FaShippingFast>
                                )}
                              </Typography>
                            </Grid>
                            <Grid item xs={10}>
                              <span className={classes.optionTitle}>
                                {option.deliveryType.toLowerCase()}
                                {option.eta && ` - ${showEta(option.eta)}`}
                              </span>
                              <Typography>{option.carrier}</Typography>
                            </Grid>
                          </Grid>
                        }
                      />
                    </CardContent>
                  </Card>
                );
              })}
          </RadioGroup>
        </FormControl>
      )}
      {deliveryType === 'EXPRESS' && orderType == 'CC' && (
        <Autocomplete
          fullWidth
          options={availableLocations || []}
          getOptionLabel={(option) =>
            `${option.name}, ${option.postcode} (${option.ref})`
          }
          value={
            availableLocations?.find(
              (location) => location.ref === locationRef,
            ) || null
          }
          onChange={(_e, value) => {
            onChange(value?.ref || undefined, 'pickupLocationRef');
          }}
          renderInput={(params) => (
            <TextField
              {...params}
              variant="standard"
              label={`${translate(
                'fc.se.field.create.order.fulfilment.plans.location',
              )} *`}
            />
          )}
        />
      )}
    </>
  );
};

const useStyles = makeStyles(() => ({
  optionTitle: {
    textTransform: 'capitalize',
    fontWeight: 500,
    fontSize: '1em',
  },
  icon: {
    marginTop: '3px',
  },
  fullWidth: {
    width: '100%',
  },
  root: {
    marginLeft: 0,
  },
  cardContent: {
    paddingBottom: '16px !important',
  },
  radio: {
    paddingLeft: 0,
  },
}));

export default FulfilmentPlans;
