import { type ReactNode, useEffect, useRef } from 'react';
import { useQueryClient } from 'react-query';
import { useLocation } from 'react-router-dom';

import CircularProgress from '@material-hu/mui/CircularProgress';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';

import { useGetLoanOffer } from '../hooks/useGetLoanOffer';
import { microloansKeys } from '../queries';
import { type LoanOffer } from '../types';

import RequestOfferEmptyState from './requestOffer/RequestOfferEmptyState';
import RequestOfferErrorState from './requestOffer/RequestOfferErrorState';
import RequestOfferFaqsSection from './requestOffer/RequestOfferFaqsSection';
import RequestOfferStepsForm from './requestOffer/RequestOfferStepsForm';

const renderEmptyState = () => (
  <Stack sx={{ width: '100%', gap: 0 }}>
    <RequestOfferEmptyState />
  </Stack>
);

const renderAvailableState = (loanOffer: LoanOffer) => (
  <>
    <Stack sx={{ width: '100%', minWidth: 0 }}>
      <RequestOfferStepsForm loanOffer={loanOffer} />
    </Stack>

    <Divider
      sx={{
        my: 6,
        borderColor: theme => theme.palette.new.border.neutral.divider,
      }}
    />

    <RequestOfferFaqsSection />
  </>
);

const RequestOffer = () => {
  const queryClient = useQueryClient();
  const location = useLocation();
  const { loanOffer, isLoading, isError, retry } = useGetLoanOffer();

  useEffect(() => {
    return () => {
      void queryClient.invalidateQueries(microloansKeys.loanOffer());
    };
  }, [queryClient]);

  const isFirstNavigation = useRef(true);

  useEffect(() => {
    if (isFirstNavigation.current) {
      isFirstNavigation.current = false;
      return;
    }
    void retry();
  }, [location.key]);

  if (isLoading) {
    return (
      <Stack
        sx={{
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          minHeight: 200,
          py: 6,
        }}
      >
        <CircularProgress />
      </Stack>
    );
  }

  let main: ReactNode;

  if (isError) {
    main = (
      <RequestOfferErrorState
        onRetry={() => {
          void retry();
        }}
      />
    );
  } else if (!loanOffer) {
    main = renderEmptyState();
  } else {
    main =
      loanOffer.availability === 'available'
        ? renderAvailableState(loanOffer)
        : renderEmptyState();
  }

  return <Stack sx={{ width: '100%', gap: 0 }}>{main}</Stack>;
};

export default RequestOffer;
