'use client';

import InputField from '@/components/input/InputField';
import clsx from 'clsx';
import { TickCircle, Trash } from 'iconsax-react';
import { useTranslation } from 'react-i18next';
import { useApplyCoupon, useRemoveCoupon } from '../../hooks/useOrderData';
import Button from '@/components/button/PrimaryButton';
import { extractErrorMessage } from '@/lib/func';
import { toast } from '@/components/Toast';
import { glassSurfaceCard } from '@/lib/styles/glassSurface';
import { useEffect, useState } from 'react';
import { useGetCartItems } from '@/app/[name]/(Main)/cart/hooks/useCartData';

type CouponSectionProps = {
    couponType: string;
    couponCode: string;
    couponCodeError: string;
    onCouponTypeChange: (id: string) => void;
    onCouponCodeChange: (value: string) => void;
};

export const CouponSection = ({
    couponCode,
    couponCodeError,
    onCouponCodeChange,
}: CouponSectionProps) => {

    const { t } = useTranslation('parallels', { keyPrefix: 'OrderDetail' });
    const { mutate: applyCoupon, isPending } = useApplyCoupon();
    const { mutate: removeCoupon, isPending: isRemoving } = useRemoveCoupon();
    const { data: cartItems } = useGetCartItems();
    const [isApplied, setIsApplied] = useState<boolean>(false);

    const handleApplyCoupon = () => {
        applyCoupon(couponCode, {
            onSuccess: () => {
                toast('کوپن با موفقیت اعمال شد', 'success');
                setIsApplied(true);
            },
            onError: (error) => {
                toast(extractErrorMessage(error), 'error');
                setIsApplied(false);
            }
        });
    };

    const handleCouponCodeChange = (value: string) => {
        onCouponCodeChange(value);
        if (isApplied) {
            setIsApplied(false);
        }
    };

    const handleRemoveCoupon = () => {
        removeCoupon(undefined, {
            onSuccess: () => {
                toast('کوپن با موفقیت حذف شد', 'success');
                setIsApplied(false);
                onCouponCodeChange('');
            },
            onError: (error) => {
                toast(extractErrorMessage(error), 'error');
            }
        });
    };

    useEffect(() => {
        const hasCoupon = (cartItems?.data?.couponDiscount ?? 0) > 0;
        setIsApplied(hasCoupon);
        if (hasCoupon && cartItems?.data?.coupon?.couponCode) {
            onCouponCodeChange(cartItems.data.coupon.couponCode);
        }
    }, [cartItems, onCouponCodeChange]);

    return (
        <section className={glassSurfaceCard('p-4')}>
            <div className="py-3">
                <h3 className="text-sm2 font-medium leading-5">{t("SectionCoupon.Title")}</h3>

                <div className='flex flex-col gap-5 mt-6'>
                    {/* {couponOptions.map(({ id, label, icon: Icon }) => (
                        <div key={id} className='flex items-center'>
                            <label className='flex items-center gap-2 w-full' htmlFor={`couponType${id}`}>
                                <Icon
                                    size={16}
                                    color='currentColor'
                                    className='mr-2'
                                />
                                <span className='text-xs mt-0.5'>{label}</span>
                            </label>

                            <input
                                checked={couponType === id}
                                onChange={() => onCouponTypeChange(id)}
                                type='radio'
                                name='couponType'
                                id={`couponType${id}`}
                                className='size-4 accent-primary' />
                        </div>
                    ))} */}
                </div>

                {isApplied ? (
                    <div className='mt-6 flex items-center gap-3'>
                        <div className='flex-1 flex items-center gap-2 px-4 py-2.5 bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 rounded-normal'>
                            <TickCircle size={20} color='#10b981' variant='Bold' />
                            <span className='text-xs text-emerald-700 dark:text-emerald-400 font-medium'>کد تخفیف اعمال شده</span>
                            <span className='text-xs text-emerald-600 dark:text-emerald-500 font-medium mr-auto'>{couponCode}</span>
                        </div>
                        <button
                            onClick={handleRemoveCoupon}
                            disabled={isRemoving}
                            className='p-2.5 hover:bg-gray-100 dark:hover:bg-neutral-800 rounded-normal transition-colors disabled:opacity-50'
                            type='button'
                        >
                            <Trash color='currentColor' size={20} className='text-gray-600 dark:text-gray-400' />
                        </button>
                    </div>
                ) : (
                    <div className='flex gap-4 items-end'>
                        <InputField
                            autoComplete='off'
                            className={clsx(
                                'relative',
                                couponCodeError.trim() === 'valid' && 'text-emerald-400 **:stroke-emerald-400 ring ring-emerald-400'
                            )}
                            placeholder={t("SectionCoupon.InputCouponCode.Placeholder")}
                            htmlFor={'couponCode'}
                            onChange={(e) => handleCouponCodeChange(e.target.value)}
                            value={couponCode}
                        />
                        <Button
                            disabled={couponCode.length === 0 || isPending}
                            className='w-fit h-11'
                            onClick={handleApplyCoupon}
                            pending={isPending}
                        >
                            <div className='flex items-center gap-2'>
                                <TickCircle size={16} color='currentColor' variant='Outline' />
                                <span className='text-xs whitespace-nowrap'>اعمال</span>
                            </div>
                        </Button>
                    </div>
                )}


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

