import Seo from '@/core/components/Seo';
import dynamic from 'next/dynamic';
import SimpleFooter from '@/core/components/elements/Footer/SimpleFooter';
import BasicLayout from '@/core/components/layouts/BasicLayout';
import DesktopView from '@/core/components/views/DesktopView';
import MobileView from '@/core/components/views/MobileView';
import { getAuth } from '~/libs/auth';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import odooApi from '@/core/api/odooApi';

const PagePengajuanTempo = dynamic(() =>
  import('@/lib/pengajuan-tempo/component/PengajuanTempo')
);

export default function TrackingOrder() {
  const [tempo, setTempo] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const auth = getAuth();
  const router = useRouter();

  useEffect(() => {
    const loadTempo = async () => {
      try {
        if (auth?.partnerId) {
          const dataTempo = await odooApi(
            'GET',
            `/api/v1/check/${auth.partnerId}/tempo`
          );
          setTempo(dataTempo);
        }
      } catch (error) {
        console.error('Error fetching tempo data:', error);
      } finally {
        setIsLoading(false);
      }
    };

    if (auth) {
      loadTempo();
    } else {
      setIsLoading(false);
    }
  }, []);
  useEffect(() => {
    if (!auth) {
      const nextUrl = encodeURIComponent(router.asPath);
      router.push(`/login?next=${nextUrl}`);
    } else if (
      auth.tempoProgres === 'approve' &&
      tempo?.paymentTerm?.toLowerCase().includes('tempo')
    ) {
      router.push('/pengajuan-tempo/approve');
    } else if (!auth.parentId) {
      router.push('/pengajuan-tempo/switch-account');
    } else if (auth.tempoProgres === 'review' && !tempo?.paymentTerm) {
      router.push('/pengajuan-tempo/review');
    } else if (auth.tempoProgres === 'rejected') {
      router.push('/pengajuan-tempo/rejected');
    } else {
      setIsLoading(false);
    }
  }, [tempo]);

  if (isLoading || !auth || !tempo) {
    return null; // Tidak render apa pun selama loading atau auth/tempo belum tersedia
  }

  return (
    <>
      <Seo title='Pengajuan Tempo - Indoteknik.com' />
      <DesktopView>
        <BasicLayout>
          <PagePengajuanTempo />
        </BasicLayout>
      </DesktopView>
      <MobileView>
        <BasicLayout>
          <PagePengajuanTempo />
        </BasicLayout>
      </MobileView>
    </>
  );
}
