import React from 'react';
import { useMemo, useState, useEffect, useRef } from 'react';
import Stepper from './Stepper';
import InformasiPerusahaan from './informasiPerusahaan';
import KontakPerusahaan from './KontakPerusahaan';
import Pengiriman from './Pengiriman';
import Referensi from './Referensi';
import Dokumen from './Dokumen';
import Konfirmasi from './Konfirmasi';
import { getAuth } from '~/libs/auth';
import { useRouter } from 'next/router';
import { Controller, useForm } from 'react-hook-form';
import {
  usePengajuanTempoStore,
  usePengajuanTempoStoreKontakPerson,
  usePengajuanTempoStorePengiriman,
  usePengajuanTempoStoreSupplier,
  usePengajuanTempoStoreDokumen,
} from '../../../../src-migrate/modules/register/stores/usePengajuanTempoStore';
import { ChevronRightIcon, ChevronLeftIcon } from '@heroicons/react/24/outline';
import createPengajuanTempoApi from '../api/createPengajuanTempoApi';
import { Button, Checkbox, Spinner, Tooltip } from '@chakra-ui/react';
import clsxm from '~/libs/clsxm';
import { toast } from 'react-hot-toast';
import useDevice from '@/core/hooks/useDevice';
import odooApi from '~/libs/odooApi';
const PengajuanTempo = () => {
  const { isDesktop, isMobile } = useDevice();
  const [currentStep, setCurrentStep] = React.useState(0);
  const NUMBER_OF_STEPS = 6;
  const [isLoading, setIsLoading] = useState(false);
  const [bigData, setBigData] = useState();
  const [idTempo, setIdTempo] = useState(0);
  const { form, errors, validate, updateForm } = usePengajuanTempoStore();
  const { control, watch, setValue } = useForm();
  const auth = getAuth();
  const router = useRouter();
  const { formDokumen, errorsDokumen, validateDokumen, updateFormDokumen } =
    usePengajuanTempoStoreDokumen();
  const {
    formKontakPerson,
    errorsKontakPerson,
    validateKontakPerson,
    updateFormKontakPerson,
  } = usePengajuanTempoStoreKontakPerson();
  const {
    formSupplier,
    errorsSupplier,
    validateSupplier,
    updateFormSupplier,
    hasSavedata,
    updateHasSave,
  } = usePengajuanTempoStoreSupplier();
  const {
    formPengiriman,
    errorsPengiriman,
    validatePengiriman,
    updateFormPengiriman,
  } = usePengajuanTempoStorePengiriman();
  const [notValid, setNotValid] = useState(false);
  const [buttonSubmitClick, setButtonSubmitClick] = useState(false);
  const stepDivs = [
    <InformasiPerusahaan
      key='informasi-perusahaan'
      chekValid={notValid}
      buttonSubmitClick={buttonSubmitClick}
    />,
    <KontakPerusahaan
      key='kontak-perusahaan'
      chekValid={notValid}
      buttonSubmitClick={buttonSubmitClick}
    />,
    <Pengiriman
      key='pengiriman'
      chekValid={notValid}
      buttonSubmitClick={buttonSubmitClick}
    />,
    <Referensi
      key='referensi'
      chekValid={notValid}
      buttonSubmitClick={buttonSubmitClick}
      data={bigData?.supplierIds}
    />,
    <Dokumen
      key='dokumen'
      chekValid={notValid}
      buttonSubmitClick={buttonSubmitClick}
    />,
    <Konfirmasi
      key='konfirmasi'
      chekValid={notValid}
      buttonSubmitClick={buttonSubmitClick}
    />,
  ];

  const stepDivsError = [
    errors,
    errorsKontakPerson,
    errorsPengiriman,
    errorsSupplier,
    errorsDokumen,
    <div key='konfirmasi'>Konfirmasi</div>,
  ];
  const stepDivsForm = [
    form,
    formKontakPerson,
    formPengiriman,
    formSupplier,
    formDokumen,
    '',
  ];
  const stepDivsUpdateForm = [
    updateForm,
    updateFormKontakPerson,
    updateFormPengiriman,
    updateFormSupplier,
    updateFormDokumen,
    <div key='konfirmasi'>Konfirmasi</div>,
  ];
  const stepLabels = [
    'informasi_perusahaan',
    'kontak_person',
    'Pengiriman',
    'Referensi',
    'Dokumen',
    'Konfirmasi',
  ];
  const isFormValid = useMemo(
    () => Object.keys(stepDivsError[currentStep]).length === 0,
    [stepDivsError[currentStep]]
  );
  useEffect(() => {
    validate();
    validateKontakPerson();
    validatePengiriman();
    validateDokumen();
    updateHasSave(false);
    if (isFormValid) {
      window.scrollTo({
        top: 0,
        behavior: 'smooth',
      });
    }
  }, [currentStep, buttonSubmitClick]);
  useEffect(() => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  }, [currentStep]);

  useEffect(() => {
    const loadBigData = async () => {
      const toCamelCase = (str) =>
        str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());

      const transformKeysToCamelCase = (data) => {
        if (Array.isArray(data)) {
          return data.map((item) => transformKeysToCamelCase(item));
        } else if (data && typeof data === 'object') {
          return Object.keys(data).reduce((acc, key) => {
            const camelKey = toCamelCase(key); // Ubah kunci menjadi camelCase
            acc[camelKey] = transformKeysToCamelCase(data[key]); // Rekursif untuk nested object atau array
            return acc;
          }, {});
        }
        return data; // Jika bukan object atau array, kembalikan nilai aslinya
      };

      try {
        const dataPaymentTerm = await odooApi(
          'GET',
          `/api/v1/partner/detail-tempo/${auth.parentId}`
        );

        console.log('Original dataPaymentTerm', dataPaymentTerm);

        const transformedData = transformKeysToCamelCase(dataPaymentTerm);

        console.log('Transformed dataPaymentTerm', transformedData);

        setBigData(transformedData);
      } catch (error) {
        console.error('Error loading dataPaymentTerm:', error);
      }
    };

    loadBigData();
  }, []);

  console.log('bigData', bigData);

  useEffect(() => {
    const cachedData = bigData;
    console.log('data_lama', getFromLocalStorage(stepLabels[currentStep]));

    if (cachedData) {
      // Ambil kunci-kunci yang relevan berdasarkan currentStep dari stepDivsForm
      const formKeys = stepDivsForm[currentStep]
        ? Object.keys(stepDivsForm[currentStep])
        : [];
      console.log('formKeys', formKeys);
      if (currentStep === 3) {
        console.log('cachedData', cachedData.supplierIds[0]);
        stepDivsUpdateForm[currentStep](cachedData.supplierIds);
      } else if (currentStep === 4) {
        formKeys.forEach((key) => {
          if (cachedData[key]) {
            // Proses hanya kunci yang ada di cachedData
            const { name, format, base64 } = cachedData[key];
            stepDivsUpdateForm[currentStep](key, name, format, base64);
          }
        });
      } else {
        formKeys.forEach((key) => {
          if (cachedData[key]) {
            // Ubah data menjadi string
            const stringData =
              typeof cachedData[key] === 'object'
                ? JSON.stringify(cachedData[key]) // Untuk objek atau array
                : String(cachedData[key]); // Untuk tipe primitif

            // Kirim data yang sudah diubah ke string ke stepDivsUpdateForm
            stepDivsUpdateForm[currentStep](key, stringData);
          }
        });
      }
    }

    validate();
    validateKontakPerson();
    validatePengiriman();
    validateDokumen();
    validateSupplier();
    updateHasSave(false);
  }, [currentStep, bigData]);

  const goToNextStep = () => {
    if (!isFormValid) {
      setNotValid(true);
      setButtonSubmitClick(!buttonSubmitClick);
      return;
    } else {
      // saveToLocalStorage(stepLabels[currentStep], stepDivsForm[currentStep]);
      if (currentStep == 3) {
        handleDaftarTempoSupplier();
      } else if (currentStep == 4) {
        handleDaftarTempoDokumen();
      } else {
        handleDaftarTempoPerPage(
          stepLabels[currentStep],
          stepDivsForm[currentStep]
        );
      }
      setButtonSubmitClick(!buttonSubmitClick);
      setNotValid(false);
    }
    setCurrentStep((prev) => (prev === NUMBER_OF_STEPS - 1 ? prev : prev + 1));
  };

  const handleDaftarTempoPerPage = async (
    label,
    formData,
    tempoRequest = false
  ) => {
    for (const error of stepDivsError) {
      if (error.length > 0) {
        return;
      }
    }
    const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
    setIsLoading(true);
    try {
      const address = await createPengajuanTempoApi({
        id: idTempo,
        user_id: auth.parentId,
        section: label,
        tempo_request: tempoRequest,
        ...formData,
      });
      if (address.id) {
        setIdTempo(address.id);
      }
      toast.dismiss(toastId);
      setIsLoading(false);
    } catch (error) {
      toast.dismiss(toastId);
      setIsLoading(false);

      toast.error('Terjadi kesalahan dalam pengiriman formulir');
      console.error(error);
    }
  };
  const handleDaftarTempoDokumen = async () => {
    for (const error of stepDivsError) {
      if (error.length > 0) {
        console.log('iman_erro', error);
        return;
      }
    }
    const formattedDokumen = Object.entries(formDokumen).map(([key, doc]) => ({
      documentName: key,
      details: {
        name: doc.name,
        format: doc.format,
        base64: doc.base64,
      },
    }));
    const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
    setIsLoading(true);
    try {
      const address = await createPengajuanTempoApi({
        id: idTempo,
        user_id: auth.parentId,
        formDocs: JSON.stringify(formattedDokumen),
      });
      if (address.id) {
        setIdTempo(address.id);
      }
      toast.dismiss(toastId);
      setIsLoading(false);
    } catch (error) {
      toast.dismiss(toastId);
      setIsLoading(false);

      toast.error('Terjadi kesalahan dalam pengiriman formulir');
      console.error(error);
    }
  };
  const handleDaftarTempoSupplier = async () => {
    for (const error of stepDivsError) {
      if (error.length > 0) {
        return;
      }
    }
    const productOrder = formSupplier.map((product) => ({
      supplier: product.supplier,
      pic: product.pic,
      telepon: product.telepon,
      durasiTempo: product.durasiTempo,
      creditLimit: product.creditLimit,
    }));
    console.log('productOrder', productOrder);
    const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
    setIsLoading(true);
    try {
      const address = await createPengajuanTempoApi({
        id: idTempo,
        user_id: auth.parentId,
        formSupplier: JSON.stringify(productOrder),
        section,
      });
      if (address.id) {
        setIdTempo(address.id);
      }
      toast.dismiss(toastId);
      setIsLoading(false);
    } catch (error) {
      toast.dismiss(toastId);
      setIsLoading(false);

      toast.error('Terjadi kesalahan dalam pengiriman formulir');
      console.error(error);
    }
  };
  const handleDaftarTempo = async () => {
    for (const error of stepDivsError) {
      if (error.length > 0) {
        return;
      }
    }
    const productOrder = formSupplier.map((product) => ({
      supplier: product.supplier,
      pic: product.pic,
      telepon: product.telepon,
      durasiTempo: product.durasiTempo,
      creditLimit: product.creditLimit,
    }));

    const formattedDokumen = Object.entries(formDokumen).map(([key, doc]) => ({
      documentName: key,
      details: {
        name: doc.name,
        format: doc.format,
        base64: doc.base64,
      },
    }));

    const data2 = {
      user_id: auth.id,
      ...form,
      ...formKontakPerson,
      ...formPengiriman,
      formDocs: JSON.stringify(formattedDokumen),
      formSupplier: JSON.stringify(productOrder),
    };
    const toastId = toast.loading('Mengirimkan formulir pengajuan tempo...');
    setIsLoading(true);
    try {
      let address5;
      const address = await createPengajuanTempoApi({
        id: 0,
        user_id: auth.parentId,
        tempo_request: tempoRequest,
        ...form,
      });
      console.log('address', address);
      if (address.id) {
        const address2 = await createPengajuanTempoApi({
          id: address.id,
          user_id: address.userId,
          ...formKontakPerson,
        });
        if (address2.id) {
          const address3 = await createPengajuanTempoApi({
            id: address2.id,
            user_id: address2.userId,
            ...formPengiriman,
          });
          if (address3.id) {
            const address4 = await createPengajuanTempoApi({
              id: address3.id,
              user_id: address3.userId,
              formDocs: JSON.stringify(formattedDokumen),
            });
            if (address4.id) {
              address5 = await createPengajuanTempoApi({
                id: address4.id,
                user_id: address4.userId,
                tempo_request: true,
                formSupplier: JSON.stringify(productOrder),
              });
            }
          }
        }
      }
      toast.dismiss(toastId);
      setIsLoading(false);

      if (address5.id) {
        toast.success('Pengajuan tempo berhasil dilakukan');
        removeFromLocalStorage();
        router.push('/pengajuan-tempo/finish?tempo_id=SO-2023-06480');
      }
    } catch (error) {
      toast.dismiss(toastId);
      setIsLoading(false);

      toast.error('Terjadi kesalahan dalam pengiriman formulir');
      console.error(error);
    }
  };

  const goToPreviousStep = () => {
    setCurrentStep((prev) => (prev <= 0 ? prev : prev - 1));
  };

  const saveToLocalStorage = (key, form) => {
    localStorage.setItem(key, JSON.stringify(form));
  };

  const getFromLocalStorage = (key) => {
    const itemStr = localStorage.getItem(key);
    if (!itemStr) return null;

    const item = JSON.parse(itemStr);
    return item;
  };
  const removeFromLocalStorage = () => {
    for (const key of stepLabels) {
      localStorage.removeItem(key);
    }
  };

  return (
    <>
      <div className='container flex flex-col items-center '>
        <h1 className='text-h-sm md:text-title-sm font-semibold text-center mb-6'>
          Form Pengajuan Tempo
        </h1>
        <p className='text-center mb-4'>
          Lorem ipsum dolor sit amet consectetur. Commodo suspendisse at enim
          magnis ut quisque rhoncus. Felis volutpat fringilla sollicitudin
          ultricies. Enim non eget in lorem netus. Nisl pharetra accumsan diam
          suspendisse.
        </p>
      </div>
      <div className='h-[2px] w-full mb-20 bg-gray_r-3' />

      <div className='container mt-10 flex flex-col'>
        <div className='flex items-center justify-center'>
          <Stepper currentStep={currentStep} numberOfSteps={NUMBER_OF_STEPS} />
        </div>
        <div>{stepDivs[currentStep]}</div>
        {isDesktop && <section className='flex gap-10 mt-10'></section>}
        {isMobile && (
          <div className='h-[2px] bg-gray-300 w-[120%] inset-0 mt-4 mb-4 relative transform -translate-x-5'></div>
        )}
        <div
          className={`flex ${
            isMobile
              ? 'flex-col justify-start items-start'
              : 'flex-row justify-end items-center'
          }   gap-4 mb-8`}
        >
          <span className='text-xs opacity-60'>
            *Pastikan data yang anda masukan sudah benar dan sesuai
          </span>
          {currentStep < 5 && (
            <Tooltip
              label={clsxm({
                'Klik simpan data terlebih dahulu':
                  currentStep === 3 && !hasSavedata,
              })}
            >
              <Button
                colorScheme='red'
                w={`${isMobile ? 'full' : 'fit'}`}
                isDisabled={
                  (currentStep === 3 && !hasSavedata) ||
                  currentStep === NUMBER_OF_STEPS - 1
                }
                onClick={goToNextStep}
              >
                Langkah Selanjutnya {<ChevronRightIcon className='w-5' />}
              </Button>
            </Tooltip>
          )}
          {currentStep == 5 && (
            <Button
              colorScheme='red'
              w={`${isMobile ? 'full' : 'fit'}`}
              onClick={handleDaftarTempo}
            >
              Daftar Tempo {<ChevronRightIcon className='w-5' />}
            </Button>
          )}
        </div>
      </div>
    </>
  );
};

export default PengajuanTempo;
