'use client';

import { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { Loader, Mail } from 'lucide-react';

import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { OTPInput } from '@/components/form/otp-input';
import { Label } from '@/components/ui/label';
import { useFormSubmission } from '@/hooks/use-form-submission';
import { toast } from '@/hooks/use-toast';

interface EmailVerificationOTPProps {
    open: boolean;
    onSuccess: () => void;
    onClose: () => void;
}

export function EmailVerificationOTP({ open, onSuccess, onClose }: EmailVerificationOTPProps) {
    const t = useTranslations();
    const [otp, setOtp] = useState('');
    const [resendCountdown, setResendCountdown] = useState(60);
    const [canResend, setCanResend] = useState(false);

    useEffect(() => {
        if (open && resendCountdown > 0) {
            const timer = setTimeout(() => {
                setResendCountdown(resendCountdown - 1);
            }, 1000);
            return () => clearTimeout(timer);
        } else if (resendCountdown === 0) {
            setCanResend(true);
        }
    }, [resendCountdown, open]);

    useEffect(() => {
        if (open) {
            setResendCountdown(60);
            setCanResend(false);
            setOtp('');
        }
    }, [open]);

    const verifyOTP = useFormSubmission({
        endPoint: '/email/confirm/check',
        method: 'POST',
        context: 'main',
        onSuccess: (response) => {
            toast({
                variant: "success",
                title: t('custom.done'),
                description: t('custom.email-verified'),
            });
            onSuccess();
        },
        onError: (error) => {
            const errorMessage = error?.response?.data?.error || t('custom.invalid-otp');
            toast({
                variant: "destructive",
                title: t('custom.failed'),
                description: errorMessage
            });
            return { handled: true };
        }
    });

    const resendCode = useFormSubmission({
        endPoint: '/email/confirm/resend',
        method: 'POST',
        context: 'main',
        onSuccess: () => {
            toast({
                variant: "success",
                title: t('custom.done'),
                description: t('custom.code-sent'),
            });
            setResendCountdown(60);
            setCanResend(false);
        },
        onError: (error) => {
            const errorMessage = error?.response?.data?.error || error?.response?.data?.message || t('custom.try-again');
            toast({
                variant: "destructive",
                title: t('custom.failed'),
                description: errorMessage
            });
            return { handled: true };
        }
    });

    const handleVerify = () => {
        if (otp.length === 6) {
            verifyOTP.mutate({ code: otp });
        }
    };

    const handleResend = () => {
        if (canResend) {
            resendCode.mutate({});
        }
    };

    return (
        <Dialog open={open} onOpenChange={() => {}}>
            <DialogContent hideClose className="sm:max-w-md">
                <DialogHeader>
                    <div className="flex items-center gap-3 mb-2">
                        <Mail className="h-6 w-6 text-primary-tw-400" />
                        <DialogTitle className="text-xl">{t('custom.verification-code')}</DialogTitle>
                    </div>
                    <DialogDescription>
                        {t('custom.enter-verification-code')}
                    </DialogDescription>
                </DialogHeader>

                <div className="space-y-6 py-4">
                    <div className="space-y-3">
                        <Label htmlFor="otp" className="text-center block">
                            {t('custom.verification-code')}
                        </Label>
                        <OTPInput
                            value={otp}
                            onChange={(value) => setOtp(value)}
                            length={6}
                        />
                    </div>

                    <Button
                        onClick={handleVerify}
                        disabled={verifyOTP.isPending || otp.length !== 6}
                        className="w-full bg-primary-tw-400 text-white"
                    >
                        {verifyOTP.isPending ? (
                            <>
                                <Loader className="w-5 h-5 animate-spin" />
                                {t('custom.verifying')}
                            </>
                        ) : (
                            t('custom.verify')
                        )}
                    </Button>

                    <div className="text-center">
                        <button
                            type="button"
                            onClick={handleResend}
                            disabled={!canResend || resendCode.isPending}
                            className="text-primary-tw-400 hover:underline text-sm disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {resendCode.isPending
                                ? t('custom.sending')
                                : canResend
                                    ? t('custom.resend-code')
                                    : `${t('custom.resend-code')} (${resendCountdown}s)`}
                        </button>
                    </div>

                    <div className="pt-4 border-t">
                        <Button
                            type="button"
                            variant="outline"
                            onClick={onClose}
                            className="w-full"
                        >
                            {t('custom.cancel')}
                        </Button>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
}
