'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 bg-background">
            <div className="bg-tertiary rounded-2xl p-6 max-w-md w-full mx-4 shadow-2xl">
                <div className="flex items-center justify-center mb-6">
                    <div className="relative">
                        <div className="p-4 bg-primary/10 rounded-full">
                            <Lock className="w-8 h-8 text-primary"/>
                        </div>
                        <div className="absolute -bottom-1 -right-1 p-1 bg-tertiary rounded-full">
                            <div className="p-1 bg-warning/20 rounded-full">
                                <Wifi className="w-3 h-3 text-warning"/>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="text-center mb-6">
                    <h2 className="text-xl font-bold text-text-primary mb-2">
                        {t('offline.pin.verify.title')}
                    </h2>
                    <p className="text-sm text-muted">
                        {t('offline.pin.verify.subtitle')}
                    </p>
                </div>

                <div className="mb-4">
                    <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>
                </div>

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

                <div className="flex gap-3">
                    <Button variant="danger" icon={LogOut} onClick={handleLogout} disabled={isLoading}>
                        {t('userMenu.logout')}
                    </Button>
                    {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>

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