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';
import Image from 'next/image';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
const KonfirmasiDokumen = ({ chekValid, buttonSubmitClick, isKonfirmasi }) => {
  const { control, watch } = useForm();
  const [isExample, setIsExample] = useState(false);
  const [popUpTittle, setPopUpTittle] = useState(false);
  const [popUpSource, setSource] = useState(false);
  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];
    // 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]
  );
  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]);
  console.log('formDokumen', formDokumen);
  return (
    <>
      <BottomPopup
        className=''
        title='Dokumen Tittle'
        active={isExample}
        close={() => setIsExample(false)}
      >
        <div className='flex p-2'>
          <Image
            src='/images/NO-SPPKP-FORMAT-TEMPLATE.jpg'
            alt='Contoh SPPKP'
            className='w-full h-full '
            width={800}
            height={800}
            quality={85}
          />
        </div>
      </BottomPopup>
      <h1 className={`font-bold ${isKonfirmasi ? 'text-xl' : ''}`}>Dokumen</h1>
      <form className='flex flex-col w-full gap-5'>
        <div className='w-full flex flex-row items-center '>
          <div className='w-2/5'>
            <label className='form-label  text-nowrap'>
              NIB (SIUP/TDP/SKDP)
            </label>
          </div>
          <div className='w-3/5'>
            <div className='flex flex-row items-start justify-between'>
              <span className='w-3/5  text-gray-600 truncate'>
                {formDokumen?.dokumenNib?.name}
              </span>
              <div className='w-2/5 '>
                <label
                  htmlFor='dokumenNib'
                  className='cursor-pointer bg-red-500 hover:bg-red-600 text-white py-1 px-3 text-sm rounded'
                >
                  Ubah
                </label>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenNib'
                  name='dokumenNib'
                  type='file'
                  title=' '
                  ref={dokumenNibRef}
                  className='hidden'
                  aria-invalid={errorsDokumen.dokumenNib}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
              </div>
            </div>
            {chekValid && (
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errorsDokumen.dokumenNib}
              </div>
            )}
          </div>
        </div>
        <div className='w-full flex flex-row items-center '>
          <div className='w-2/5'>
            <label className='form-label  text-nowrap'>NPWP Perusahaan</label>
          </div>
          <div className='w-3/5'>
            <div className='flex flex-row items-start justify-between'>
              <span className='w-3/5  text-gray-600 truncate'>
                {formDokumen?.dokumenNpwp?.name}
              </span>
              <div className='w-2/5 '>
                <label
                  htmlFor='dokumenNpwp'
                  className='cursor-pointer bg-red-500 hover:bg-red-600 text-white py-1 px-3 text-sm rounded'
                >
                  Ubah
                </label>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenNpwp'
                  name='dokumenNpwp'
                  type='file'
                  title=' '
                  ref={dokumenNpwpRef}
                  className='hidden'
                  aria-invalid={errorsDokumen.dokumenNpwp}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
              </div>
            </div>
            {chekValid && (
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errorsDokumen.dokumenNpwp}
              </div>
            )}
          </div>
        </div>
        <div className='w-full flex flex-row items-center '>
          <div className='w-2/5'>
            <label className='form-label  text-nowrap'>SPPKP</label>
          </div>
          <div className='w-3/5'>
            <div className='flex flex-row items-start justify-between'>
              <span className='w-3/5  text-gray-600 truncate'>
                {formDokumen?.dokumenSppkp?.name}
              </span>
              <div className='w-2/5 '>
                <label
                  htmlFor='dokumenSppkp'
                  className='cursor-pointer bg-red-500 hover:bg-red-600 text-white py-1 px-3 text-sm rounded'
                >
                  Ubah
                </label>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenSppkp'
                  name='dokumenSppkp'
                  type='file'
                  title=' '
                  ref={dokumenSppkpRef}
                  className='hidden'
                  aria-invalid={errorsDokumen.dokumenSppkp}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
              </div>
            </div>
            {chekValid && (
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errorsDokumen.dokumenSppkp}
              </div>
            )}
          </div>
        </div>

        <div className='w-full flex flex-row items-center '>
          <div className='w-2/5'>
            <label className='form-label  text-nowrap'>
              {' '}
              Akta Perubahan <span className=' opacity-60'>(Opsional)</span>
            </label>
          </div>
          <div className='w-3/5'>
            <div className='flex flex-row items-start justify-between'>
              <span className='w-3/5  text-gray-600 truncate'>
                {formDokumen?.dokumenAktaPerubahan?.name}
              </span>
              <div className='w-2/5 '>
                <label
                  htmlFor='dokumenAktaPerubahan'
                  className='cursor-pointer bg-red-500 hover:bg-red-600 text-white py-1 px-3 text-sm rounded'
                >
                  Ubah
                </label>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenAktaPerubahan'
                  name='dokumendokumenAktaPerubahanSppkp'
                  type='file'
                  title=' '
                  ref={dokumenAktaPerubahanRef}
                  className='hidden'
                  aria-invalid={errorsDokumen.dokumenAktaPerubahan}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
              </div>
            </div>
            {chekValid && (
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errorsDokumen.dokumenAktaPerubahan}
              </div>
            )}
          </div>
        </div>

        <div className='w-full flex flex-row items-center '>
          <div className='w-2/5'>
            <label className='form-label  text-nowrap'>
              KTP Dirut/Direktur <span className=' opacity-60'>(Opsional)</span>
            </label>
          </div>
          <div className='w-3/5'>
            <div className='flex flex-row items-start justify-between'>
              <span className='w-3/5  text-gray-600 truncate'>
                {formDokumen?.dokumenKtpDirut?.name}
              </span>
              <div className='w-2/5 '>
                <label
                  htmlFor='dokumenKtpDirut'
                  className='cursor-pointer bg-red-500 hover:bg-red-600 text-white py-1 px-3 text-sm rounded'
                >
                  Ubah
                </label>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenKtpDirut'
                  name='dokumenKtpDirut'
                  type='file'
                  title=' '
                  ref={dokumenKtpDirutRef}
                  className='hidden'
                  aria-invalid={errorsDokumen.dokumenKtpDirut}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
              </div>
            </div>
            {chekValid && (
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errorsDokumen.dokumenKtpDirut}
              </div>
            )}
          </div>
        </div>

        <div className='w-full flex flex-row items-center '>
          <div className='w-2/5'>
            <label className='form-label  text-nowrap'>
              Akta Pendirian <span className=' opacity-60'>(Opsional)</span>
            </label>
          </div>
          <div className='w-3/5'>
            <div className='flex flex-row items-start justify-between'>
              <span className='w-3/5  text-gray-600 truncate'>
                {formDokumen?.dokumenAktaPendirian?.name}
              </span>
              <div className='w-2/5 '>
                <label
                  htmlFor='dokumenAktaPendirian'
                  className='cursor-pointer bg-red-500 hover:bg-red-600 text-white py-1 px-3 text-sm rounded'
                >
                  Ubah
                </label>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenAktaPendirian'
                  name='dokumenAktaPendirian'
                  type='file'
                  title=' '
                  ref={dokumenAktaPendirianRef}
                  className='hidden'
                  aria-invalid={errorsDokumen.dokumenAktaPendirian}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
              </div>
            </div>
            {chekValid && (
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errorsDokumen.dokumenAktaPendirian}
              </div>
            )}
          </div>
        </div>

        <div className='w-full flex flex-row items-center '>
          <div className='w-2/5'>
            <label className='form-label  text-nowrap'>
              Laporan Keuangan
              <span className=' opacity-60'>(Opsional)</span>
            </label>
          </div>
          <div className='w-3/5'>
            <div className='flex flex-row items-start justify-between'>
              <span className='w-3/5  text-gray-600 truncate'>
                {formDokumen?.dokumenLaporanKeuangan?.name}
              </span>
              <div className='w-2/5 '>
                <label
                  htmlFor='dokumenLaporanKeuangan'
                  className='cursor-pointer bg-red-500 hover:bg-red-600 text-white py-1 px-3 text-sm rounded'
                >
                  Ubah
                </label>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenLaporanKeuangan'
                  name='dokumenLaporanKeuangan'
                  type='file'
                  title=' '
                  ref={dokumenLaporanKeuanganRef}
                  className='hidden'
                  aria-invalid={errorsDokumen.dokumenLaporanKeuangan}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
              </div>
            </div>
            {chekValid && (
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errorsDokumen.dokumenLaporanKeuangan}
              </div>
            )}
          </div>
        </div>

        <div className='w-full flex flex-row items-center '>
          <div className='w-2/5'>
            <label className='form-label  text-nowrap'>
              Foto Kantor (Tampak Depan)
            </label>
          </div>
          <div className='w-3/5'>
            <div className='flex flex-row items-start justify-between'>
              <span className='w-3/5  text-gray-600 truncate'>
                {formDokumen?.dokumenFotoKantor?.name}
              </span>
              <div className='w-2/5 '>
                <label
                  htmlFor='dokumenFotoKantor'
                  className='cursor-pointer bg-red-500 hover:bg-red-600 text-white py-1 px-3 text-sm rounded'
                >
                  Ubah
                </label>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenFotoKantor'
                  name='dokumenFotoKantor'
                  type='file'
                  title=' '
                  ref={dokumenFotoKantorRef}
                  className='hidden'
                  aria-invalid={errorsDokumen.dokumenFotoKantor}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
              </div>
            </div>
            {chekValid && (
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errorsDokumen.dokumenFotoKantor}
              </div>
            )}
          </div>
        </div>

        <div className='w-full flex flex-row items-center '>
          <div className='w-2/5'>
            <label className='form-label  text-nowrap'>Tempat Bekerja</label>
          </div>
          <div className='w-3/5'>
            <div className='flex flex-row items-start justify-between'>
              <span className='w-3/5  text-gray-600 truncate'>
                {formDokumen?.dokumenTempatBekerja?.name}
              </span>
              <div className='w-2/5 '>
                <label
                  htmlFor='dokumenTempatBekerja'
                  className='cursor-pointer bg-red-500 hover:bg-red-600 text-white py-1 px-3 text-sm rounded'
                >
                  Ubah
                </label>
                <input
                  // value={formDokumen?.dokumenNib?.name}
                  id='dokumenTempatBekerja'
                  name='dokumenTempatBekerja'
                  type='file'
                  title=' '
                  ref={dokumenTempatBekerjaRef}
                  className='hidden'
                  aria-invalid={errorsDokumen.dokumenTempatBekerja}
                  onChange={handleInputChange}
                  accept='.pdf,.png,.jpg,.jpeg'
                />
              </div>
              <div
                onClick={() => setIsExample(!isExample)}
                className='rounded text-white p-2 flex flex-row bg-red-500 hover:cursor-pointer hover:bg-red-400'
              >
                <EyeIcon className={`w-4 ${isDesktop && 'mr-2'}`} />
                {isDesktop && (
                  <p className='font-light text-xs'>Lihat Contoh</p>
                )}
              </div>
              <Image
                src={`data:image/png;base64, ${formDokumen.dokumenNib.base64}`}
                alt='Contoh SPPKP'
                className='w-full h-full '
                width={800}
                height={800}
                quality={85}
              />
            </div>
            {chekValid && (
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errorsDokumen.dokumenTempatBekerja}
              </div>
            )}
          </div>
        </div>
      </form>
    </>
  );
};

export default KonfirmasiDokumen;
