import { FC, useContext, useEffect, useState } from 'react';
import { getQuery } from 'mystique/hooks/getQuery';
import { Autocomplete } from '@material-ui/lab';
import { FormControlLabel, Switch, TextField } from '@material-ui/core';
import { Connection } from 'mystique/types/common';
import { useI18n } from 'mystique/hooks/useI18n';
import { useSettings } from 'mystique/hooks/useSettings';
import { useTemplateRender } from '../../../../../hooks/useTemplateRender';
import { orderTypesSettingName } from '../../../../../constants/SettingNames';
import { CreateOrderContext } from '../CreateOrderContext';

const customerQuery = `query {
  customers(first: 100){
    edges {
      node {
        ref
        id
        firstName
        lastName
      }
    }
  }
}
`;

interface CustomerQueryResult {
  customers: Connection<CustomerQueryNode>;
}

interface CustomerQueryNode {
  ref: string;
  id: number | string;
  firstName: string;
  lastName: string;
}

export interface CustomerInterface {
  name: string;
  ref: string;
  id: number | string;
}

export interface OrderType {
  label: string;
  value: string;
}

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

const CustomerAndOrderType: FC<CustomerAndOrderTypeProps> = ({
  defaultCustomer,
  onChange,
}) => {
  const [customers, setCustomers] = useState<CustomerInterface[]>([]);
  const [useDefaultAddress, setUseDefaultAddress] = useState<boolean>(false);
  const {
    createOrderInf,
    availableLocations: locations,
    customerAddresses,
  } = useContext(CreateOrderContext);
  const { defaultAddress } = customerAddresses || {};
  const { type, deliveryAddress, pickupLocationRef } = createOrderInf || {};

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

  const orderTypesSetting = useSettings({ query: orderTypesSettingName });
  const orderTypes: OrderType[] =
    (orderTypesSetting.query.status === 'ok' &&
      orderTypesSetting.query.result?.value.map((type: OrderType) => {
        return {
          ...type,
          label: templateRender(type.label),
        };
      })) ||
    [];

  useEffect(() => {
    getCustomers().then((resp) => {
      setCustomers(resp.customers);
      onChange(resp.customer, 'customer');
    });
  }, []);

  useEffect(() => {
    onChange(undefined, 'multiOrder');
  }, [useDefaultAddress, deliveryAddress]);

  useEffect(() => {
    if (useDefaultAddress) {
      onChange(null, 'deliveryAddress');
    }
  }, [useDefaultAddress]);

  useEffect(() => {
    if (!deliveryAddress && defaultAddress) {
      setUseDefaultAddress(true);
    }
  }, [defaultAddress]);

  const getCustomers = async () => {
    const customers: CustomerInterface[] = [];
    await getQuery<CustomerQueryResult>(customerQuery).then((resp) => {
      const customersList = resp.data?.customers.edges.map((customer) => {
        return {
          name: `${customer.node.firstName} ${
            customer.node.lastName ? customer.node.lastName : ''
          }`.trim(),
          ref: customer.node.ref,
          id: customer.node.id,
        };
      });
      if (customersList) {
        customers.push(...customersList);
      }
    });
    let initialCustomer;
    if (!createOrderInf?.customer) {
      initialCustomer = customers.find(
        (customer) => customer.ref === defaultCustomer,
      );
    }

    return {
      customers: customers,
      customer: initialCustomer || createOrderInf?.customer,
    };
  };

  const changeDeliveryAddress = (value: string | number, property: string) => {
    const copyDeliveryAddress: any =
      (deliveryAddress ? { ...deliveryAddress } : { ...defaultAddress }) || {};
    copyDeliveryAddress[property] = value;
    onChange(copyDeliveryAddress, 'deliveryAddress');
  };

  return (
    <>
      <Autocomplete
        fullWidth
        value={createOrderInf?.customer || null}
        options={customers}
        getOptionLabel={(option) => option.name}
        getOptionSelected={(option, value) => option.ref === value.ref}
        onChange={(_e, value) => {
          onChange(value, 'customer');
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="standard"
            label={`${translate(
              'fc.se.field.create.order.second.step.customer.label',
            )} *`}
          />
        )}
      />
      <Autocomplete
        fullWidth
        value={orderTypes.find((item) => item.value === type) || null}
        options={orderTypes}
        getOptionLabel={(option) => option.label}
        getOptionSelected={(option, value) => option.value === value.value}
        onChange={(_e, value) => {
          onChange(value?.value, 'type');
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="standard"
            label={`${translate(
              'fc.se.field.create.order.second.step.order.type.label',
            )} *`}
          />
        )}
      />
      {type == 'HD' ? (
        <>
          <FormControlLabel
            disabled={!defaultAddress}
            control={
              <Switch
                color="primary"
                checked={useDefaultAddress}
                onChange={(_event, checked) => {
                  setUseDefaultAddress(checked);
                  if (checked) {
                    onChange(null, 'deliveryAddress');
                  }
                }}
              />
            }
            label={`${translate(
              'fc.se.field.create.order.second.step.customer.address.label',
            )}`}
          />
          <TextField
            onChange={(event) => {
              changeDeliveryAddress(event.target.value, 'street');
            }}
            value={
              (deliveryAddress
                ? deliveryAddress?.street
                : defaultAddress?.street) || ''
            }
            fullWidth
            disabled={useDefaultAddress}
            label={`${translate(
              'fc.se.field.create.order.second.step.street.label',
            )} *`}
            variant="standard"
          />
          <TextField
            onChange={(event) => {
              changeDeliveryAddress(event.target.value, 'city');
            }}
            value={
              (deliveryAddress
                ? deliveryAddress?.city
                : defaultAddress?.city) || ''
            }
            fullWidth
            disabled={useDefaultAddress}
            label={translate('fc.se.field.create.order.second.step.city.label')}
            variant="standard"
          />
          <TextField
            onChange={(event) => {
              changeDeliveryAddress(event.target.value, 'postcode');
            }}
            value={
              (deliveryAddress
                ? deliveryAddress?.postcode
                : defaultAddress?.postcode) || ''
            }
            fullWidth
            disabled={useDefaultAddress}
            label={`${translate(
              'fc.se.field.create.order.second.step.postcode.label',
            )} *`}
            variant="standard"
          />
          <TextField
            onChange={(event) => {
              changeDeliveryAddress(event.target.value, 'state');
            }}
            value={
              (deliveryAddress
                ? deliveryAddress?.state
                : defaultAddress?.state) || ''
            }
            fullWidth
            disabled={useDefaultAddress}
            label={translate(
              'fc.se.field.create.order.second.step.state.label',
            )}
            variant="standard"
          />
          <TextField
            onChange={(event) => {
              changeDeliveryAddress(event.target.value, 'country');
            }}
            value={
              (deliveryAddress
                ? deliveryAddress?.country
                : defaultAddress?.country) || ''
            }
            fullWidth
            disabled={useDefaultAddress}
            label={`${translate(
              'fc.se.field.create.order.second.step.country.label',
            )} *`}
            variant="standard"
          />
        </>
      ) : null}
      {type == 'CC' && locations?.length ? (
        <Autocomplete
          fullWidth
          options={locations}
          getOptionLabel={(option) =>
            `${option.name}, ${option.postcode} (${option.ref})`
          }
          onChange={(_e, value) => {
            onChange(value?.ref, 'pickupLocationRef');
          }}
          value={
            locations.find((location) => location.ref === pickupLocationRef) ||
            null
          }
          getOptionSelected={(option, value) => option.ref === value.ref}
          renderInput={(params) => (
            <TextField
              {...params}
              label={`${translate(
                'fc.se.field.create.order.second.step.location',
              )} *`}
              variant="standard"
            />
          )}
        />
      ) : null}
    </>
  );
};

export default CustomerAndOrderType;