import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Controller, set, useForm } from 'react-hook-form';
import { usePengajuanTempoStoreDokumen } from '../../../../src-migrate/modules/register/stores/usePengajuanTempoStore';
import ProgressBar from '@ramonak/react-progress-bar';
import { UseToastOptions } from '@chakra-ui/react';
import { toast } from 'react-hot-toast';
import getFileBase64 from '@/core/utils/getFileBase64';
const Dokumen = ({ chekValid, buttonSubmitClick }) => {
  const { control, watch } = useForm();
  const {
    formDokumen,
    errorsDokumen,
    validateDokumen,
    updateFormDokumen,
    getJumlahDokumenDiisi,
  } = usePengajuanTempoStoreDokumen();

  // const handleInputChange = (event) => {
  //   const { name, value } = event.target;
  //   updateFormDokumen(name, value);
  //   validateDokumen();
  // };
  const handleInputChange = async (event) => {
    let fileBase64 = '';
    const { name } = event.target;
    const file = event.target.files?.[0];
    console.log('file', file);
    // Allowed file extensions
    const allowedExtensions = ['pdf', 'png', 'jpg', 'jpeg'];
    let fileExtension = '';
    if (file) {
      fileExtension = file.name.split('.').pop()?.toLowerCase(); // Extract file extension

      // Check if the file extension is allowed
      if (!fileExtension || !allowedExtensions.includes(fileExtension)) {
        toast.error(
          'Format file yang diijinkan adalah .pdf, .png, .jpg, atau .jpeg',
          { duration: 4000 }
        );

        event.target.value = '';
        return;
      }

      // Check for file size
      if (file.size > 2000000) {
        toast.error('Maksimal ukuran file adalah 2MB', { duration: 4000 });

        event.target.value = '';
        return;
      }

      // Convert file to Base64
      fileBase64 = await getFileBase64(file);
      updateFormDokumen(name, file.name, fileExtension, fileBase64);
      validateDokumen();
    }
  };

  const isFormValid = useMemo(
    () => Object.keys(errorsDokumen).length === 0,
    [errorsDokumen]
  );
  console.log('formDokumen', formDokumen?.dokumenNib?.name);
  const dokumenNibRef = useRef(null);
  const dokumenNpwpRef = useRef(null);
  const dokumenSppkpRef = useRef(null);
  const dokumenAktaPerubahanRef = useRef(null);
  const dokumenKtpDirutRef = useRef(null);
  const dokumenAktaPendirianRef = useRef(null);
  const dokumenLaporanKeuanganRef = useRef(null);
  const dokumenFotoKantorRef = useRef(null);
  const dokumenTempatBekerjaRef = useRef(null);

  useEffect(() => {
    const loadIndustries = async () => {
      if (!isFormValid) {
        const options = {
          behavior: 'smooth',
          block: 'center',
        };
        if (errorsDokumen.dokumenNib && dokumenNibRef.current) {
          dokumenNibRef.current.scrollIntoView(options);
          return;
        }
        if (errorsDokumen.dokumenNpwp && dokumenNpwpRef.current) {
          dokumenNpwpRef.current.scrollIntoView(options);
          return;
        }
        if (errorsDokumen.dokumenSppkp && dokumenSppkpRef.current) {
          dokumenSppkpRef.current.scrollIntoView(options);
          return;
        }
        if (
          errorsDokumen.dokumenAktaPerubahan &&
          dokumenAktaPerubahanRef.current
        ) {
          dokumenAktaPerubahanRef.current.scrollIntoView(options);
          return;
        }
        if (errorsDokumen.dokumenKtpDirut && dokumenKtpDirutRef.current) {
          dokumenKtpDirutRef.current.scrollIntoView(options);
          return;
        }
        if (
          errorsDokumen.dokumenAktaPendirian &&
          dokumenAktaPendirianRef.current
        ) {
          dokumenAktaPendirianRef.current.scrollIntoView(options);
          return;
        }
        if (
          errorsDokumen.dokumenLaporanKeuangan &&
          dokumenLaporanKeuanganRef.current
        ) {
          dokumenLaporanKeuanganRef.current.scrollIntoView(options);
          return;
        }
        if (errorsDokumen.dokumenFotoKantor && dokumenFotoKantorRef.current) {
          dokumenFotoKantorRef.current.scrollIntoView(options);
          return;
        }
        if (
          errorsDokumen.dokumenTempatBekerja &&
          dokumenTempatBekerjaRef.current
        ) {
          dokumenTempatBekerjaRef.current.scrollIntoView(options);
          return;
        }
      }
    };
    loadIndustries();
  }, [buttonSubmitClick, chekValid]);

  useEffect(() => {
    validateDokumen();
  }, [buttonSubmitClick]);
  return (
    <>
      <div className='flex justify-start'>
        <h1 className='font-bold'>Dokumen</h1>
      </div>
      <form className='flex mt-4 flex-col w-full '>
        <div className='w-full grid grid-cols-[1fr_auto_1fr] gap-5'>
          <div className='kolom-kiri w-full grid grid-rows-2 gap-10 '>
            <div className='w-full grid grid-cols-2 gap-5'>
              <div>
                <label className='form-label  text-nowrap'>
                  NIB (SIUP/TDP/SKDP)
                </label>
                <span className='text-xs opacity-60'>
                  Pastikan dokumen yang anda upload sudah benar
                </span>
              </div>
              <div className=''>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenNib'
                  name='dokumenNib'
                  type='file'
                  ref={dokumenNibRef}
                  className='form-input'
                  aria-invalid={errorsDokumen.dokumenNib}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
                {chekValid && (
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errorsDokumen.dokumenNib}
                  </div>
                )}
              </div>
            </div>
            <div className='w-full grid grid-cols-2 gap-5'>
              <div>
                <label className='form-label  text-nowrap'>
                  NPWP Perusahaan
                </label>
                <span className='text-xs opacity-60'>
                  Pastikan dokumen yang anda upload sudah benar
                </span>
              </div>
              <div className=''>
                <input
                  // value={formDokumen.dokumenNpwp}
                  id='dokumenNpwp'
                  name='dokumenNpwp'
                  type='file'
                  ref={dokumenNpwpRef}
                  className='form-input'
                  aria-invalid={errorsDokumen.dokumenNpwp}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
                {chekValid && (
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errorsDokumen.dokumenNpwp}
                  </div>
                )}
              </div>
            </div>
            <div className='w-full grid grid-cols-2 gap-5'>
              <div>
                <label className='form-label  text-nowrap'>SPPKP</label>
                <span className='text-xs opacity-60'>
                  Pastikan dokumen yang anda upload sudah benar
                </span>
              </div>
              <div className=''>
                <input
                  // value={formDokumen.dokumenSppkp}
                  id='dokumenSppkp'
                  name='dokumenSppkp'
                  type='file'
                  ref={dokumenSppkpRef}
                  className='form-input'
                  aria-invalid={errorsDokumen.dokumenSppkp}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
                {chekValid && (
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errorsDokumen.dokumenSppkp}
                  </div>
                )}
              </div>
            </div>
            <div className='w-full grid grid-cols-2 gap-5'>
              <div>
                <label className='form-label  text-nowrap'>
                  Akta Perubahan <span className=' opacity-60'>(Opsional)</span>
                </label>
                <span className='text-xs opacity-60'>
                  Pastikan dokumen yang anda upload sudah benar
                </span>
              </div>
              <div className=''>
                <input
                  // value={formDokumen.dokumenAktaPerubahan}
                  id='dokumenAktaPerubahan'
                  name='dokumenAktaPerubahan'
                  type='file'
                  ref={dokumenAktaPerubahanRef}
                  className='form-input'
                  aria-invalid={errorsDokumen.dokumenAktaPerubahan}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
                {chekValid && (
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errorsDokumen.dokumenAktaPerubahan}
                  </div>
                )}
              </div>
            </div>
            <div className='w-full grid grid-cols-2 gap-5'>
              <div>
                <label className='form-label  text-nowrap'>
                  KTP Dirut/Direktur{' '}
                  <span className=' opacity-60'>(Opsional)</span>
                </label>
                <span className='text-xs opacity-60'>
                  Pastikan dokumen yang anda upload sudah benar
                </span>
              </div>
              <div className=''>
                <input
                  // value={formDokumen.dokumenKtpDirut}
                  id='dokumenKtpDirut'
                  name='dokumenKtpDirut'
                  type='file'
                  ref={dokumenKtpDirutRef}
                  className='form-input'
                  aria-invalid={errorsDokumen.dokumenKtpDirut}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
                {chekValid && (
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errorsDokumen.dokumenKtpDirut}
                  </div>
                )}
              </div>
            </div>
          </div>
          <div className='w-px bg-gray-300'></div>
          <div className='kolom kanan w-full grid grid-rows-2 gap-10 '>
            <div className='w-full grid grid-cols-2 gap-5'>
              <div>
                <label className='form-label  text-nowrap'>
                  Akta Pendirian <span className=' opacity-60'>(Opsional)</span>
                </label>
                <span className='text-xs opacity-60'>
                  Pastikan dokumen yang anda upload sudah benar
                </span>
              </div>
              <div className=''>
                <input
                  // value={formDokumen.dokumenAktaPendirian}
                  id='dokumenAktaPendirian'
                  name='dokumenAktaPendirian'
                  type='file'
                  ref={dokumenAktaPendirianRef}
                  className='form-input'
                  aria-invalid={errorsDokumen.dokumenAktaPendirian}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
                {chekValid && (
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errorsDokumen.dokumenAktaPendirian}
                  </div>
                )}
              </div>
            </div>
            <div className='w-full grid grid-cols-2 gap-5'>
              <div>
                <label className='form-label  text-nowrap'>
                  Laporan Keuangan
                  <span className=' opacity-60'>(Opsional)</span>
                </label>
                <span className='text-xs opacity-60'>
                  Pastikan dokumen yang anda upload sudah benar
                </span>
              </div>
              <div className=''>
                <input
                  // value={formDokumen.dokumenLaporanKeuangan}
                  id='dokumenLaporanKeuangan'
                  name='dokumenLaporanKeuangan'
                  type='file'
                  ref={dokumenLaporanKeuanganRef}
                  className='form-input'
                  aria-invalid={errorsDokumen.dokumenLaporanKeuangan}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
                {chekValid && (
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errorsDokumen.dokumenLaporanKeuangan}
                  </div>
                )}
              </div>
            </div>
            <div className='w-full grid grid-cols-2 gap-5'>
              <div>
                <label className='form-label  text-nowrap'>
                  Foto Kantor (Tampak Depan)
                </label>
                <span className='text-xs opacity-60'>
                  Pastikan dokumen yang anda upload sudah benar
                </span>
              </div>
              <div className=''>
                <input
                  // value={formDokumen.dokumenFotoKantor}
                  id='dokumenFotoKantor'
                  name='dokumenFotoKantor'
                  type='file'
                  ref={dokumenFotoKantorRef}
                  className='form-input'
                  aria-invalid={errorsDokumen.dokumenFotoKantor}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
                {chekValid && (
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errorsDokumen.dokumenFotoKantor}
                  </div>
                )}
              </div>
            </div>
            <div className='w-full grid grid-cols-2 gap-5'>
              <div>
                <label className='form-label  text-nowrap'>
                  Tempat Bekerja
                </label>
                <span className='text-xs opacity-60'>
                  Pastikan dokumen yang anda upload sudah benar
                </span>
              </div>
              <div className=''>
                <input
                  // value={formDokumen.dokumenTempatBekerja}
                  id='dokumenTempatBekerja'
                  name='dokumenTempatBekerja'
                  type='file'
                  ref={dokumenTempatBekerjaRef}
                  className='form-input'
                  aria-invalid={errorsDokumen.dokumenTempatBekerja}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
                {chekValid && (
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errorsDokumen.dokumenTempatBekerja}
                  </div>
                )}
              </div>
            </div>
            <div></div>
          </div>
        </div>
      </form>
      <div className='w-1/2 mt-8 flex gap-3 flex-col'>
        <div className='flex justify-between'>
          <p className='font-bold'>Upload Progress</p>
          <p>
            <span className='text-red-500 font-bold'>
              {parseInt((getJumlahDokumenDiisi() / 9) * 100)} %
            </span>
            <span className='ml-2 opacity-60'>
              {getJumlahDokumenDiisi() > 5
                ? getJumlahDokumenDiisi() == 9
                  ? 'Selesai'
                  : 'Sedikit Lagi'
                : ''}
            </span>
          </p>
        </div>
        {/* 50 keatas baru muncul kata kata sedikit lagi */}
        <ProgressBar
          completed={getJumlahDokumenDiisi()}
          bgColor='#ef4444'
          labelAlignment='outside'
          isLabelVisible={false}
          baseBgColor='#E5E7EB'
          labelColor='#e80909'
          labelSize='0'
          maxCompleted={9}
        />
        <span className='opacity-75'>
          Tingkatin sedikit lagi agar pengajuan tempo kamu dapat kami proses
          dengan cepat
        </span>
      </div>
    </>
  );
};

export default Dokumen;
