import React, { useState, useEffect } from 'react';
import * as Yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { Controller, useForm } from 'react-hook-form';
import HookFormSelect from '@/core/components/elements/Select/HookFormSelect';
import odooApi from '~/libs/odooApi';
import stateApi from '@/lib/address/api/stateApi.js';
import cityApi from '@/lib/address/api/cityApi';
import { Radio, RadioGroup, Stack, Checkbox } from '@chakra-ui/react';
const informasiPerusahaan = ({}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    control,
    reset,
    watch,
    setValue,
    getValues,
    values,
  } = useForm({
    resolver: yupResolver(validationSchema),
    defaultValues,
  });
  const [industries, setIndustries] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState('');
  const [states, setState] = useState([]);
  const [cities, setCities] = useState([]);
  const [bersedia, setBersedia] = useState(true);
  const category_produk = [
    { id: 1, name: 'Pengaman, Kesehatan & Keamanan' },
    { id: 2, name: 'Perkakas Tangan, Listrik & Pneumatic' },
    { id: 3, name: 'Mesin Industrial' },
    { id: 4, name: 'Mesin Pertanian & Perkebunan' },
    { id: 5, name: 'Mesin Pembersih & Janitorial' },
    { id: 6, name: 'Cairan Berbahan Kimia' },
    { id: 7, name: 'Perlengkapan Pengukuran & Pengujian' },
    { id: 8, name: 'Peralatan Listrik & Elektronik' },
    { id: 9, name: 'Perlengkapan Logistik & Gudang' },
    { id: 10, name: 'Peralatan Kantor & Stationery' },
    { id: 11, name: 'Komponen & Aksesoris' },
    { id: 12, name: 'Peralatan Horeca & Food Service' },
  ];
  console.log('defaultValues', getValues());
  useEffect(() => {
    const loadState = async () => {
      let dataState = await stateApi();
      dataState = dataState.map((state) => ({
        value: state.id,
        label: state.name,
      }));
      setState(dataState);
    };
    loadState();
  }, []);

  const watchState = watch('state');
  useEffect(() => {
    setValue('city', '');
    if (watchState) {
      const loadCities = async () => {
        let dataCities = await cityApi({ stateId: watchState });
        dataCities = dataCities.map((city) => ({
          value: city.id,
          label: city.name,
        }));
        setCities(dataCities);
      };
      loadCities();
    }
  }, [watchState, setValue]);

  useEffect(() => {
    const loadIndustries = async () => {
      const dataIndustries = await odooApi('GET', '/api/v1/partner/industry');
      setIndustries(
        dataIndustries?.map((o) => ({
          value: o.id,
          label: o.name,
          category: o.category,
        }))
      );
    };
    loadIndustries();
  }, []);

  useEffect(() => {
    const selectedIndustryType = industries.find(
      (industry) => industry.value === watch('industry_id')
    );
    if (selectedIndustryType) {
      // updateForm('industry_id', `${selectedIndustryType?.value}`);
      setSelectedCategory(selectedIndustryType.category);
    }
  }, [watch('industry_id'), industries]);

  const onSubmitHandler = async (values) => {
    setValue('bersedia', `${bersedia}`);
    console.log('values', values);
  };

  const estimasiValue = watch('estimasi');
  const tempoLimitValue = watch('tempoLimit');

  // Memformat angka menjadi format rupiah
  const formatRupiah = (value) => {
    if (!value) return '';
    const numberString = value.replace(/[^0-9]/g, ''); // Menghapus karakter non-digit
    return numberString
      ? 'Rp ' + new Intl.NumberFormat('id-ID').format(numberString)
      : '';
  };

  // Memperbarui nilai input dengan format rupiah
  const handleChange = (e) => {
    const value = e.target.value;
    const formattedValue = formatRupiah(value);
    setValue('estimasi', formattedValue); // Mengupdate nilai di react-hook-form
  };
  const onChangeTempoDuration = (e) => {
    setValue('tempoDuration', `${e}`); // Mengupdate nilai di react-hook-form
  };

  const onChangeTempoLimit = (e) => {
    setValue('tempoLimit', `${e}`); // Mengupdate nilai di react-hook-form
  };
  const handleBersediaChange = () => {
    setBersedia(!bersedia);
    setValue('bersedia', `${bersedia}`);
  };
  const [selectedIds, setSelectedIds] = useState([]);

  const handleCheckboxChange = (id) => {
    setSelectedIds((prevSelected) =>
      prevSelected.includes(id)
        ? prevSelected.filter((selectedId) => selectedId !== id)
        : [...prevSelected, id]
    );
    setValue('categoryProduk', `${selectedIds}`);
  };

  const midIndex = Math.ceil(category_produk.length / 2);
  const firstColumn = category_produk.slice(0, midIndex);
  const secondColumn = category_produk.slice(midIndex);
  return (
    <>
      <div className='flex justify-start'>
        <h1>Informasi Perusahaan</h1>
      </div>
      <form
        onSubmit={handleSubmit(onSubmitHandler)}
        className='flex mt-4 flex-col w-full '
      >
        <div className='w-full grid grid-row-2 gap-5'>
          <div className='flex flex-row  justify-between items-start'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>
                Nama Perusahaan
              </label>
              <span className='text-xs opacity-60'>
                isi detail perusahaan sesuai dengan nama yang terdaftar{' '}
              </span>
            </div>
            <div className='w-3/5'>
              <input
                {...register('name')}
                placeholder='Masukkan nama perusahaan'
                type='text'
                className='form-input'
                aria-invalid={errors.name?.message}
              />
              <span className='text-xs opacity-60'>
                Format: PT. INDOTEKNIK DOTCOM GEMILANG
              </span>
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errors.name?.message}
              </div>
            </div>
          </div>
          <div className='flex flex-row  justify-between items-start'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>Industri</label>
              <span className='text-xs opacity-60'>
                isi detail perusahaan sesuai dengan nama yang terdaftar
              </span>
            </div>
            <div className='w-3/5'>
              <Controller
                {...register('industry_id')}
                control={control}
                render={(props) => (
                  <HookFormSelect
                    {...props}
                    options={industries}
                    placeholder={'Pilih industri bisnis anda'}
                  />
                )}
              />
              {selectedCategory && (
                <span className='text-gray_r-11 text-xs opacity-60'>
                  Kategori : {selectedCategory}
                </span>
              )}
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errors.industry_id?.message}
              </div>
            </div>
          </div>

          <div className='flex flex-row  justify-between items-start'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>
                Alamat Perusahaan
              </label>
              <span className='text-xs opacity-60'>
                alamat sesuai dengan alamat kantor pusat
              </span>
            </div>
            <div className='w-3/5 flex gap-3 flex-col'>
              <div>
                <input
                  {...register('street')}
                  placeholder='Masukkan alamat lengkap perusahaan'
                  type='text'
                  className='form-input'
                />
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.street?.message}
                </div>
              </div>
              <div className='sub-alamat flex flex-row w-full gap-3'>
                <div className='w-2/5'>
                  <Controller
                    name='state'
                    control={control}
                    render={(props) => (
                      <HookFormSelect
                        {...props}
                        options={states}
                        placeholder='Provinsi'
                      />
                    )}
                  />
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errors.state?.message}
                  </div>
                </div>
                <div className='w-1/3'>
                  <Controller
                    name='city'
                    control={control}
                    render={(props) => (
                      <HookFormSelect
                        {...props}
                        options={cities}
                        disabled={!watchState}
                        placeholder='Kota'
                      />
                    )}
                  />
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errors.city?.message}
                  </div>
                </div>
                <div className='w-1/3'>
                  <input
                    {...register('zip')}
                    placeholder='Kode Pos'
                    type='number'
                    className='form-input'
                  />
                  <div className='text-caption-2 text-danger-500 mt-1'>
                    {errors.zip?.message}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className='flex flex-row  justify-between items-start'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>
                No. Telfon Perusahaan
              </label>
              <span className='text-xs opacity-60'>
                isi no telfon perusahaan yang sesuai
              </span>
            </div>
            <div className='w-3/5'>
              <input
                {...register('mobile')}
                placeholder='Masukkan nomor telfon perusahaan'
                type='text'
                className='form-input'
                aria-invalid={errors.mobile?.message}
              />
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errors.mobile?.message}
              </div>
            </div>
          </div>

          <div className='flex flex-row  justify-between items-start'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>Data Bank</label>
              <span className='text-xs opacity-60'>
                Isi detail data bank perusahaan anda
              </span>
            </div>
            <div className='w-3/5 flex gap-3 flex-row'>
              <div>
                <input
                  {...register('bankName')}
                  placeholder='Nama bank'
                  type='text'
                  className='form-input'
                />
                <span className='text-xs opacity-60'>
                  Format: BCA, Mandiri, CIMB, BNI dll
                </span>
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.bankName?.message}
                </div>
              </div>
              <div>
                <input
                  {...register('accountName')}
                  placeholder='Nama Rekening'
                  type='text'
                  className='form-input'
                />
                <span className='text-xs opacity-60'>Format: John Doe</span>
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.accountName?.message}
                </div>
              </div>
              <div>
                <input
                  {...register('accountNumber')}
                  placeholder='Nomor Rekening Bank'
                  type='text'
                  className='form-input'
                />
                <span className='text-xs opacity-60'>Format: 01234567896</span>
                <div className='text-caption-2 text-danger-500 mt-1'>
                  {errors.accountNumber?.message}
                </div>
              </div>
            </div>
          </div>

          <div className='flex flex-row  justify-between items-start'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>
                Website <span className=' opacity-60'>(Opsional)</span>
              </label>
              <span className='text-xs opacity-60'>
                isi no telfon perusahaan yang sesuai
              </span>
            </div>
            <div className='w-3/5'>
              <input
                {...register('website')}
                placeholder='www.indoteknik.com'
                type='text'
                className='form-input'
              />
            </div>
          </div>

          <div className='flex flex-row  justify-between items-start'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>
                Estimasi Pembelian pertahun
              </label>
            </div>
            <div className='w-3/5'>
              <div className='relative'>
                <input
                  {...register('estimasi', {
                    setValueAs: (value) => value.replace(/^Rp\s*/, ''), // Menyimpan hanya angka
                  })}
                  placeholder='Isi estimasi pembelian produk pertahun'
                  type='text'
                  className='form-input' // padding untuk memberi ruang untuk "RP"
                  value={formatRupiah(estimasiValue)} // Menampilkan nilai terformat
                  onChange={handleChange} // Mengatur perubahan input
                />
              </div>
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errors.estimasi?.message}
              </div>
            </div>
          </div>

          <div className='flex flex-row  justify-between items-center'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>
                Durasi Tempo
              </label>
              <span className='text-xs opacity-60'>
                Pilih durasi tempo yang anda inginkan
              </span>
            </div>
            <div className='w-3/5 flex flex-row items-center'>
              <div className='w-1/5 '>
                <RadioGroup
                  onChange={onChangeTempoDuration}
                  // value={selectedValue}
                >
                  <Stack direction='column' className=''>
                    <Radio colorScheme='red' value='7'>
                      7 Hari
                    </Radio>
                    <Radio colorScheme='red' value='14' className=''>
                      14 Hari
                    </Radio>
                    <Radio colorScheme='red' value='30' className=''>
                      30 Hari
                    </Radio>
                  </Stack>
                </RadioGroup>
              </div>
              <div className='w-4/5 flex flex-row justify-between items-center '>
                <div>
                  <label className='form-label w-2/5 text-nowrap'>
                    Limit Tempo
                  </label>
                  <span className='text-xs opacity-60'>
                    Ajukan nilai limit yang anda mau
                  </span>
                </div>
                <div className='flex items-center'>
                  <RadioGroup
                    onChange={onChangeTempoLimit}
                    className='flex items-center justify-between'
                  >
                    <Stack direction='row' className=''>
                      {/* Kolom 1 */}
                      <Stack direction='column' spacing={2} className='mr-4'>
                        <Radio colorScheme='red' value='5.000.000'>
                          5.000.000
                        </Radio>
                        <Radio colorScheme='red' value='10.000.000'>
                          10.000.000
                        </Radio>
                        <Radio colorScheme='red' value='15.000.000'>
                          15.000.000
                        </Radio>
                        <Radio colorScheme='red' value='20.000.000'>
                          20.000.000
                        </Radio>
                      </Stack>

                      {/* Kolom 2 */}
                      <Stack direction='column' className='ml-8' spacing={2}>
                        <Radio colorScheme='red' value='25.000.000'>
                          25.000.000
                        </Radio>
                        <Radio colorScheme='red' value='30.000.000'>
                          30.000.000
                        </Radio>
                        <Radio colorScheme='red' value='35.000.000'>
                          35.000.000
                        </Radio>
                        <div className='flex flex-row'>
                          <Radio colorScheme='red' value='custom'></Radio>
                          <input
                            placeholder='Isi limit yang anda inginkan'
                            type='text'
                            className='border ml-2 p-1' // padding untuk memberi ruang untuk "RP"
                            value={formatRupiah(tempoLimitValue)} // Menampilkan nilai terformat
                            onChange={(e) => {
                              const value = e.target.value;
                              const formattedValue = formatRupiah(value);
                              setValue('tempoLimit', formattedValue); // Mengupdate nilai di react-hook-form
                            }}
                          />
                        </div>
                      </Stack>
                    </Stack>
                  </RadioGroup>
                </div>
              </div>
              {/* <input
                {...register('tempoDuration')}
                placeholder='Nomor Rekening Bank'
                type='text'
                className='form-input'
              /> */}
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errors.tempoDuration?.message}
              </div>
            </div>
          </div>

          <div className='text-red-500'>
            *Durasi dan limit dapat berbeda sesuaui dengan verifikasi oleh tim
            Indoteknik.com
          </div>

          <div className='flex flex-row  justify-between items-start'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>
                Apakah bersedia transaksi via website?
              </label>
              <span className='text-xs opacity-60'>
                Pilih produk bisa lebih dari 1
              </span>
            </div>
            <div className='w-3/5 flex justify-start'>
              <div className='flex gap-x-4'>
                <Checkbox
                  borderColor='gray.600'
                  colorScheme='red'
                  isChecked={bersedia}
                  onChange={handleBersediaChange}
                  value={true}
                  size='md'
                >
                  Saya bersedia
                </Checkbox>
                <Checkbox
                  borderColor='gray.600'
                  colorScheme='red'
                  isChecked={!bersedia}
                  onChange={handleBersediaChange}
                  value={false}
                  size='md'
                >
                  Tidak bersedia
                </Checkbox>
              </div>
              <div className='text-caption-2 text-danger-500 mt-1'>
                {errors.estimasi?.message}
              </div>
            </div>
          </div>

          <div className='flex flex-row  justify-between items-start'>
            <div>
              <label className='form-label w-2/5 text-nowrap'>
                Kategori Produk yang Digunakan
              </label>
              <span className='text-xs opacity-60'>
                Pilih produk bisa lebih dari 1
              </span>
            </div>
            <div className='w-3/5 flex flex-row justify-between'>
              <div className='flex flex-col gap-2'>
                {firstColumn.map((item) => (
                  <Checkbox
                    key={item.id}
                    onChange={() => handleCheckboxChange(item.id)}
                  >
                    {item.name}
                  </Checkbox>
                ))}
              </div>
              <div className='flex flex-col gap-2'>
                {secondColumn.map((item) => (
                  <Checkbox
                    key={item.id}
                    onChange={() => handleCheckboxChange(item.id)}
                  >
                    {item.name}
                  </Checkbox>
                ))}
              </div>
            </div>
          </div>
          <div className='flex 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>
            <button
              type='submit'
              className='bg-red-600 border border-red-600 rounded-md text-sm text-white w-28 h-11 mb-1 content-center flex flex-row justify-center items-center'
            >
              <p>Selanjutnya</p>
            </button>
          </div>
        </div>
      </form>
    </>
  );
};

const validationSchema = Yup.object().shape({
  // email: Yup.string()
  //   .email('Format harus seperti contoh@email.com')
  //   .required('Harus di-isi'),
  name: Yup.string().required('Harus di-isi'),
  industry_id: Yup.string().required('Harus di-pilih'),
  street: Yup.string().required('Harus di-isi'),
  zip: Yup.string().required('Harus di-isi'),
  state: Yup.string().required('Harus di-pilih'),
  city: Yup.string().required('Harus di-pilih'),
  mobile: Yup.string().required('Harus di-isi'),
  bankName: Yup.string().required('Harus di-isi'),
  accountName: Yup.string().required('Harus di-isi'),
  accountNumber: Yup.string().required('Harus di-isi'),
  estimasi: Yup.string().required('Harus di-isi'),
  tempoDuration: Yup.string().required('Harus di-isi'),
  bersedia: Yup.string().required('Harus di-pilih'),
});

const defaultValues = {
  // email: '',
  name: '',
  industry_id: '',
  street: '',
  state: '',
  city: '',
  zip: '',
  mobile: '',
  bankName: '',
  accountName: '',
  accountNumber: '',
  estimasi: '',
  tempoDuration: '',
  bersedia: '',
};

export default informasiPerusahaan;
