'use client';

import { useState, useContext } from 'react';
import { SessionContext } from '@/context/SessionContext';
import { useTranslations } from 'next-intl';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faLock, faShieldAlt, faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons';

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);

  // Only allow PIN setup if authenticated
  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 {
      if (window.electron) {
        const result = await window.electron.offlinePinSet(pin);

        if (result.success) {
          await window.electron.offlineModeSet(true, 30); // 30 days sync interval
          onSuccess?.();
        } else {
          setError(result.error || t('offline.pin.errors.setupFailed'));
        }
      }
    } catch (error) {
      console.error('[OfflinePin] Error setting PIN:', error);
      setError(t('offline.pin.errors.setupFailed'));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-tertiary rounded-2xl p-6 max-w-md w-full mx-4 shadow-2xl">
        {/* Header */}
        <div className="flex items-center gap-3 mb-4">
          <div className="p-3 bg-primary/10 rounded-lg">
            <FontAwesomeIcon icon={faShieldAlt} className="w-6 h-6 text-primary" />
          </div>
          <div className="flex-1">
            <h2 className="text-xl font-bold text-textPrimary">
              {showOnFirstLogin ? t('offline.pin.setup.titleFirstLogin') : t('offline.pin.setup.title')}
            </h2>
            <p className="text-sm text-muted">
              {t('offline.pin.setup.subtitle')}
            </p>
          </div>
        </div>

        {/* Info box */}
        <div className="bg-info/10 border border-info/20 rounded-lg p-3 mb-4">
          <p className="text-sm text-info">
            <FontAwesomeIcon icon={faLock} className="w-3 h-3 mr-2" />
            {t('offline.pin.setup.description')}
          </p>
        </div>

        {/* PIN Input */}
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-textPrimary 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="w-full px-4 py-2 bg-secondary border border-gray-dark rounded-lg focus:outline-none focus:border-primary"
                disabled={isLoading}
              />
              <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>

          <div>
            <label className="block text-sm font-medium text-textPrimary 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="w-full px-4 py-2 bg-secondary border border-gray-dark rounded-lg focus:outline-none focus:border-primary"
              disabled={isLoading}
            />
          </div>
        </div>

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

        {/* Actions */}
        <div className="mt-6 flex gap-3 justify-end">
          {onClose && (
            <button
              onClick={onClose}
              className="px-4 py-2 text-muted hover:text-textPrimary transition-colors"
              disabled={isLoading}
            >
              {t('offline.pin.setup.laterButton')}
            </button>
          )}
          <button
            onClick={handleSetPin}
            disabled={isLoading || !pin || !confirmPin}
            className="px-6 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            <FontAwesomeIcon icon={faLock} className="w-4 h-4" />
            {isLoading ? t('offline.pin.setup.configuringButton') : t('offline.pin.setup.configureButton')}
          </button>
        </div>

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