import React from 'react';
import styled from 'styled-components';
import ServiceSlider from '../../../../../common/services-slider/ServiceSlider';
import {
  useOrderDetails,
  useOrderStaticData,
  usePrevOrderDetails,
} from '../../../store';
import { OrderServiceType } from '../../../types';

function OrderServices() {
  const [orderStaticData] = useOrderStaticData();
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const [prevOrderDetails] = usePrevOrderDetails();
  const orderServices = orderDetails?.order_services;
  const prevOrderServices = prevOrderDetails?.order_services;

  const orderServicesOptions = orderStaticData?.order_service_list;

  const desiredOrder = [
    'unpack_items',
    'take_packaging_away',
    'assemble',
    'disassemble',
    'collect_disposal',
  ];

  const sortedServices = orderServicesOptions?.sort((a: any, b: any) => {
    return desiredOrder.indexOf(a.type) - desiredOrder.indexOf(b.type);
  });

  const toggleServices = (id: number) => {
    const clone = [...orderServices];
    const selectedService = clone?.find(
      (s: OrderServiceType) => s?.order_service_list_id === id
    );
    const assembleOrderService = orderStaticData?.order_service_list?.find(
      (x: any) => x?.type?.toLowerCase() === 'assemble'
    );
    const disassembleOrderService = orderStaticData?.order_service_list?.find(
      (x: any) => x?.type?.toLowerCase() === 'disassemble'
    );

    const assemblyTypeService = clone?.find(
      (x: any) => x?.order_service_list_id === assembleOrderService?.id
    );

    const disassemblyTypeService = clone?.find(
      (x: any) => x?.order_service_list_id === disassembleOrderService?.id
    );

    if (selectedService !== undefined) {
      const isAssembleService =
        assembleOrderService?.id === selectedService?.order_service_list_id;

      const isDisassembleService =
        disassembleOrderService?.id === selectedService?.order_service_list_id;

      if (selectedService.new_id) {
        const updatedOrderServices = clone.filter(
          (service: OrderServiceType) => service.id !== selectedService.id
        );
        const newData = {
          ...orderDetails,
          order_services: updatedOrderServices,
        };
        setOrderDetails(newData);
      } else {
        let updatedSelectedService = {
          ...selectedService,
          is_deleted: !selectedService.is_deleted,
        };

        let updatedOrderServices = [];
        let newUpdatedOrderServices: any = [];

        updatedOrderServices = clone.filter(
          (service: OrderServiceType) => service.id !== selectedService.id
        );

        updatedOrderServices.push(updatedSelectedService);
        if (
          (isAssembleService &&
            updatedSelectedService?.is_deleted === true &&
            (disassemblyTypeService?.is_deleted === true ||
              disassemblyTypeService === undefined ||
              disassemblyTypeService === null)) ||
          (isDisassembleService &&
            updatedSelectedService?.is_deleted === true &&
            (assemblyTypeService?.is_deleted === true ||
              assemblyTypeService === undefined ||
              assemblyTypeService === null))
        ) {
          const prevSelectedService = prevOrderServices?.find(
            (s: OrderServiceType) => s?.order_service_list_id === id
          );
          updatedSelectedService = {
            ...selectedService,
            is_deleted: true,
            service_category_id: prevSelectedService?.service_category_id,
          };
          updatedOrderServices = clone.filter(
            (service: OrderServiceType) => service.id !== selectedService.id
          );

          updatedOrderServices.push(updatedSelectedService);
          // new cases
          if (
            isAssembleService &&
            disassemblyTypeService?.is_deleted === true &&
            disassemblyTypeService !== undefined &&
            disassemblyTypeService !== null
          ) {
            const newUpdatedSelectedService = {
              ...disassemblyTypeService,
              is_deleted: true,
              service_category_id: prevSelectedService?.service_category_id,
            };
            newUpdatedOrderServices = updatedOrderServices?.filter(
              (service: OrderServiceType) =>
                service.id !== disassemblyTypeService.id
            );
            newUpdatedOrderServices?.push(newUpdatedSelectedService);
          }
          // new cases
          if (
            isDisassembleService &&
            assemblyTypeService?.is_deleted === true &&
            assemblyTypeService !== undefined &&
            assemblyTypeService !== null
          ) {
            const newUpdatedSelectedService = {
              ...assemblyTypeService,
              is_deleted: true,
              service_category_id: prevSelectedService?.service_category_id,
            };
            newUpdatedOrderServices = updatedOrderServices?.filter(
              (service: OrderServiceType) =>
                service.id !== assemblyTypeService.id
            );
            newUpdatedOrderServices?.push(newUpdatedSelectedService);
          }
        }

        const newData = {
          ...orderDetails,
          order_services:
            newUpdatedOrderServices.length > 0
              ? newUpdatedOrderServices
              : updatedOrderServices,
        };
        setOrderDetails(newData);
      }
    } else {
      // service not exist case
      // if not matched then treat it as an new service
      let largestId: number;
      if (clone === undefined || clone.length === 0) {
        largestId = 0;
      } else {
        largestId = Math.max(
          ...clone?.map((o: OrderServiceType) => +o?.order_service_list_id!)
        );
      }

      let service: OrderServiceType = {};
      // Normal service addition
      service = {
        is_deleted: false,
        order_service_list_id: id,
        new_id:
          largestId !== undefined && largestId !== null ? largestId + 1 : 1,
        id: largestId !== undefined && largestId !== null ? largestId + 1 : 1,
      };
      // special case if assembly already exist and we are adding disassemble service and vice-versa
      if (
        assemblyTypeService?.is_deleted === false &&
        disassembleOrderService?.id === id
      ) {
        service = {
          is_deleted: false,
          order_service_list_id: id,
          new_id:
            largestId !== undefined && largestId !== null ? largestId + 1 : 1,
          id: largestId !== undefined && largestId !== null ? largestId + 1 : 1,
          service_category_id: assemblyTypeService?.service_category_id,
        };
      }

      if (
        disassemblyTypeService?.is_deleted === false &&
        assembleOrderService?.id === id
      ) {
        service = {
          is_deleted: false,
          order_service_list_id: id,
          new_id:
            largestId !== undefined && largestId !== null ? largestId + 1 : 1,
          id: largestId !== undefined && largestId !== null ? largestId + 1 : 1,
          service_category_id: disassemblyTypeService?.service_category_id,
        };
      }
      clone.push(service);
      const newData = { ...orderDetails, order_services: clone };
      setOrderDetails(newData);
    }
  };
  const isDisabled = true;

  return (
    <Container disabled={isDisabled}>
      {sortedServices?.map((service: any) => {
        const selected = !!orderServices?.find(
          (s: OrderServiceType) =>
            s?.order_service_list_id === service?.id && s.is_deleted === false
        );
        return (
          <ServiceSlider
            serviceName={service?.type?.replaceAll('_', ' ')}
            serviceId={service?.id}
            isSelected={selected}
            toggle={toggleServices}
            key={service?.id}
            disabled={true}
          />
        );
      })}
    </Container>
  );
}

const Container = styled.div<{ disabled: boolean }>`
  display: flex;
  gap: 30px;
  flex: 1;
  @media screen and (max-width: 1170px) {
    flex-wrap: wrap;

    ${({ disabled }) =>
      disabled &&
      `
    pointer-events: none;

    > * {
    pointer-events: none;
    }
  `}
  }
`;

export default OrderServices;
