import { yupResolver } from '@hookform/resolvers/yup'
import React, { useEffect, useState } from 'react' 
import { useForm } from 'react-hook-form'
import * as Yup from 'yup'
import Manifest from '@/lib/treckingAwb/component/Manifest'
import { trackingOrder } from '../api/trackingOrder'
import { useQuery } from 'react-query'
import { Spinner } from '@chakra-ui/react';
import { Search } from 'lucide-react';
import odooApi from '@/core/api/odooApi'

const TrackingOrder = () => {
    const [idAWB, setIdAWB] = useState(null)
    const [inputQuery, setInputQuery] = useState(null)
    const [buttonClick, setButtonClick] = useState(false)
    const [apiError, setApiError] = useState(null) // State to store API error message
    
    const closePopup = () => {
        setIdAWB(null)
        setButtonClick(false)
        setInputQuery(null)
        setApiError(null) // Reset error message on close
    }
    
    const {
        register,
        handleSubmit,
        formState: { errors },
        control,
        reset
    } = useForm({
        resolver: yupResolver(validationSchema),
        defaultValues
    })
    
    const query = {
        email: inputQuery?.email,
        so: inputQuery?.id
    }
    
    const { data: tracking, isLoading, isError, error } = useQuery(
        ['tracking', query],
        () => trackingOrder({ query: query }),
        {
            enabled: !!query.email && !!query.so,
            onSuccess: (data) => {
                if (buttonClick) {
                    if (data?.code === 403 || data?.code === 400 || data?.code === 404) {
                        setApiError(data?.description);
                    } else if (data?.pickings?.length > 0) {
                        setIdAWB(data.pickings[0]?.id);
                    } else {
                        setApiError('No pickings data available');
                    }
                    setButtonClick(false);
                    setInputQuery(null);
                }
            },
        }
    );

    const onSubmitHandler = async (values) => {
        setInputQuery(values)
        setButtonClick(true)
    }

    return (
        <div className='container mx-auto flex py-10 flex-col'>
            <h1 className='text-h-sm md:text-title-sm font-semibold mb-6'>Tracking Order</h1>
            <div className='flex justify-start items-start'>
                <span className='text-base w-full'>Untuk melacak pesanan Anda, masukkan ID Pesanan Anda di kotak di bawah ini dan tekan tombol "Lacak". ID ini diberikan kepada Anda pada tanda terima dan dalam email konfirmasi yang seharusnya Anda terima.</span>
            </div>
            <div>
                <form onSubmit={handleSubmit(onSubmitHandler)} className='flex mt-4 flex-row w-full '>
                    <div className='w-[90%] grid grid-cols-2 gap-4'>
                        <div className='flex flex-col '>
                            <label className='form-label mb-2'>ID Pesanan*</label>
                            <input
                                {...register('id')}
                                placeholder='dapat dilihat pada email konfirmasi anda'
                                type='text'
                                className='form-input mb-2'
                                aria-invalid={errors.id?.message}
                            />
                            <div className='text-caption-2 text-danger-500 mt-1'>{errors.id?.message}</div>
                        </div>
                        <div className='flex flex-col '>
                            <label className='form-label mb-2'>Email Penagihan*</label>
                            <input
                                {...register('email')}
                                placeholder='Email yang anda gunakan saat pembayaran'
                                type='text'
                                className='form-input'
                                aria-invalid={errors.email?.message}
                            />
                            <div className='text-caption-2 text-danger-500 mt-1'>{errors.email?.message}</div>
                        </div>
                    </div>
                    <div className={` ${errors.id?.message ? 'mt-2' : 'mt-5'} flex items-center ml-4`}>
                        <button
                            type='submit'
                            className='bg-red-600 border border-red-600 rounded-md text-sm text-white w-24 h-11 mb-1 content-center flex flex-row justify-center items-center'
                        >
                            {isLoading && <Spinner size='xs' className='mr-2'/>}
                            {!isLoading && <Search size={16} strokeWidth={1} className='mr-2'/>} 
                            <p>Lacak</p>
                        </button>
                    </div>
                </form>
                {/* Display the API error message */}
                {apiError && <div className='text-danger-500 mt-4'>{apiError}</div>}
                <Manifest idAWB={idAWB} closePopup={closePopup} />
            </div>
        </div>
    )
}

const validationSchema = Yup.object().shape({
    email: Yup.string().email('Format harus seperti contoh@email.com').required('Harus di-isi'),
    id: Yup.string().required('Harus di-isi'),
})

const defaultValues = {
    email: '',
    id: ''
}

export default TrackingOrder
