import Button from '@/components/Button'
import DefaulModal from '@/components/DefaulModal'
import Input from '@/components/Input'
import { useState, type FC } from 'react'
import { useDirectLogin } from '../hooks/useAuthData'
import { toast } from '@/components/Toast'
import { extractErrorMessage } from '@/helpers/utils'
import { setRefreshToken, setToken } from '@/config/func'

const DirectLogin: FC = () => {

    const [showModal, setShowModal] = useState<boolean>(false)
    const [subscriptionId, setSubscriptionId] = useState<string>('e6375048-4abc-4864-9614-198494631cae')
    const directLogin = useDirectLogin()

    const handleSubmit = () => {
        directLogin.mutate({ subscriptionId: subscriptionId }, {
            onSuccess: (data) => {
                setToken(data?.data?.tokens?.accessToken?.token)
                setRefreshToken(data?.data?.tokens?.refreshToken?.token)
                toast('با موفقیت لاگین شدید', 'success')
                window.location.reload()
            },
            onError: (error) => {
                toast(extractErrorMessage(error), 'error')
            }
        })
    }

    return (
        <div>
            <Button
                onClick={() => setShowModal(true)}
                className='w-fit px-4'
            >
                لاگین
            </Button>

            <DefaulModal
                open={showModal}
                close={() => setShowModal(false)}
                title_header='لاگین مستقیم'
                isHeader
            >
                <div className='mt-4'>
                    <Input
                        label='شماره اشتراک'
                        value={subscriptionId}
                        onChange={(e) => setSubscriptionId(e.target.value)}
                    />
                </div>

                <div className='mt-5'>
                    <Button disabled={directLogin.isPending} onClick={handleSubmit} className='w-full'>
                        لاگین
                    </Button>
                </div>

            </DefaulModal>
        </div>
    )
}

export default DirectLogin