'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faLock, faWifi, faEye, faEyeSlash, faSignOutAlt } from '@fortawesome/free-solid-svg-icons';
import System from '@/lib/models/System';

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 {
      if (window.electron) {
        const result = await window.electron.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 () => {
    System.removeCookie("token");
    await window.electron.removeToken();
    window.electron.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">
        {/* Header */}
        <div className="flex items-center justify-center mb-6">
          <div className="relative">
            <div className="p-4 bg-primary/10 rounded-full">
              <FontAwesomeIcon icon={faLock} 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">
                <FontAwesomeIcon icon={faWifi} className="w-3 h-3 text-warning" />
              </div>
            </div>
          </div>
        </div>

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

        {/* PIN Input */}
        <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="w-full px-4 py-3 bg-secondary border border-gray-dark rounded-lg focus:outline-none focus:border-primary 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-textPrimary"
            >
              <FontAwesomeIcon icon={showPin ? faEyeSlash : faEye} className="w-4 h-4" />
            </button>
          </div>
        </div>

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

        {/* Actions */}
        <div className="flex gap-3">
          <button
            onClick={handleLogout}
            className="flex-1 px-4 py-2 text-error hover:bg-error/10 rounded-lg transition-all flex items-center justify-center gap-2"
            disabled={isLoading}
          >
            <FontAwesomeIcon icon={faSignOutAlt} className="w-4 h-4" />
            <span className="text-sm font-medium">{t('userMenu.logout')}</span>
          </button>
          {onCancel && (
            <button
              onClick={onCancel}
              className="flex-1 px-4 py-2 border border-gray-dark text-muted hover:text-textPrimary hover:border-gray rounded-lg transition-colors"
              disabled={isLoading}
            >
              {t('offline.pin.verify.cancelButton')}
            </button>
          )}
          <button
            onClick={handleVerifyPin}
            disabled={isLoading || !pin || attempts > 2}
            className="flex-1 px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
          >
            {isLoading ? (
              <>
                <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                {t('offline.pin.verify.verifyingButton')}
              </>
            ) : (
              <>
                <FontAwesomeIcon icon={faLock} className="w-4 h-4" />
                {t('offline.pin.verify.unlockButton')}
              </>
            )}
          </button>
        </div>

        {/* Help text */}
        {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>
  );
}