'use client';

import {useState, useContext} from 'react';
import {SessionContext} from '@/context/SessionContext';
import {useTranslations} from '@/lib/i18n';
import {Lock, ShieldCheck, Eye, EyeOff} from 'lucide-react';
import * as tauri from '@/lib/tauri';
import Button from '@/components/ui/Button';
import IconButton from '@/components/ui/IconButton';

interface OfflinePinSetupProps {
    onClose?: () => void;
    onSuccess?: () => void;
    showOnFirstLogin?: boolean;
}

export default function OfflinePinSetup({onClose, onSuccess, showOnFirstLogin}: OfflinePinSetupProps) {
    const t = useTranslations();
    const {session} = useContext(SessionContext);
    const [pin, setPin] = useState('');
    const [confirmPin, setConfirmPin] = useState('');
    const [showPin, setShowPin] = useState(false);
    const [error, setError] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    if (!session?.isConnected || !session?.user) {
        return null;
    }

    const validatePin = (): boolean => {
        if (pin.length < 4) {
            setError(t('offline.pin.errors.tooShort'));
            return false;
        }
        if (pin.length > 8) {
            setError(t('offline.pin.errors.tooLong'));
            return false;
        }
        if (!/^\d+$/.test(pin)) {
            setError(t('offline.pin.errors.digitsOnly'));
            return false;
        }
        if (pin !== confirmPin) {
            setError(t('offline.pin.errors.mismatch'));
            return false;
        }
        return true;
    };

    const handleSetPin = async () => {
        if (!validatePin()) return;

        setIsLoading(true);
        setError('');

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

            if (result.success) {
                await tauri.offlineModeSet(true, 30);
                onSuccess?.();
            } else {
                setError(result.error || t('offline.pin.errors.setupFailed'));
            }
        } catch (error) {
            setError(t('offline.pin.errors.setupFailed'));
        } finally {
            setIsLoading(false);
        }
    };

    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">
                        <ShieldCheck className="w-6 h-6" strokeWidth={1.75}/>
                        {showOnFirstLogin ? t('offline.pin.setup.titleFirstLogin') : t('offline.pin.setup.title')}
                    </h2>
                    {onClose && (
                        <IconButton icon={Lock} variant="light" onClick={onClose}/>
                    )}
                </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">
                            {t('offline.pin.setup.subtitle')}
                        </p>

                        <div className="p-3 bg-info/10 border border-info/20 rounded-lg">
                            <p className="text-sm text-info flex items-center gap-2">
                                <Lock className="w-3 h-3 shrink-0"/>
                                {t('offline.pin.setup.description')}
                            </p>
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-text-primary mb-2">
                                {t('offline.pin.setup.pinLabel')}
                            </label>
                            <div className="relative">
                                <input
                                    type={showPin ? 'text' : 'password'}
                                    value={pin}
                                    onChange={(e) => setPin(e.target.value.replace(/\D/g, '').slice(0, 8))}
                                    placeholder="••••"
                                    maxLength={8}
                                    className="input-base text-center text-lg tracking-widest"
                                    disabled={isLoading}
                                />
                                <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>

                        <div>
                            <label className="block text-sm font-medium text-text-primary mb-2">
                                {t('offline.pin.setup.confirmPinLabel')}
                            </label>
                            <input
                                type={showPin ? 'text' : 'password'}
                                value={confirmPin}
                                onChange={(e) => setConfirmPin(e.target.value.replace(/\D/g, '').slice(0, 8))}
                                placeholder="••••"
                                maxLength={8}
                                className="input-base text-center text-lg tracking-widest"
                                disabled={isLoading}
                            />
                        </div>

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

                        <p className="text-xs text-muted text-center">
                            {t('offline.pin.setup.footer')}
                        </p>
                    </div>
                </div>

                <div className="flex justify-end gap-3 px-6 py-4">
                    {onClose && (
                        <Button variant="ghost" onClick={onClose} disabled={isLoading}>
                            {t('offline.pin.setup.laterButton')}
                        </Button>
                    )}
                    <Button
                        variant="primary"
                        icon={Lock}
                        isLoading={isLoading}
                        loadingText={t('offline.pin.setup.configuringButton')}
                        onClick={handleSetPin}
                        disabled={isLoading || !pin || !confirmPin}
                    >
                        {t('offline.pin.setup.configureButton')}
                    </Button>
                </div>
            </div>
        </div>
    );
}
