import Input from '@/components/Input'
import Select from '@/components/Select'
import Button from '@/components/Button'
import { TickCircle } from 'iconsax-react'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { FC, useEffect, useState } from 'react'
import { AddressData, CreateAddressType, UpdateAddressType } from '../types/Types'
import { useGetDomains } from '../../domain/hooks/useDomainData'
import { useCreateAddress, useUpdateAddress } from '../hooks/useAddressData'
import { useGetSpace } from '../../domain/hooks/useDomainData'
import { useGetTemplates } from '../../personality/hooks/usePersonalityData'
import { toast } from '@/components/Toast'
import { ErrorType } from '@/helpers/types'
import ForwarderManager from './ForwarderManager'

interface AddressFormProps {
    selectedAddress: AddressData | null
    isEditMode: boolean
    onCancel: () => void
    onSuccess: () => void
}

const AddressForm: FC<AddressFormProps> = ({ selectedAddress, isEditMode, onCancel, onSuccess }) => {
    const { t } = useTranslation()
    const { data: templates } = useGetTemplates()
    const { data: domain } = useGetDomains()
    const { data: spaceData } = useGetSpace()
    const { mutate: createAddress, isPending } = useCreateAddress()
    const { mutate: updateAddress, isPending: isUpdating } = useUpdateAddress()
    const [forwarders, setForwarders] = useState<string[]>([])

    type FormData = CreateAddressType & { password?: string; quotaMB?: number }

    const { register, handleSubmit, formState: { errors }, setValue, reset, setError, clearErrors
    } = useForm<FormData>({
        defaultValues: {
            domainId: domain?.data?.domain?.id,
        }
    })

    const validateForm = (params: FormData): boolean => {
        clearErrors()
        let isValid = true

        if (!params.title) {
            setError('title', { message: t('errors.required') })
            isValid = false
        }

        if (!params.username) {
            setError('username', { message: t('errors.required') })
            isValid = false
        }

        if (!isEditMode && !params.password) {
            setError('password', { message: t('errors.required') })
            isValid = false
        }

        if (!params.domainId) {
            setError('domainId', { message: t('errors.required') })
            isValid = false
        }

        // اعتبارسنجی quota
        if (params.quotaMB) {
            const quotaInBytes = params.quotaMB * 1024 * 1024
            const remainingSpace = spaceData?.data?.quota?.totalInGB * 1024 * 1024 * 1024 - spaceData?.data?.quota?.usedInGB * 1024 * 1024 * 1024

            if (quotaInBytes > remainingSpace) {
                setError('quotaMB', { message: 'فضای وارد شده بیش از فضای باقی‌مانده است' })
                isValid = false
            }
        }

        return isValid
    }

    const onSubmit = (params: FormData) => {
        if (!validateForm(params)) {
            return
        }

        if (isEditMode && selectedAddress) {
            const updateParams: UpdateAddressType = {
                title: params.title,
                password: params.password || undefined,
                quota: params.quotaMB ? params.quotaMB * 1024 * 1024 : undefined,
                forwarders: forwarders,
                templateId: params.templateId ? params.templateId : undefined,
            }


            updateAddress({ id: selectedAddress.id, params: updateParams }, {
                onSuccess: (data) => {
                    toast(data?.data?.message || 'آپدیت با موفقیت انجام شد', 'success')
                    onSuccess()
                },
                onError: (error: ErrorType) => {
                    toast(error.response?.data?.error?.message[0] || 'خطا در آپدیت', 'error')
                }
            })
        } else {
            const createParams: CreateAddressType = {
                ...params,
                quota: params.quotaMB ? params.quotaMB * 1024 * 1024 : undefined,
                forwarders: forwarders,
            }
            createAddress(createParams, {
                onSuccess: (data) => {
                    toast(data?.data?.message, 'success')
                    reset()
                    setForwarders([])
                    onSuccess()
                },
                onError: (error: ErrorType) => {
                    toast(error.response?.data?.error?.message[0], 'error')
                }
            })
        }
    }

    useEffect(() => {
        if (domain?.data?.domain?.id && !isEditMode) {
            setValue('domainId', domain?.data?.domain?.id)
            setValue('templateId', domain?.data?.template)
        }
    }, [domain, isEditMode, setValue])

    useEffect(() => {
        if (selectedAddress && isEditMode) {
            reset({
                title: selectedAddress.title,
                username: selectedAddress.displayName,
                password: '',
                domainId: selectedAddress.domain.id,
                quotaMB: selectedAddress.emailQuota ? Math.round(selectedAddress.emailQuota / (1024 * 1024)) : undefined,
                templateId: selectedAddress.template || '',
            })
            setForwarders(selectedAddress.forwarders || [])
        } else if (!isEditMode) {
            reset({
                title: '',
                username: '',
                password: '',
                domainId: domain?.data?.domain?.id,
                quotaMB: undefined,
                templateId: domain?.data?.template || '',
            })
            setForwarders([])
        }
    }, [selectedAddress, isEditMode, reset, domain, templates])

    return (
        <div className='xl:w-[350px] w-full bg-white rounded-4xl p-8'>
            <div className='flex justify-between items-center'>
                <div>
                    {isEditMode ? 'ویرایش آدرس' : t('setting.add_address')}
                </div>
                {isEditMode && (
                    <Button
                        variant='secondary'
                        onClick={onCancel}
                        className='px-4 w-fit text-xs'
                    >
                        انصراف
                    </Button>
                )}
            </div>

            <div className='mt-6'>
                <Input
                    label={t('setting.domain1')}
                    value={domain?.data?.domain?.name}
                    readOnly
                />
            </div>

            <div className='mt-6'>
                <Input
                    label={t('setting.title1')}
                    {...register('title')}
                    error_text={errors.title?.message as string}
                />
            </div>

            <div className='mt-6'>
                <Select
                    placeholder='انتخاب قالب'
                    label={'قالب'}
                    items={
                        templates?.data?.templates
                            ? templates.data.templates.map((template) => ({
                                key: template.id,
                                value: template.id,
                                label: template.name
                            }))
                            : []
                    }
                    {...register('templateId')}
                />
            </div>

            <div className='mt-6 relative'>
                <Input
                    label={t('setting.username')}
                    className='text-left'
                    {...register('username')}
                    error_text={errors.username?.message as string}
                    readOnly={isEditMode}
                />
                <div className='absolute flex items-center dltr text-xs z-10 right-[1px] top-[29px] rounded-r-2.5 h-[38px] bg-[#EBEEF5] px-3'>
                    @ {domain?.data?.domain?.name}
                </div>
            </div>

            <div className='mt-6'>
                <Input
                    label='حجم ایمیل (مگابایت)'
                    type='number'
                    {...register('quotaMB', { valueAsNumber: true })}
                    error_text={errors.quotaMB?.message as string}
                    placeholder='حجم ایمیل را به مگابایت وارد کنید'
                />
                <div className='text-xs text-gray-500 mt-1'>
                    فضای باقی‌مانده: {spaceData?.data?.quota ? Math.round((spaceData.data.quota.totalInGB - spaceData.data.quota.usedInGB) * 1024) : 0} مگابایت
                </div>
            </div>

            <div className='mt-6'>
                <ForwarderManager
                    forwarders={forwarders}
                    onChange={setForwarders}
                />
            </div>

            <div className='mt-6'>
                <Input
                    label={isEditMode ? 'رمز عبور جدید' : t('setting.password')}
                    type='password'
                    {...register('password')}
                    error_text={errors.password?.message as string}
                    placeholder={isEditMode ? 'برای تغییر رمز عبور وارد کنید' : ''}
                />
            </div>

            {!isEditMode && (
                <div className='mt-2 text-xs'>
                    <div>رمز عبور می‌بایست:</div>
                    <ul className='list-disc pr-3 mt-1 flex flex-col gap-1'>
                        <li>حداقل ۸ کاراکتر باشد</li>
                        <li>ترکیبی از حروف کوچک و بزرگ باشد</li>
                        <li>شامل اعداد باشد</li>
                        <li>شامل کاراکتر های خاص (نماد ها) باشد</li>
                    </ul>
                </div>
            )}



            <div className='mt-9 flex justify-end'>
                <Button
                    className='w-fit px-20'
                    onClick={handleSubmit(onSubmit)}
                    loading={isPending || isUpdating}
                >
                    <div className='flex gap-2'>
                        <TickCircle size={20} color='white' />
                        <div>
                            {isEditMode ? 'آپدیت' : t('setting.create')}
                        </div>
                    </div>
                </Button>
            </div>
        </div>
    )
}

export default AddressForm 