import * as React from 'react';
import { useEffect, useState } from 'react';
import { ProfileBoxItem } from 'components/profile-list/ProfileBoxItem';
import { UsageBoxItemLoading } from 'components/usage/UsageBoxItemLoading';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import Authentication from 'store/authentication';
import Profile from 'store/models/Profile';
import { useServiceLazyQuery, useSubscriptionQuery } from 'typings/graphql';
import { connectionColor, profileColor } from 'utils/helpers';
import { WithTranslation, withTranslation } from 'utils/i18n';

import { AddConnectionItem, ConnectionItem } from '../../components/connection/ConnectionItem';

interface IConnectionsProps extends WithTranslation {
  authentication: Authentication;
  profile: Profile;
  inGrid?: boolean;
  onClick?: () => void;
  onSelect: (packIndex: number) => void;
  selectedPack?: string;
  editMenu?: object;
}

const Connections = ({
  authentication,
  profile,
  t,
  inGrid = false,
  onClick,
  onSelect,
  selectedPack,
  editMenu,
}: IConnectionsProps) => {
  const { statusCode, subscriptionId } = profile;

  const router = useRouter();
  const [fiberDescription, setFiberDescription] = useState('');
  const [serviceId, setServiceId] = useState('');
  const { accountInput } = authentication;

  const addConnectionClick = (type: 'backup' | 'mobile' | 'internet' | 'forwarding') => {
    router.push(`/${router.query.ssn}/thjonusta/${subscriptionId}/tengja?pack=${type}`);
  };

  const isGuid = (input: string): boolean => {
    const guidPattern =
      /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
    if (guidPattern.test(input) && input !== serviceId) {
      setServiceId(input);
    }
    return guidPattern.test(input);
  };

  const [getService] = useServiceLazyQuery({
    onCompleted(data) {
      if (data?.service?.name) {
        setFiberDescription(data.service.name);
      } else {
        return;
      }
    },
  });

  useEffect(() => {
    if (isGuid(serviceId)) {
      getService({
        variables: {
          serviceId: serviceId,
        },
      });
    }
  }, [serviceId]);

  const connectionData = profile.connections.map((connection) => {
    const { subscriptionId } = connection;
    return useSubscriptionQuery({
      variables: { subscriptionId, accountInput },
    });
  });

  return (
    <ProfileBoxItem
      key={subscriptionId}
      profile={profile}
      color={profileColor(profile.rateplan)}
      status={t(`statusCode.${statusCode}`)}
      inGrid={!!inGrid}
      onClick={onClick}
      editMenu={editMenu}
    >
      {profile.connections.map((connection, i) => {
        const selected = !!selectedPack && parseInt(selectedPack, 10) === i;
        const selectFunc = () => {
          onSelect(i);
        };
        const { loading, error, data } = connectionData[i];
        if (error) {
          return <div>error</div>;
        }
        if (loading) {
          return <UsageBoxItemLoading />;
        }
        const profiles = data?.me?.profiles;
        const usedProfile = profiles && profiles[0];
        const userName = usedProfile?.name ?? '';
        const fiberAddress = connection.type === 'Internet' && usedProfile?.title;

        const title =
          connection.type === 'Mobile'
            ? userName?.split(' ')[0]
            : t(`subscription:subscription.type.${connection.type}`);
        const description = fiberAddress
          ? fiberAddress?.split(',')[0]
          : isGuid(connection.subscriptionId)
          ? fiberDescription
          : connection.subscriptionId;
        return (
          <ConnectionItem
            key={connection.id}
            color={connectionColor(connection.type)}
            selected={selected}
            onSelect={selectFunc}
            type={connection.type}
            title={title}
            description={description}
            isActive={connection.isActive}
            className="tourConnectionItem"
          />
        );
      })}
      {Array(profile.availableInternetConnections)
        .fill('Net')
        .map((value, i) => (
          <AddConnectionItem
            key={i}
            type="Internet"
            description={value}
            onClick={() => {
              addConnectionClick('internet');
            }}
            className="tourEmptyInternetConnectionItem"
          />
        ))}

      {Array(profile.availableBackupConnections)
        .fill('4.5G varaleið')
        .map((value, i) => (
          <AddConnectionItem
            key={i}
            type="BackupConnection"
            description={value}
            onClick={() => {
              addConnectionClick('backup');
            }}
            className="tourEmptyBackupConnectionItem"
          />
        ))}

      {Array(profile.availableNumberForwardConnections)
        .fill('Vinnusími')
        .map((value, i) => (
          <AddConnectionItem
            key={i}
            type="CallForwarding"
            description={value}
            onClick={() => {
              addConnectionClick('forwarding');
            }}
            className="tourEmptyNumberForwardConnectionItem"
          />
        ))}

      {Array(profile.availableMobileConnections)
        .fill('Farsími eða snjalltæki')
        .map((value, i) => (
          <AddConnectionItem
            key={i}
            type="Mobile"
            description={value}
            onClick={() => {
              addConnectionClick('mobile');
            }}
            className="tourEmptyMobileConnectionItem"
          />
        ))}
    </ProfileBoxItem>
  );
};

export default withTranslation(['subscriptions', 'subscription'])(
  inject('authentication')(observer(Connections)),
);
