import React from 'react';
import { Box } from '@nova-hf/ui';
import { useRouter } from 'next/router';
import {
  ServiceStatus,
  ServiceType,
  useContractItemsServiceIdQuery,
  useMobileServicesQuery,
} from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

import ServiceList, { ServiceItems } from '../../components/service-cards/ServiceList';

type MobileServiceListProps = {
  filter?: string;
};

const MobileServiceList = ({ filter }: MobileServiceListProps) => {
  const { t } = useTranslation('alltSaman');
  const router = useRouter();
  const customerId = router.query.customerId;
  const contractId = router.query.contractId?.toString();
  const serviceItem: ServiceItems[] = [];
  const color = 'pink';

  const { data: contractItemsServiceData } = useContractItemsServiceIdQuery({
    variables: {
      input: {
        id: contractId?.toString() ?? '',
      },
    },
  });

  const contractItemsService = contractItemsServiceData?.contract?.contractItems;

  const { data, error, loading } = useMobileServicesQuery({
    variables: {
      input: {
        userId: customerId as string,
        status: ServiceStatus.Active,
        page: 1,
        perPage: 50,
      },
    },
  });

  const mobileServices = data?.mobileServices.services;
  const numberFilter = filter ?? '';

  const isInContract = (serviceId: string) => {
    return (
      contractItemsService?.some(
        (contractItemService) => contractItemService.serviceId === serviceId,
      ) ?? false
    );
  };

  mobileServices?.map((mobile) => {
    if (mobile) {
      if (!isInContract(mobile?.id) && mobile?.phoneNumber?.includes(numberFilter)) {
        serviceItem.push({
          key: mobile?.id ?? '',
          serviceTitle: mobile?.phoneNumber ?? '',
          serviceDescription: mobile?.user?.nickname
            ? mobile.user.nickname
            : mobile?.user?.name
            ? mobile.user.name
            : '',
          serviceType: mobile?.type ?? '',
        });
      }
    }
  });

  if (loading) {
    return <Box padding={30}>Loading.....</Box>;
  }
  if (error) {
    return <Box padding={30}>Something went wrong!</Box>;
  }

  return (
    <Box>
      <ServiceList
        icon={'mobile'}
        color={color}
        services={serviceItem}
        onClick
        type={ServiceType.Mobile}
        customerId={customerId as string}
        text={t('alltSaman.chooseFromNumbers')}
      />
    </Box>
  );
};

export default MobileServiceList;
