"use client";
import { useToken } from "@/hooks/use-token";
import axios from "axios";
import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useLanguage } from "@/store/language-context";
import { useToast } from "@/hooks/use-toast";

import {
    Dialog,
    DialogClose,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

import { BadgeCheck, Bomb, Loader, TriangleAlert, X, } from "lucide-react";
import logo from "@/assets/used-icons/IvoryLogo.svg";
import { useUserData } from "@/store/user-profile";

export default function ProductRegister(
    { product_id, title, isDialog = true }:
        { product_id: number, title: string, isDialog?: boolean }
) {
    const { URL } = useLanguage();
    const { t } = useTranslation();
    const { toast } = useToast();
    const { profile, loading } = useUserData() ?? {};

    const token = useToken();

    const [open, setOpen] = useState(false);

    const [noAuthInput, setNoAuthInput] = useState({
        email: '',
        firstName: '',
        secondName: '',
        companyTitle: "",
        jobTitle: "",
        phone: '',
        isLoading: false,
        error: []
    });

    const subscribeWithNoAuth = async (e) => {
        e.preventDefault();
        setNoAuthInput(prev => ({ ...prev, isLoading: true }));

        const requestBody = {
            ivory_product_id: product_id,
            email: noAuthInput.email,
            first_name: noAuthInput.firstName,
            last_name: noAuthInput.secondName,
            company_title: noAuthInput.companyTitle,
            job_title: noAuthInput.jobTitle,
            phone: noAuthInput.phone,
        };

        try {
            const response = await axios.post(`${URL}/ivory-products/store`, requestBody);

            if (response.status === 200) {
                setOpen(false);
                toast({
                    variant: "success",
                    title: (
                        <div className="flex items-center gap-2">
                            <BadgeCheck />
                            <span>
                                {t('custom.done-check')}
                            </span>
                        </div>
                    ),
                    description: t('custom.done-desc')
                });
            } else if (response.status === 404) {
                setOpen(false);
                toast({
                    variant: "warning",
                    title: (
                        <div className="flex items-center gap-2">
                            <TriangleAlert />
                            <span>
                                {t('custom.failed')}
                            </span>
                        </div>
                    ),
                    description: t('custom.old-check')
                });
            }
        } catch (error) {
            if (error?.status === 500) {
                setOpen(false);
                toast({
                    variant: "warning",
                    title: (
                        <div className="flex items-center gap-2">
                            <Bomb size={19} />
                            <span>
                                {t('custom.err-title')}
                            </span>
                        </div>
                    ),
                    description: t('custom.err')
                });
            }

            setNoAuthInput(prev => ({ ...prev, error: error?.response?.data?.data }))

        } finally {
            setNoAuthInput(prev => ({ ...prev, isLoading: false }));
        }
    };

    const subscribeWithAuth = useMutation({
        mutationKey: [title, product_id],
        mutationFn: async () => {

            if (!token) {
                setOpen(true);
                return;
            };

            const body = {
                ivory_product_id: product_id,
                email: profile?.email,
                first_name: profile?.first_name,
                last_name: profile?.last_name,
                company_title: profile?.company_title,
                job_title: profile?.job_title,
                phone: profile?.phone,
            };

            const response = await axios.post(`${URL}/ivory-products/store`, body, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                }
            });
            if (response.status !== 200) throw new Error(response.statusText);
            return response;
        },
        onSuccess: (response) => {
            if (response) {
                toast({
                    variant: 'success',
                    title: (
                        <div className="flex items-center gap-2">
                            <span>
                                <BadgeCheck />
                            </span>
                            <p>
                                {t('custom.done-check')}
                            </p>
                        </div>
                    ),
                    description: t('custom.done-desc')
                });
            }
        },
        onError: (err) => {
            if (err) {
                toast({
                    variant: "destructive",
                    title: (
                        <div className="flex items-center gap-2">
                            <span>
                                <Bomb />
                            </span>
                            <p>
                                {t('custom.failed')}
                            </p>
                        </div>
                    ),
                    description: t('custom.err')
                });
            }
            return;
        }
    });

    const reset = () => {
        setNoAuthInput({
            email: '',
            firstName: '',
            secondName: '',
            companyTitle: "",
            jobTitle: "",
            phone: '',
            isLoading: false,
            error: []
        });
    };

    return (
        <>
            {
                isDialog ?
                    <Dialog open={open} onOpenChange={setOpen}>
                        <DialogTrigger asChild className="w-full grid place-items-center">
                            <Button
                                variant='outline'
                                className='bg-primary-tw text-white w-40'
                                disabled={subscribeWithAuth.isPending}
                                onClick={() => subscribeWithAuth.mutate()}
                            >
                                {subscribeWithAuth.isPending ?
                                    <>
                                        {t('custom.checking')}
                                        <Loader className="animate-spin" />
                                    </>
                                    :
                                    t('leadership.order-now')
                                }
                            </Button>
                        </DialogTrigger>
                        <DialogContent className=" bg-white rounded-lg">
                            <DialogHeader>
                                <DialogTitle className="text-center">{title}</DialogTitle>
                                <DialogDescription />
                            </DialogHeader>
                            <form method="POST" onSubmit={subscribeWithNoAuth} className="text-start px-4 py-3 text-text-color space-y-2">
                                {/* first & second name */}
                                <div className="flex items-center gap-2 w-full max-lg:flex-col">
                                    <div className="w-full">
                                        <label htmlFor="firstName" className="flex items-center gap-2">
                                            <span>
                                                <img src={logo} alt="Ivory Logos" className="w-4" />
                                            </span>
                                            {t('contact.first-name')}
                                        </label>
                                        <Input
                                            type="text"
                                            id="firstName"
                                            name="firstName"
                                            value={noAuthInput.firstName || ''}
                                            placeholder={t('footer.enter-first-name')}
                                            onChange={(e) => setNoAuthInput(prev => ({
                                                ...prev,
                                                firstName: e.target.value
                                            }))}
                                            className={`focus:ring-secondary-tw text-common-text my-1 w-80`}
                                            required
                                        />
                                    </div>

                                    <div className="w-full">
                                        <label htmlFor="secName" className="flex items-center gap-2">
                                            <span>
                                                <img src={logo} alt="Ivory Logos" className="w-4" />
                                            </span>
                                            {t('contact.second-name')}
                                        </label>
                                        <Input
                                            type="text"
                                            id="secName"
                                            name="secName"
                                            value={noAuthInput.secondName || ''}
                                            placeholder={t('footer.enter-second-name')}
                                            onChange={(e) => setNoAuthInput(prev => ({
                                                ...prev,
                                                secondName: e.target.value
                                            }))}
                                            className={`focus:ring-secondary-tw text-common-text my-1 w-80`}
                                            required
                                        />
                                    </div>
                                </div>

                                <div className="flex items-start gap-2 w-full max-lg:flex-col">
                                    {/* email */}
                                    <div className="w-full">
                                        <label htmlFor="email" className="flex items-center gap-2">
                                            <span>
                                                <img src={logo} alt="Ivory Logos" className="w-4" />
                                            </span>
                                            {t('contact.email')}
                                        </label>
                                        <Input
                                            type="email"
                                            id="email"
                                            name="email"
                                            value={noAuthInput.email || ''}
                                            placeholder={t('footer.enter-email')}
                                            onChange={(e) => setNoAuthInput(prev => ({
                                                ...prev,
                                                email: e.target.value
                                            }))}
                                            className={`focus:ring-secondary-tw text-common-text my-1 w-80`}
                                            required
                                        />
                                        {noAuthInput?.error?.some(item => item.includes("البريد الالكتروني") || item.includes('mail'))
                                            && <p className="text-sm text-red-500">{t('footer.email-is-here')}</p>}
                                    </div>

                                    {/* phone number */}
                                    <div className="w-full">
                                        <label htmlFor="phone" className="flex items-center gap-2">
                                            <span>
                                                <img src={logo} alt="Ivory Logos" className="w-4" />
                                            </span>
                                            {t('contact.phone')}
                                        </label>
                                        <Input
                                            type="number"
                                            id="phone"
                                            name="phone"
                                            value={noAuthInput.phone || ''}
                                            placeholder={t('footer.enter-phone')}
                                            onChange={(e) => setNoAuthInput(prev => ({
                                                ...prev,
                                                phone: e.target.value
                                            }))}
                                            className={`focus:ring-secondary-tw text-common-text my-1 w-80`}
                                            required
                                        />
                                        {noAuthInput?.error?.some(item => item.includes("الهاتف") || item.includes('hone'))
                                            && <p className="text-sm text-red-500">{t('footer.phone-is-here')}</p>}
                                    </div>
                                </div>

                                <DialogFooter className="gap-2">
                                    <Button
                                        type="submit"
                                        disabled={noAuthInput.isLoading}
                                        className="w-full bg-primary-tw text-white rounded-md h-8 text-base">
                                        {noAuthInput.isLoading ?
                                            <>
                                                <Loader className="animate-spin" />
                                                {t('custom.checking')}
                                            </>
                                            :
                                            t('custom.check')}
                                    </Button>
                                    <DialogClose
                                        type="button"
                                        className="w-full bg-semi-gray text-white rounded-md p-1"
                                        disabled={noAuthInput.isLoading}
                                        onClick={reset}>
                                        {t('custom.reset')}
                                    </DialogClose>
                                </DialogFooter>
                            </form>
                        </DialogContent>
                    </Dialog>
                    :
                    <div className="w-full">
                        <div className="grid place-items-center w-full">
                            <Button
                                variant='outline'
                                type="button"
                                className='bg-primary-tw text-white w-40'
                                disabled={subscribeWithAuth.isPending}
                                // onClick={() => subscribeWithAuth.mutate()}
                                onClick={() => subscribeWithAuth.mutate()}
                            >
                                {subscribeWithAuth.isPending ?
                                    <>
                                        <Loader className="animate-spin" />
                                        {t('custom.checking')}
                                    </>
                                    :
                                    t('leadership.order-now')
                                }
                            </Button>
                        </div>
                        {
                            open &&
                            <section className="w-full grid place-items-center my-8">
                                <div className="w-11/12 md:w-9/12 border rounded-md p-4 relative">
                                    <Button type="button"
                                        className="absolute end-2 top-2 size-6 bg-primary-tw text-white"
                                        variant="outline"
                                        onClick={() => setOpen(false)}
                                    >
                                        <X />
                                    </Button>
                                    <h2 className="text-center font-semibold mb-4 text-xl text-secondary-tw">
                                        {`${t('custom.subs-in-service')} ${title}`}
                                    </h2>
                                    <form onSubmit={(e) => subscribeWithNoAuth(e)} className="px-4 py-3 w-full grid md:grid-cols-3 gap-4">
                                        {/* first name */}
                                        <div className="w-full">
                                            <Label htmlFor="firstName" className="flex items-center gap-2">
                                                <span>
                                                    <img src={logo} alt="Ivory Logos" className="w-4" />
                                                </span>
                                                {t('contact.first-name')}
                                            </Label>
                                            <Input
                                                type="text"
                                                id="firstName"
                                                name="firstName"
                                                value={noAuthInput.firstName || ''}
                                                placeholder={`${t('footer.enter')} ${t('contact.first-name')} ${t('footer.here')}`}
                                                onChange={(e) => setNoAuthInput(prev => ({
                                                    ...prev,
                                                    firstName: e.target.value
                                                }))}
                                                className="!w-full my-2 text-black placeholder:py-2 bg-[#F5F5F5] focus:ring-secondary-tw"
                                                required
                                            />
                                        </div>
                                        {/* second name */}
                                        <div className="w-full">
                                            <Label htmlFor="secName" className="flex items-center gap-2">
                                                <span>
                                                    <img src={logo} alt="Ivory Logos" className="w-4" />
                                                </span>
                                                {t('contact.second-name')}
                                            </Label>
                                            <Input
                                                type="text"
                                                id="secName"
                                                name="secName"
                                                value={noAuthInput.secondName || ''}
                                                placeholder={`${t('footer.enter')} ${t('contact.second-name')} ${t('footer.here')}`}
                                                onChange={(e) => setNoAuthInput(prev => ({
                                                    ...prev,
                                                    secondName: e.target.value
                                                }))}
                                                className="!w-full my-2 text-black placeholder:py-2 bg-[#F5F5F5] focus:ring-secondary-tw"
                                                required
                                            />
                                        </div>

                                        {/* email */}
                                        <div className="w-full">
                                            <Label htmlFor="email" className="flex items-center gap-2">
                                                <span>
                                                    <img src={logo} alt="Ivory Logos" className="w-4" />
                                                </span>
                                                {t('contact.email')}
                                            </Label>
                                            <Input
                                                type="email"
                                                id="email"
                                                name="email"
                                                value={noAuthInput.email || ''}
                                                placeholder={`${t('footer.enter')} ${t('contact.email')} ${t('footer.here')}`}
                                                onChange={(e) => setNoAuthInput(prev => ({
                                                    ...prev,
                                                    email: e.target.value
                                                }))}
                                                className="w-full my-2 text-black placeholder:py-2 bg-[#F5F5F5] focus:ring-secondary-tw"
                                                required
                                            />
                                            {noAuthInput?.error?.some(item => item.includes("البريد الالكتروني"))
                                                && <p className="text-sm text-red-500">{t('contact.email')} {t('footer.is-here')}</p>}
                                        </div>

                                        {/* phone number */}
                                        <div className="w-full">
                                            <Label htmlFor="phone" className="flex items-center gap-2">
                                                <span>
                                                    <img src={logo} alt="Ivory Logos" className="w-4" />
                                                </span>
                                                {t('contact.phone')}
                                            </Label>
                                            <Input
                                                type="number"
                                                id="phone"
                                                name="phone"
                                                value={noAuthInput.phone || ''}
                                                placeholder={`${t('footer.enter')} ${t('contact.phone')} ${t('footer.here')}`}
                                                onChange={(e) => setNoAuthInput(prev => ({
                                                    ...prev,
                                                    phone: e.target.value
                                                }))}
                                                className="w-full my-2 text-black placeholder:py-2 bg-[#F5F5F5] focus:ring-secondary-tw"
                                                required
                                            />
                                            {noAuthInput?.error?.some(item => item.includes("الهاتف"))
                                                && <p className="text-sm text-red-500"> {t('footer.phone-is-here')}</p>}
                                        </div>

                                        {/* company */}
                                        <div className="w-full">
                                            <Label htmlFor="companyTitle" className="flex items-center gap-2">
                                                <span>
                                                    <img src={logo} alt="Ivory logo" className="w-4" />
                                                </span>
                                                {t('contact.company')}
                                            </Label>
                                            <Input
                                                type="text"
                                                id="companyTitle"
                                                name="companyTitle"
                                                value={noAuthInput.companyTitle || ''}
                                                placeholder={`${t('footer.enter')} ${t('contact.company')} ${t('footer.here')}`}
                                                onChange={(e) => setNoAuthInput(prev => ({
                                                    ...prev,
                                                    companyTitle: e.target.value
                                                }))}
                                                className="w-full my-2 text-black placeholder:py-2 bg-[#F5F5F5] focus:ring-secondary-tw"
                                                required
                                            />
                                            {noAuthInput?.error?.some(item => item.includes("الشركة"))
                                                && <p className="text-sm text-red-500">{t('contact.company')} {t('footer.is-here')}</p>}
                                        </div>

                                        {/* job title */}
                                        <div className="w-full">
                                            <Label htmlFor="jobTitle" className="flex items-center gap-2">
                                                <span>
                                                    <img src={logo} alt="Ivory Logos" className="w-4" />
                                                </span>
                                                {t('contact.job')}
                                            </Label>
                                            <Input
                                                type="text"
                                                id="jobTitle"
                                                name="jobTitle"
                                                value={noAuthInput.jobTitle || ''}
                                                placeholder={`${t('footer.enter')} ${t('contact.job')} ${t('footer.here')}`}
                                                onChange={(e) => setNoAuthInput(prev => ({
                                                    ...prev,
                                                    jobTitle: e.target.value
                                                }))}
                                                className="!w-full my-2 text-black placeholder:py-2 bg-[#F5F5F5] focus:ring-secondary-tw"
                                                required
                                            />
                                            {noAuthInput?.error?.some(item => item.includes("الوظيفة"))
                                                && <p className="text-sm text-red-500">{t('contact.job')} {t('footer.is-here')}</p>}
                                        </div>

                                        <DialogFooter className="gap-2 md:col-span-3">
                                            <Button type="submit"
                                                disabled={noAuthInput.isLoading}
                                                className="w-full bg-primary-tw text-white"
                                            >
                                                {noAuthInput.isLoading ?
                                                    <>
                                                        <Loader className="animate-spin" />
                                                        {t('custom.confirming')}
                                                    </>
                                                    :
                                                    t('custom.confirm')}
                                            </Button>
                                            <Button type="button"
                                                className="w-full bg-semi-gray text-white"
                                                disabled={noAuthInput.isLoading}
                                                onClick={reset}>
                                                {t('custom.reset')}
                                            </Button>

                                        </DialogFooter>
                                    </form>
                                </div>
                            </section>
                        }
                    </div>
            }
        </>
    )
};