'use client';

import {useState} from 'react';
import {useTranslations} from '@/lib/i18n';
import {Lock, Wifi, Eye, EyeOff, LogOut} from 'lucide-react';
import {removeCookie} from '@/lib/utils/cookies';
import * as tauri from '@/lib/tauri';
import Button from '@/components/ui/Button';

interface OfflinePinVerifyProps {
    onSuccess: (userId: string) => void;
    onCancel?: () => void;
}

export default function OfflinePinVerify({onSuccess, onCancel}: OfflinePinVerifyProps) {
    const t = useTranslations();
    const [pin, setPin] = useState('');
    const [showPin, setShowPin] = useState(false);
    const [error, setError] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [attempts, setAttempts] = useState(0);

    const handleVerifyPin = async () => {
        if (!pin || pin.length < 4) {
            setError(t('offline.pin.verify.enterPin'));
            return;
        }

        setIsLoading(true);
        setError('');

        try {
            const result = await tauri.offlinePinVerify(pin);

            if (result.success && result.userId) {
                onSuccess(result.userId);
            } else {
                setAttempts(prev => prev + 1);
                setPin('');

                if (attempts >= 2) {
                    setError(t('offline.pin.verify.tooManyAttempts'));
                } else {
                    setError(result.error || t('offline.pin.verify.incorrect'));
                }
            }
        } catch (error) {
            setError(t('offline.pin.verify.error'));
        } finally {
            setIsLoading(false);
        }
    };

    const handleKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            handleVerifyPin();
        }
    };

    const handleLogout = async () => {
        removeCookie("token");
        await tauri.removeToken();
        tauri.logout();
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-darkest-background/60 backdrop-blur-md animate-fadeIn">
            <div className="relative bg-tertiary text-text-primary rounded-xl max-w-md w-full flex flex-col">
                <div className="flex justify-between items-center px-6 py-4">
                    <h2 className="flex items-center gap-3 font-['ADLaM_Display'] text-xl tracking-wide">
                        <Lock className="w-6 h-6" strokeWidth={1.75}/>
                        {t('offline.pin.verify.title')}
                    </h2>
                    <div className="p-1.5 bg-warning/20 rounded-full">
                        <Wifi className="w-4 h-4 text-warning"/>
                    </div>
                </div>

                <div className="bg-darkest-background rounded-xl mx-2 mb-2">
                    <div className="p-5 space-y-4">
                        <p className="text-sm text-muted text-center">
                            {t('offline.pin.verify.subtitle')}
                        </p>

                        <div className="relative">
                            <input
                                type={showPin ? 'text' : 'password'}
                                value={pin}
                                onChange={(e) => setPin(e.target.value.replace(/\D/g, '').slice(0, 8))}
                                onKeyPress={handleKeyPress}
                                placeholder={t('offline.pin.verify.placeholder')}
                                maxLength={8}
                                autoFocus
                                className="input-base text-center text-lg tracking-widest"
                                disabled={isLoading || attempts > 2}
                            />
                            <button
                                type="button"
                                onClick={() => setShowPin(!showPin)}
                                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted hover:text-text-primary transition-colors"
                            >
                                {showPin ? <EyeOff className="w-4 h-4"/> : <Eye className="w-4 h-4"/>}
                            </button>
                        </div>

                        {error && (
                            <div className="p-3 bg-error/10 border border-error/20 rounded-lg">
                                <p className="text-sm text-error text-center">{error}</p>
                            </div>
                        )}

                        {attempts > 0 && attempts <= 2 && (
                            <p className="text-xs text-muted text-center">
                                {t('offline.pin.verify.attemptsRemaining', {count: 3 - attempts})}
                            </p>
                        )}
                    </div>
                </div>

                <div className="flex justify-between px-6 py-4">
                    <Button variant="danger" icon={LogOut} onClick={handleLogout} disabled={isLoading}>
                        {t('userMenu.logout')}
                    </Button>
                    <div className="flex gap-3">
                        {onCancel && (
                            <Button variant="secondary" onClick={onCancel} disabled={isLoading}>
                                {t('offline.pin.verify.cancelButton')}
                            </Button>
                        )}
                        <Button
                            variant="primary"
                            icon={Lock}
                            isLoading={isLoading}
                            loadingText={t('offline.pin.verify.verifyingButton')}
                            onClick={handleVerifyPin}
                            disabled={isLoading || !pin || attempts > 2}
                        >
                            {t('offline.pin.verify.unlockButton')}
                        </Button>
                    </div>
                </div>
            </div>
        </div>
    );
}
