import { getAuth } from '@/auth';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';
import { RefreshCw, Shield, Smartphone, QrCode } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import clsx from 'clsx';

const API_URL = apiConfig.service_dashboard;

const GenerateQr = () => {
  const { GetData, PostData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [qrCodeUrl, setQrCodeUrl] = useState<string | null>(null);
  const [inputToken, setInputToken] = useState('');
  const [loading, setLoading] = useState<boolean>(false);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  const getQrCode = async () => {
    if (!parsedUser?.id) {
      toast.error('User ID not found');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const response = await GetData(`${API_URL}/user/generate_mfa/${parsedUser.id}`, {});
      if (response?.status) {
        setQrCodeUrl(response.data.token_base64);
        toast.success('QR Code generated successfully');
      } else {
        setError('QR Code not found');
        toast.error(response?.message);
      }
    } catch (error) {
      toast.error('Something went wrong, please try again');
    } finally {
      setLoading(false);
    }
  };

  const verifyToken = async () => {
    if (!parsedUser?.id) {
      toast.error('User ID not found');
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await PostData(`${API_URL}/user/verify_mfa`, {
        id: parsedUser.id,
        token: inputToken
      });

      if (response?.status) {
        toast.success('Token verified successfully');
        setInputToken('');
      } else {
        toast.error(response?.message);
      }
    } catch (error) {
      toast.error('Something went wrong, please try again');
    } finally {
      setIsSubmitting(false);
      setQrCodeUrl(null);
    }
  };

  return (
    <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden hover:shadow-xl transition-shadow duration-300 h-fit">
      <div className="bg-gradient-to-r from-red-600 to-pink-600 px-6 py-4">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center">
            <Shield className="text-white w-4 h-4" />
          </div>
          <h3 className="text-xl font-semibold text-white">Multi-Factor Authentication</h3>
        </div>
      </div>

      <div className="p-6">
        {!qrCodeUrl ? (
          // Initial Setup State
          <div className="text-center space-y-6">
            <div className="w-16 h-16 bg-red-100 rounded-2xl flex items-center justify-center mx-auto">
              <Smartphone className="w-8 h-8 text-red-600" />
            </div>

            <div className="space-y-2">
              <h4 className="text-lg font-semibold text-gray-900">Secure Your Account</h4>
              <p className="text-gray-600 text-sm leading-relaxed">
                Add an extra layer of security to your account with multi-factor authentication
                using your mobile device.
              </p>
            </div>

            <div className="bg-gradient-to-r from-red-50 to-pink-50 rounded-xl p-4 border border-red-100">
              <div className="flex items-start space-x-3">
                <div className="w-6 h-6 bg-red-600 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                  <span className="text-white text-xs font-bold">1</span>
                </div>
                <div className="text-left">
                  <p className="text-sm font-medium text-gray-900">Download an authenticator app</p>
                  <p className="text-xs text-gray-600 mt-1">
                    Google Authenticator{' '}
                    <a
                      href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2"
                      target="_blank"
                      className="underline text-red-400 hover:text-red-500"
                    >
                      click here
                    </a>
                  </p>
                </div>
              </div>
            </div>

            <button
              onClick={getQrCode}
              disabled={loading}
              className={clsx(
                'w-full py-3 px-6 rounded-xl font-medium transition-all duration-200 flex items-center justify-center space-x-2',
                loading
                  ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                  : 'bg-gradient-to-r from-red-600 to-pink-600 text-white hover:from-red-700 hover:to-pink-700 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5'
              )}
            >
              {loading ? (
                <>
                  <div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin"></div>
                  <span>Generating QR Code...</span>
                </>
              ) : (
                <>
                  <QrCode className="w-5 h-5" />
                  <span>Setup Multi-Factor Authentication</span>
                </>
              )}
            </button>
          </div>
        ) : (
          // QR Code Generated State
          <div className="space-y-6">
            <div className="text-center space-y-4">
              <div className="w-16 h-16 bg-green-100 rounded-2xl flex items-center justify-center mx-auto">
                <QrCode className="w-8 h-8 text-green-600" />
              </div>

              <div className="space-y-2">
                <h4 className="text-lg font-semibold text-gray-900">Scan QR Code</h4>
                <p className="text-gray-600 text-sm">
                  Open your authenticator app and scan this QR code
                </p>
              </div>
            </div>

            <div className="flex justify-center">
              <div className="bg-white rounded-2xl p-4 shadow-lg border-2 border-gray-100">
                <img src={qrCodeUrl} alt="QR Code MFA" className="w-48 h-48 rounded-xl" />
              </div>
            </div>

            <div className="space-y-4">
              <div className="space-y-2">
                <label className="block text-sm font-medium text-gray-700">Verification Code</label>
                <input
                  type="text"
                  className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent transition-all duration-200 text-center text-lg tracking-widest"
                  placeholder="000000"
                  value={inputToken}
                  onChange={(e) => setInputToken(e.target.value.replace(/\D/g, '').slice(0, 6))}
                  maxLength={6}
                />
                <p className="text-xs text-gray-500">
                  Enter the 6-digit code from your authenticator app
                </p>
              </div>

              <button
                onClick={verifyToken}
                disabled={isSubmitting || inputToken.length !== 6}
                className={clsx(
                  'w-full py-3 px-6 rounded-xl font-medium transition-all duration-200 flex items-center justify-center space-x-2',
                  isSubmitting || inputToken.length !== 6
                    ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                    : 'bg-gradient-to-r from-red-600 to-orange-600 text-white hover:from-red-700 hover:to-orange-700 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5'
                )}
              >
                {isSubmitting ? (
                  <>
                    <RefreshCw className="w-5 h-5 animate-spin" />
                    <span>Verifying...</span>
                  </>
                ) : (
                  <>
                    <Shield className="w-5 h-5" />
                    <span>Verify & Enable MFA</span>
                  </>
                )}
              </button>
            </div>
          </div>
        )}

        {error && (
          <div className="mt-4 p-3 bg-red-50 rounded-lg border border-red-200">
            <p className="text-sm text-red-600 text-center">{error}</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default GenerateQr;
