import { ChangeEvent, useEffect, useMemo, useState } from "react";
import { useMutation } from "react-query";
import { useRegisterStore } from "../stores/useRegisterStore";
import { RegisterProps } from "~/types/auth";
import { registerUser } from "~/services/auth";
import { useRouter } from "next/router";
import { UseToastOptions, color, useToast } from "@chakra-ui/react";
import Link from "next/link";
import getFileBase64 from '@/core/utils/getFileBase64'
import { Controller, useForm } from 'react-hook-form'
import HookFormSelect from '@/core/components/elements/Select/HookFormSelect'
import odooApi from "~/libs/odooApi";

interface FormProps {
  type: string;
  required: boolean;
  isPKP: boolean;
}

interface industry_id {
  label: string;
  value: string;
  category: string;
}

interface company_type_id {
  value: string;
  label: string;
}

const FormBisnis: React.FC<FormProps> = ({ type, required, isPKP }) => {
  const {
    formBisnis,
    isCheckedTNC,
    isValidCaptcha,
    errors,
    updateFormBisnis,
    validateFormBisnis,
  } = useRegisterStore()
  console.log("errors bisnis",errors)
  const { control, watch, setValue } = useForm();
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [selectedCompanyId, setSelectedCompanyId] = useState<string>('');

  const [industries, setIndustries] = useState<industry_id[]>([]);
  const [companyTypes, setCompanyTypes] = useState<company_type_id[]>([]);
  const isFormValid = useMemo(() => Object.keys(errors).length === 0, [errors]);

  const router = useRouter();
  const toast = useToast();

  useEffect(() => {
    const loadCompanyTypes = async () => {
      const dataCompanyTypes = await odooApi('GET', '/api/v1/partner/company_type');
      setCompanyTypes(dataCompanyTypes?.map((o: { id: any; name: any; }) => ({ value: o.id, label: o.name })));
    };
    loadCompanyTypes();
  }, []);

  useEffect(() => {
    const selectedCompanyType = companyTypes.find(company => company.value === watch('company_type_id'));
    if (selectedCompanyType) {
      updateFormBisnis("company_type_id", selectedCompanyType?.value);
      setSelectedCompanyId(selectedCompanyType?.label)
      validateFormBisnis();
    }
  }, [watch('company_type_id'), companyTypes]);

  useEffect(() => {
    const selectedIndustryType = industries.find(industry => industry.value === watch('industry_id'));
    if (selectedIndustryType) {
      updateFormBisnis("industry_id", selectedIndustryType?.value);
      setSelectedCategory(selectedIndustryType.label);
      validateFormBisnis();
    }
  }, [watch('industry_id'), industries]);

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

  const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    updateFormBisnis(name, value);
    updateFormBisnis('name','iman');
    updateFormBisnis('email','it@fixcomart.co.id');
    updateFormBisnis('password','Fixcomart378');
    updateFormBisnis('phone','082339129611');
    validateFormBisnis();
  };

  const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
    let fileBase64 = '';
    const { name} = event.target;
    const file = event.target.files?.[0];
    if (file) {
      if (typeof file !== 'undefined') {
        if (file.size > 5000000) {
          // toast.error('Maksimal ukuran file adalah 5MB')
          return;
        }
        fileBase64 = await getFileBase64(file);
      }
      updateFormBisnis(name, fileBase64);
      validateFormBisnis();
    }
  };

  const mutation = useMutation({
    mutationFn: (data: RegisterProps) => registerUser(data)
  });

  const handleSubmit = async (e: ChangeEvent<HTMLFormElement>) => {
    e.preventDefault();

    const response = await mutation.mutateAsync(formBisnis);

    if (response?.register === true) {
      const urlParams = new URLSearchParams({
        activation: 'otp',
        email: formBisnis.email,
        redirect: (router.query?.next || '/') as string
      });
      router.push(`${router.route}?${urlParams}`);
    }

    const toastProps: UseToastOptions = {
      duration: 5000,
      isClosable: true
    };

    switch (response?.reason) {
      case 'EMAIL_USED':
        toast({
          ...toastProps,
          title: 'Email sudah digunakan',
          status: 'warning'
        });
        break;
      case 'NOT_ACTIVE':
        const activationUrl = `${router.route}?activation=email`;
        toast({
          ...toastProps,
          title: 'Akun belum aktif',
          description: <>Akun sudah terdaftar namun belum aktif. <Link href={activationUrl} className="underline">Klik untuk aktivasi akun</Link></>,
          status: 'warning'
        });
        break;
    }
  };
  return (
    <form className="mt-6 grid grid-cols-1 gap-y-4" onSubmit={handleSubmit}>
      <div>
        <label htmlFor='email' className="font-bold">Email Bisnis {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}</label>

        <input
          type='text'
          id='email_partner'
          name='email_partner'
          placeholder='example@email.com'
          value={!required ? formBisnis.email_partner : ''}
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          onChange={handleInputChange}
          autoComplete="username"
          aria-invalid={!required && isPKP && !!errors.email_partner}

        />

        {!required && isPKP && !!errors.email_partner && <span className="form-msg-danger">{errors.email_partner}</span>}
      </div>

      <div>
        <label className="font-bold" htmlFor="company">
          Nama Bisnis 
        </label>
        <div className="flex justify-between items-start gap-2 h-12">
          <div className='w-4/5 pr-1'>
            <Controller
              name='company_type_id'
              control={control}
              render={(props) => <HookFormSelect {...props} options={companyTypes} disabled={required} placeholder="Badan Usaha"/>}
              />
              {!required &&  !!errors.company_type_id && <span className="form-msg-danger">{errors.company_type_id}</span>}
          </div>
          <div className="w-[120%]">
            <input
              type="text"
              name="business_name"
              id="business_name"
              className="form-input h-full "
              placeholder="Nama Perusahaan"
              autoCapitalize="true"
              value={formBisnis.business_name}
              aria-invalid={!!errors.business_name}
              onChange={handleInputChange}
              />

            { !!errors.business_name && <span className="form-msg-danger">{errors.business_name}</span>}
          </div>
        </div>
      </div>

      <div className="mt-8 sm:mt-8">
        <label className="font-bold" htmlFor="business_name">
          Klasifikasi Jenis Usaha
        </label>
        <Controller
          name='industry_id'
          control={control}
          render={(props) => <HookFormSelect {...props} options={industries} disabled={required} placeholder={'Select industry'}/>}
          />
          {selectedCategory && 
            <span className='text-gray_r-11 text-xs'>Kategori : {selectedCategory}</span>
          }
          {!required && !!errors.industry_id && <span className="form-msg-danger">{errors.industry_id}</span>}
      </div>

      <div>
        <label htmlFor='nama_wajib_pajak' className="font-bold">Nama Wajib Pajak {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}</label>

        <input
          type='text'
          id='nama_wajib_pajak'
          name='nama_wajib_pajak'
          placeholder='Masukan nama lengkap anda'
          value={!required?  formBisnis.nama_wajib_pajak : ''}
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          onChange={handleInputChange}
          aria-invalid={isPKP && !required && !!errors.nama_wajib_pajak}
        />

        {isPKP && !required && !!errors.nama_wajib_pajak && <span className="form-msg-danger">{errors.nama_wajib_pajak}</span>}
      </div>

      <div>
        <label htmlFor='npwp' className="font-bold">Nomor NPWP {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}</label>

        <input
          type='tel'
          id='npwp'
          name='npwp'
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          placeholder='000.000.000.0-000.000'
          value={!required ? formBisnis.npwp : ''}
          onChange={handleInputChange}
          aria-invalid={isPKP && !required && !!errors.npwp}
        />

        {isPKP && !required && !!errors.npwp && <span className="form-msg-danger">{errors.npwp}</span>}
      </div>

      <div>
        <label htmlFor="npwp_document" className="font-bold">Dokumen NPWP {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}</label>

        <input
          type="file"
          id="npwp_document"
          name="npwp_document"
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          onChange={handleFileChange}
          accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"  // Filter file types
        />

        {isPKP && !required && !!errors.npwp_document && <span className="form-msg-danger">{errors.npwp_document}</span>}
      </div>

      <div>
        <label htmlFor="sppkp_document" className="font-bold">Dokumen SPPKP {!isPKP && !required && <span className='font-normal text-gray_r-11'>(opsional)</span>}</label>

        <input
          type="file"
          id="sppkp_document"
          name="sppkp_document"
          className={`form-input mt-3 ${required ? 'cursor-no-drop' : ''}`}
          disabled={required}
          contentEditable={required}
          readOnly={required}
          onChange={handleFileChange}
          accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"  // Filter file types
        />

        {isPKP && !required && !!errors.sppkp_document && <span className="form-msg-danger">{errors.sppkp_document}</span>}
      </div>

      {/* <button
        type="submit"
        className="btn-yellow w-full mt-2"
        disabled={!isFormValid || !isCheckedTNC || mutation.isLoading || !isValidCaptcha}
      >
        {mutation.isLoading ? 'Loading...' : 'Daftar'}
      </button> */}
    </form>
  )
}

export default FormBisnis;
