import React, { useState, useEffect, useMemo, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { usePengajuanTempoStoreSupplier } from '../../../../src-migrate/modules/register/stores/usePengajuanTempoStore';
import * as Yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { PlusCircleIcon } from '@heroicons/react/24/outline';

const initialData = [];
const Referensi = ({ chekValid, buttonSubmitClick }) => {
  const {
    register,
    formState: { errors },
    handleSubmit,
    watch,
    setValue,
    control,
  } = useForm({
    resolver: yupResolver(validationSchema),
    defaultValues,
  });
  const { formSupplier, updateFormSupplier } = usePengajuanTempoStoreSupplier();
  const [formData, setFormData] = useState([
    {
      supplier: '',
      pic: '',
      telepon: '',
      durasiTempo: '',
      creditLimit: '',
    },
  ]);

  const [buttonSubmit, setButtonSubmit] = useState(false);
  const [supplierData, setSupplierData] = useState(initialData);
  const [newSupplier, setNewSupplier] = useState({
    supplier: '',
    pic: '',
    telepon: '',
    durasiTempo: '',
    creditLimit: '',
  });
  const onChangeInput = (e, index) => {
    const { name, value } = e.target;

    let formattedValue = value;

    if (name === 'durasiTempo') {
      formattedValue = value.replace(/\s*Hari\s*/g, '');
    } else if (name === 'creditLimit') {
      formattedValue = value.replace(/^Rp\s*/, '');
    }

    const editData = supplierData.map((item, i) =>
      i === index ? { ...item, [name]: formattedValue } : item
    );

    setSupplierData(editData);
  };

  const handleNewSupplierChange = (e) => {
    const { name, value } = e.target;

    let formattedValue = value;

    if (name === 'durasiTempo') {
      formattedValue = value.replace(/\s*Hari\s*/g, '');
    } else if (name === 'creditLimit') {
      formattedValue = value.replace(/^Rp\s*/, '');
    }

    const updatedSupplier = { ...newSupplier, [name]: formattedValue };
    setNewSupplier(updatedSupplier);

    // if (Object.values(updatedSupplier).every((val) => val.trim() !== '')) {
    //   setSupplierData((prevData) => {
    //     const newData = [...prevData, updatedSupplier];
    //     return newData;
    //   });

    //   setNewSupplier({
    //     supplier: '',
    //     pic: '',
    //     telepon: '',
    //     durasiTempo: '',
    //     creditLimit: '',
    //   });
    // }
  };

  const handleAddNewSupplier = () => {
    // Pastikan semua field sudah diisi sebelum menambahkan supplier baru
    if (Object.values(newSupplier).every((val) => val.trim() !== '')) {
      setSupplierData((prevData) => {
        const newData = [...prevData, newSupplier];
        return newData;
      });

      // Reset newSupplier setelah menambahkan
      setNewSupplier({
        supplier: '',
        pic: '',
        telepon: '',
        durasiTempo: '',
        creditLimit: '',
      });
    }
  };

  useEffect(() => {
    handleAddNewSupplier();
    updateFormSupplier(supplierData);
    setButtonSubmit(!buttonSubmit);
  }, [buttonSubmitClick]);
  const simpanData = () => {
    setButtonSubmit(!buttonSubmit);
    if (Object.values(newSupplier).every((val) => val.trim() !== '')) {
      setSupplierData((prevData) => {
        const newData = [...prevData, newSupplier];
        return newData;
      });

      // Reset newSupplier setelah menambahkan
      setNewSupplier({
        supplier: '',
        pic: '',
        telepon: '',
        durasiTempo: '',
        creditLimit: '',
      });
    }
  };
  const formatRupiah = (value) => {
    if (!value) return '';
    const numberString = value.replace(/[^0-9]/g, '');
    return numberString
      ? 'Rp ' + new Intl.NumberFormat('id-ID').format(numberString)
      : '';
  };
  const formatHari = (value) => {
    if (!value) return '';

    const numberString = value.replace(/[^0-9]/g, '');

    return numberString ? numberString.replace(/Hari/g, '') + ' Hari' : '';
  };
  // useEffect(() => {
  // setSupplierData((prevData) => {
  //   const newData = [...prevData, newSupplier];
  //   return newData;
  // });
  // updateFormSupplier(supplierData);
  // }, [buttonSubmitClick]);
  useEffect(() => {
    updateFormSupplier(supplierData);
  }, [buttonSubmit]);
  useEffect(() => {
    if (formSupplier) {
      setSupplierData(formSupplier);
    }
  }, [buttonSubmitClick]);
  return (
    <>
      <div className='flex justify-start'>
        <h1 className='font-bold'>
          Referensi Supplier / Rekanan Bisnis Perusahaan{' '}
          <span className=' opacity-60 text-2xl'>(Opsional)</span>
        </h1>
      </div>
      <form className='flex mt-4 flex-col w-full '>
        <table className='border' border='1' cellPadding='10'>
          <thead>
            <tr className='border '>
              <th className='text-left px-5 py-2'>Nama Supplier / Rekanan</th>
              <th className='text-left px-5 py-2'>PIC</th>
              <th className='text-left px-5 py-2'>Telepon</th>
              <th className='text-left px-5 py-2'>Durasi Tempo</th>
              <th className='text-left px-5 py-2'>Credit Limit</th>
            </tr>
          </thead>
          <tbody>
            {supplierData.map((supplier, index) => (
              <tr key={index}>
                <td>
                  <input
                    name='supplier'
                    value={supplier.supplier}
                    type='text'
                    onChange={(e) => onChangeInput(e, index)}
                    className='form-input border px-4 py-2'
                    placeholder='Type Supplier'
                  />
                </td>
                <td>
                  <input
                    name='pic'
                    value={supplier.pic}
                    type='text'
                    className='form-input border px-4 py-2'
                    onChange={(e) => onChangeInput(e, index)}
                    placeholder='Type PIC'
                  />
                </td>
                <td>
                  <input
                    name='telepon'
                    type='text'
                    className='form-input border px-4 py-2'
                    value={supplier.telepon}
                    onChange={(e) => onChangeInput(e, index)}
                    placeholder='Type Telepon'
                  />
                </td>
                <td>
                  <input
                    name='durasiTempo'
                    type='text'
                    className='form-input border px-4 py-2'
                    value={formatHari(supplier.durasiTempo)}
                    onChange={(e) => onChangeInput(e, index)}
                    placeholder='Type Durasi Tempo'
                  />
                </td>
                <td>
                  <input
                    name='creditLimit'
                    type='text'
                    value={formatRupiah(supplier.creditLimit)}
                    className='form-input border px-4 py-2'
                    onChange={(e) => onChangeInput(e, index)}
                    placeholder='Type Credit Limit'
                  />
                </td>
              </tr>
            ))}
            <tr>
              <td>
                <input
                  name='supplier'
                  value={newSupplier.supplier}
                  type='text'
                  className='form-input border px-4 py-2'
                  onChange={handleNewSupplierChange}
                  placeholder='Isi nama supplier anda'
                />
              </td>
              <td>
                <input
                  name='pic'
                  value={newSupplier.pic}
                  type='text'
                  className='form-input border px-4 py-2'
                  onChange={handleNewSupplierChange}
                  placeholder='Isi PIC supplier anda'
                />
              </td>
              <td>
                <input
                  name='telepon'
                  value={newSupplier.telepon}
                  type='text'
                  onChange={handleNewSupplierChange}
                  placeholder='Isi telepon supplier anda'
                  className='form-input border px-4 py-2'
                />
              </td>
              <td>
                <input
                  name='durasiTempo'
                  value={formatHari(newSupplier.durasiTempo)}
                  type='text'
                  onChange={handleNewSupplierChange}
                  className='form-input border px-4 py-2'
                  placeholder='Durasi jatuh tempo'
                />
              </td>
              <td>
                <input
                  name='creditLimit'
                  value={formatRupiah(newSupplier.creditLimit)}
                  type='text'
                  className='form-input border px-4 py-2'
                  onChange={handleNewSupplierChange}
                  placeholder='limit kredit'
                />
              </td>
            </tr>
          </tbody>
        </table>
      </form>
      <div className='flex items-start gap-4 mt-8'>
        <button
          onClick={handleAddNewSupplier}
          className='bg-gray-200 border border-gray-500 rounded-md text-sm text-gray-500 p-2 h-11 mb-1 content-center flex flex-row justify-center items-center'
        >
          {<PlusCircleIcon className='w-5 mr-2' />}
          {''} Tambah data baru
        </button>
        <button
          onClick={simpanData}
          className='bg-gray-200 border border-gray-500 rounded-md text-sm text-gray-500 p-2 h-11 mb-1 content-center flex flex-row justify-center items-center'
        >
          simpan data
        </button>
      </div>
      {/* <button className='mt-8' onClick={cetakData}>
        CETAK
      </button> */}
    </>
  );
};

const validationSchema = Yup.object().shape({
  supplier: Yup.string().required('Harus di-isi'),
  pic: Yup.string().required('Harus di-isi'),
  telepon: Yup.string().required('Harus di-isi'),
  durasiTempo: Yup.string().required('Harus di-isi'),
  creditLimit: Yup.string().required('Harus di-isi'),
});

const defaultValues = {
  supplier: '',
  pic: '',
  telepon: '',
  durasiTempo: '',
  creditLimit: '',
};
export default Referensi;
