import React, { useEffect, useState } from 'react';
import {
  Box,
  Container,
  Grid,
  GridItem,
  HeroPortal,
  Input,
  ListCard,
  Pagination,
  Radio,
  RadioGroup,
  Switch,
  Tabs,
  Text,
} from '@nova-hf/ui';
import Wrapper from 'components/app-layout/Wrapper';
import { useRouter } from 'next/router';
import {
  CustomerType,
  PortingStatus,
  PortInSortKey,
  PortOutSortKey,
  SortDirection,
  usePortInsLazyQuery,
  usePortOutsLazyQuery,
} from 'typings/graphql';
import { formatDate } from 'utils/helpers';
import { withStaff } from 'utils/with-staff';

enum PortingType {
  PortIn,
  PortOut,
}

const Numeraflutningar = withStaff(() => {
  const [phoneNumberQuery, setPhoneNumberQuery] = useState('');
  const [nationalIdQuery, setNationalIdQuery] = useState('');
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize] = useState(20);
  const [customerType, setCustomerType] = useState(CustomerType.Unknown);
  const [portInSort, setPortInSort] = useState(PortInSortKey.CreatedOn);
  const [portOutSort, setPortOutSort] = useState(PortOutSortKey.CreatedOn);
  const [sortDirection] = useState(SortDirection.Descending);
  const [status] = useState(PortingStatus.Unknown);
  const [searchOnlyActive, setSearchOnlyActive] = useState(true);
  const [hasInputError, setHasInputError] = useState(false);

  const [currentPortingTab, setCurrentPortingTab] = useState(PortingType.PortIn);
  const router = useRouter();

  const [getPortInsResults, { loading: portInsLoading, data: portInsData }] = usePortInsLazyQuery();
  const [getPortOutsResults, { data: portOutsData }] = usePortOutsLazyQuery();

  useEffect(() => {
    if (currentPortingTab === PortingType.PortIn) {
      getPortInsResults({
        variables: {
          input: {
            customerType: customerType,
            sort: portInSort,
            direction: sortDirection,
            status: searchOnlyActive ? PortingStatus.Active : PortingStatus.Unknown,
            pageNumber: pageNumber,
            pageSize: pageSize,
            nationalId: nationalIdQuery,
            phoneNumber: phoneNumberQuery,
          },
        },
      });
    } else if (currentPortingTab === PortingType.PortOut) {
      getPortOutsResults({
        variables: {
          input: {
            customerType: customerType,
            sort: portOutSort,
            direction: sortDirection,
            status: searchOnlyActive ? PortingStatus.Active : PortingStatus.Unknown,
            pageNumber: pageNumber,
            pageSize: pageSize,
            nationalId: nationalIdQuery,
            phoneNumber: phoneNumberQuery,
          },
        },
      });
    }
  }, [
    currentPortingTab,
    phoneNumberQuery,
    nationalIdQuery,
    pageNumber,
    pageSize,
    customerType,
    portInSort,
    status,
    portOutSort,
    sortDirection,
    searchOnlyActive,
  ]);

  const portIns = portInsData?.portIns;
  const portOuts = portOutsData?.portOuts;

  const onSelectPage = (page: number, totalPages: number | undefined) => {
    if (page < 1 || page > (totalPages ?? 1)) return null;
    setPageNumber(page);
    window.scroll({ top: 0, behavior: 'smooth' });
  };

  const handleKeyDown = (event) => {
    const value: string = event.target?.value;
    if (event.key === 'Enter') {
      if (value && value.length == 7) {
        setPhoneNumberQuery(value);
        setNationalIdQuery('');
        setHasInputError(false);
      } else if (value && value.length == 10) {
        setPhoneNumberQuery('');
        setNationalIdQuery(value);
        setHasInputError(false);
      } else {
        setPhoneNumberQuery('');
        setNationalIdQuery('');
        setHasInputError(true);
      }
    }
  };

  return (
    <Wrapper header="dark">
      <Box marginTop={10}>
        <HeroPortal
          color="pink"
          title="Númeraflutningar"
          breadcrumbs={[
            {
              href: '/staff',
              text: 'Leit',
            },
            {
              text: 'Númeraflutningar',
            },
          ]}
        >
          <Box marginBottom={5}>
            <Input
              autoComplete="off"
              id="InputId"
              label="Sláðu inn símanúmer eða kennitölu"
              name="Porting input"
              type="number"
              onKeyDown={handleKeyDown}
              inputStatus={hasInputError ? 'error' : undefined}
              message={hasInputError ? 'Símanúmer eða kennitala ekki á réttu formi' : ''}
            />
          </Box>
        </HeroPortal>
        <Container>
          <Tabs
            tabBaseId="myTabs"
            tabBaseLabel="my tabs brings all the tabs in the hood"
            selectedTab="0"
            tabs={[
              {
                id: '0',
                label: 'Flutt Til Nova',
                onClick: () => setCurrentPortingTab(PortingType.PortIn),
                panelContent: (
                  <>
                    <Box display="flex">
                      <Box marginX={2}>
                        <RadioGroup ariaLabel="classical-elements">
                          <Text>Tegund viðskiptavinarins:</Text>
                          <Box display="flex" flexDirection="column">
                            <Radio
                              value="Allt"
                              isChecked={customerType === CustomerType.Unknown}
                              onChange={() => setCustomerType(CustomerType.Unknown)}
                              color="pink"
                            />
                            <Radio
                              value="Einstaklingar"
                              isChecked={customerType === CustomerType.Individual}
                              onChange={() => setCustomerType(CustomerType.Individual)}
                              color="pink"
                            />
                            <Radio
                              value="Fyrirtæki"
                              isChecked={customerType === CustomerType.Company}
                              onChange={() => setCustomerType(CustomerType.Company)}
                              color="pink"
                            />
                          </Box>
                        </RadioGroup>
                      </Box>
                      <Box marginX={2}>
                        <RadioGroup ariaLabel="classical-elements">
                          <Text>Raða eftir:</Text>
                          <Box display="flex" flexDirection="column">
                            <Radio
                              value="Skráð"
                              isChecked={portInSort === PortInSortKey.CreatedOn}
                              onChange={() => setPortInSort(PortInSortKey.CreatedOn)}
                              color="pink"
                            />
                            <Radio
                              value="Flutningsdagsetningunni"
                              isChecked={portInSort === PortInSortKey.PortInDate}
                              onChange={() => setPortInSort(PortInSortKey.PortInDate)}
                              color="pink"
                            />
                          </Box>
                        </RadioGroup>
                      </Box>
                      <Box marginX={2}>
                        <Text>Bara virkir númeraflutningar</Text>
                        <Switch
                          color="pink"
                          isOn={searchOnlyActive}
                          onToggle={() => setSearchOnlyActive(!searchOnlyActive)}
                        />
                      </Box>
                    </Box>
                    <Box marginY={5}>
                      {portInsLoading && <Box>loading....</Box>}
                      {portIns?.items.map((portIn) => (
                        <ListCard
                          key={portIn.id}
                          icon="mobile"
                          color={portIn.isActive ? 'green' : 'grey300'}
                          button={{
                            text: 'Skoða',
                            icon: 'longArrowRight',
                            onClick: () =>
                              router.push(`/staff/numeraflutningar/tilNova/${portIn.id}`),
                          }}
                        >
                          <Grid>
                            <GridItem gridColumn={{ sm: 'span1' }}>
                              <Text variant="pSmallRegular">Símanúmer</Text>
                              <Text variant="pMediumBold">{portIn.phoneNumber}</Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">nafn</Text>
                              <Text variant="pMediumBold">{portIn.fullName}</Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">Kennitala rétthafa</Text>
                              <Text variant="pMediumBold">{portIn.nationalId}</Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">Skráð</Text>
                              <Text variant="pMediumBold">
                                {formatDate(portIn.createdOn, 'd. MMM yyyy HH:mm')}
                              </Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">Flutningsdagsetning</Text>
                              <Text variant="pMediumBold">
                                {formatDate(portIn.portInDatetime, 'd. MMM yyyy HH:mm')}
                              </Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">Staða</Text>
                              <Text variant="pMediumBold">{portIn.portingStatus}</Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span1' }}>
                              <Text variant="pSmallRegular">Hver á næsta leik</Text>
                              <Text variant="pMediumBold">{portIn.responsibleCompany}</Text>
                            </GridItem>
                          </Grid>
                        </ListCard>
                      ))}
                      <Box display="flex" placeItems="center" width="100%" marginY={5}>
                        <Pagination
                          color="pink"
                          currentPage={portIns?.pageNumber ?? 1}
                          onNext={(n) => onSelectPage(n + 1, portIns?.totalPages)}
                          onPage={(n) => onSelectPage(n, portIns?.totalPages)}
                          onPrev={(n) => onSelectPage(n - 1, portIns?.totalPages)}
                          pages={portIns?.totalPages ?? 1}
                        />
                      </Box>
                    </Box>
                  </>
                ),
              },
              {
                id: '1',
                label: 'Flutt frá Nova',
                onClick: () => setCurrentPortingTab(PortingType.PortOut),
                panelContent: (
                  <>
                    <Box display="flex">
                      <Box marginX={2}>
                        <RadioGroup ariaLabel="classical-elements">
                          <Text>Tegund viðskiptavinarins:</Text>
                          <Box display="flex" flexDirection="column">
                            <Radio
                              value="Allt"
                              isChecked={customerType === CustomerType.Unknown}
                              onChange={() => setCustomerType(CustomerType.Unknown)}
                              color="pink"
                            />
                            <Radio
                              value="Einstaklingar"
                              isChecked={customerType === CustomerType.Individual}
                              onChange={() => setCustomerType(CustomerType.Individual)}
                              color="pink"
                            />
                            <Radio
                              value="Fyrirtæki"
                              isChecked={customerType === CustomerType.Company}
                              onChange={() => setCustomerType(CustomerType.Company)}
                              color="pink"
                            />
                          </Box>
                        </RadioGroup>
                      </Box>
                      <Box marginX={2}>
                        <RadioGroup ariaLabel="classical-elements">
                          <Text>Raða eftir:</Text>
                          <Box display="flex" flexDirection="column">
                            <Radio
                              value="Skráð"
                              isChecked={portOutSort === PortOutSortKey.CreatedOn}
                              onChange={() => setPortOutSort(PortOutSortKey.CreatedOn)}
                              color="pink"
                            />
                            <Radio
                              value="Staðfesta þann"
                              isChecked={portOutSort === PortOutSortKey.ConfirmOn}
                              onChange={() => setPortOutSort(PortOutSortKey.ConfirmOn)}
                              color="pink"
                            />
                          </Box>
                        </RadioGroup>
                      </Box>
                      <Box marginX={2}>
                        <Text>Bara virkir númeraflutningar</Text>
                        <Switch
                          color="pink"
                          isOn={searchOnlyActive}
                          onToggle={() => setSearchOnlyActive(!searchOnlyActive)}
                        />
                      </Box>
                    </Box>
                    <Box marginY={5}>
                      {portOuts?.items.map((portOut) => (
                        <ListCard
                          key={portOut.id}
                          icon="mobile"
                          color={portOut.isActive ? 'green' : 'grey300'}
                          button={{
                            text: 'Skoða',
                            icon: 'longArrowRight',
                            onClick: () =>
                              router.push(`/staff/numeraflutningar/fraNova/${portOut.id}`),
                          }}
                        >
                          <Grid>
                            <GridItem gridColumn={{ sm: 'span1' }}>
                              <Text variant="pSmallRegular">Símanúmer</Text>
                              <Text variant="pMediumBold">{portOut.phoneNumber}</Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">nafn</Text>
                              <Text variant="pMediumBold">{portOut.fullName}</Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">Kennitala rétthafa</Text>
                              <Text variant="pMediumBold">{portOut.nationalId}</Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">Skráð</Text>
                              <Text variant="pMediumBold">
                                {formatDate(portOut.createdOn, 'd. MMM yyyy HH:mm')}
                              </Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">Staðfesta þann</Text>
                              <Text variant="pMediumBold">
                                {portOut.confirmOn
                                  ? formatDate(portOut.confirmOn, 'd. MMM yyyy HH:mm')
                                  : '-'}
                              </Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span2' }}>
                              <Text variant="pSmallRegular">Staða</Text>
                              <Text variant="pMediumBold">{portOut.portingStatus}</Text>
                            </GridItem>
                            <GridItem gridColumn={{ sm: 'span1' }}>
                              <Text variant="pSmallRegular">Hver á næsta leik</Text>
                              <Text variant="pMediumBold">{portOut.responsibleCompany}</Text>
                            </GridItem>
                          </Grid>
                        </ListCard>
                      ))}
                      <Box display="flex" placeItems="center" width="100%" marginY={5}>
                        <Pagination
                          color="pink"
                          currentPage={portOuts?.pageNumber ?? 1}
                          onNext={(n) => onSelectPage(n + 1, portOuts?.totalPages)}
                          onPage={(n) => onSelectPage(n, portOuts?.totalPages)}
                          onPrev={(n) => onSelectPage(n - 1, portOuts?.totalPages)}
                          pages={portOuts?.totalPages ?? 1}
                        />
                      </Box>
                    </Box>
                  </>
                ),
              },
            ]}
          />
        </Container>
      </Box>
    </Wrapper>
  );
});

Numeraflutningar.getInitialProps = () => {
  return {
    namespacesRequired: ['staff'],
  };
};

export default Numeraflutningar;
