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, 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;
}

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

const Form: React.FC<FormProps> = ({ type, required }) => {
  const {
    form,
    isCheckedTNC,
    isValidCaptcha,
    errors,
    updateForm,
    validate,
  } = useRegisterStore()

  const { control, watch, setValue } = useForm();
  const [selectedCategory, setSelectedCategory] = useState<string>('');

  const [industries, setIndustries] = useState<Industry[]>([]);
  const [companyTypes, setCompanyTypes] = useState([])
  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 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 selectedIndustry = watch('industry');

  useEffect(() => {
    const selected = industries.find(industry => industry.value === selectedIndustry);
    if (selected) {
      setSelectedCategory(selected.category);
    }
  }, [selectedIndustry, industries]);


  const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    updateForm(name, value)
    validate()
  }

  const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
    let fileBase64 = ''
    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)
      }
      updateForm("document", fileBase64);  // Menyimpan file ke dalam form state
      validate();
    }
  }

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

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

    const response = await mutation.mutateAsync(form)

    if (response?.register === true) {
      const urlParams = new URLSearchParams({
        activation: 'otp',
        email: form.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'>Email Bisnis</label>

        <input
          type='text'
          id='email'
          name='email'
          className='form-input mt-3'
          placeholder='example@email.com'
          value={form.email}
          onChange={handleInputChange}
          autoComplete="username"
          aria-invalid={!!errors.email}
        />

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

      <div>
        <label htmlFor="company">
          Nama Bisnis <span className='text-gray_r-11'>(opsional)</span>
        </label>
        <div className="flex justify-between items-center gap-2 h-12">
            <div className='w-4/5 pr-1'>
                <Controller
                  name='companyType'
                  control={control}
                  render={(props) => <HookFormSelect {...props} options={companyTypes} placeholder="Badan Usaha"/>}
                />
            </div>
            <input
                type="text"
                name="company"
                id="company"
                className="form-input h-full w-[120%]"
                placeholder="Nama Perusahaan"
                autoCapitalize="true"
                value={form.company}
                onChange={handleInputChange}
              />
            </div>
      </div>

      <div className="">
        <label htmlFor="company">
          Klasifikasi Jenis Usaha <span className='text-gray_r-11'>(opsional)</span>
        </label>
              <Controller
                name='industry'
                control={control}
                render={(props) => <HookFormSelect {...props} options={industries} placeholder={'Select industry'}/>}
              />
          <span className='text-gray_r-11 text-xs'>Kategori : {selectedCategory}</span>
      </div>

      <div>
        <label htmlFor='name'>Nama Wajib Pajak</label>

        <input
          type='text'
          id='name'
          name='name'
          className='form-input mt-3'
          placeholder='Masukan nama lengkap anda'
          value={form.name}
          onChange={handleInputChange}
          aria-invalid={!!errors.name}
        />

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

      <div>
        <label htmlFor='phone'>Nomor NPWP</label>

        <input
          type='tel'
          id='phone'
          name='phone'
          className='form-input mt-3'
          placeholder='08xxxxxxxx'
          value={form.phone}
          onChange={handleInputChange}
          aria-invalid={!!errors.phone}
        />

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

      <div>
        <label htmlFor="document">Dokumen NPWP (opsional)</label>

        <input
          type="file"
          id="document"
          name="document"
          className="form-input mt-3"
          onChange={handleFileChange}
          accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"  // Filter file types
        />

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

      <div>
        <label htmlFor="document">Dokumen SPPKP (opsional)</label>

        <input
          type="file"
          id="document"
          name="document"
          className="form-input mt-3"
          onChange={handleFileChange}
          accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"  // Filter file types
        />

        {/* {!!errors.document && <span className="form-msg-danger">{errors.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 Form