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';
const informasiPerusahaan = ({}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    control,
    reset,
    watch,
    setValue,
    values,
  } = useForm({
    resolver: yupResolver(validationSchema),
    defaultValues,
  });
  const [industries, setIndustries] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState('');
  const [states, setState] = useState([]);
  const [cities, setCities] = useState([]);

  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) => {
    console.log('values', values);
  };
  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-4'>
          <div className='flex flex-row  justify-between items-center'>
            <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.id?.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-center'>
            <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'>
                  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-center'>
            <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'>
              <input
                {...register('street')}
                placeholder='Masukkan alamat lengkap perusahaan'
                type='text'
                className='form-input'
              />
              <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>
        <button
          type='submit'
          className='bg-red-600 border mt-8 border-red-600 rounded-md text-sm text-white w-24 h-11 mb-1 content-center flex flex-row justify-center items-center'
        >
          <p>Selanjutnya</p>
        </button>
      </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'),
});

const defaultValues = {
  // email: '',
  name: '',
  industry_id: '',
  street: '',
  state: '',
  city: '',
  zip: '',
};

export default informasiPerusahaan;
