import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { apiCall } from '../utils/api';
import { User } from '../types';

const PendingApproval: React.FC = () => {
  const navigate = useNavigate();
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Get user data from localStorage
    const savedUser = localStorage.getItem('user');
    if (savedUser) {
      setUser(JSON.parse(savedUser));
    }
    setLoading(false);

    // Check status every 30 seconds
    const interval = setInterval(checkUserStatus, 30000);
    return () => clearInterval(interval);
  }, []);

  const checkUserStatus = async () => {
    try {
      const token = localStorage.getItem('authToken');
      const { data: userData } = await apiCall('/auth/users/me', {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (userData) {
        setUser(userData);
        
        // If user is approved, redirect to dashboard
        if (userData.status === 'active') {
          window.location.href = '/';
        }
      }
    } catch (error) {
      console.error('Error checking user status:', error);
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('authToken');
    localStorage.removeItem('user');
    window.location.href = '/';
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-4 border-amber-500 border-t-transparent mx-auto"></div>
          <p className="mt-4 text-slate-600">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-3xl shadow-2xl max-w-md w-full p-8 text-center relative overflow-hidden">
        {/* Decorative element */}
        <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-amber-200 to-orange-200 rounded-full blur-3xl opacity-30 -translate-y-20 translate-x-20"></div>
        
        <div className="relative z-10">
          {/* Icon */}
          <div className="w-24 h-24 bg-gradient-to-br from-amber-400 to-orange-500 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg">
            <svg className="w-12 h-12 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          
          {/* Welcome message */}
          <h1 className="text-3xl font-bold bg-gradient-to-r from-amber-600 to-orange-600 bg-clip-text text-transparent mb-2">
            Welcome, {user?.name?.split(' ')[0]}!
          </h1>
          
          <p className="text-lg text-slate-600 mb-8">
            Your account is being reviewed
          </p>

          {/* Status message */}
          <div className="bg-gradient-to-r from-amber-50 to-orange-50 border border-amber-200 rounded-2xl p-6 mb-8">
            <p className="text-amber-800 leading-relaxed">
              Thank you for signing up! An administrator will review your account request shortly. 
              We'll notify you once your access has been approved.
            </p>
          </div>

          {/* Auto-refresh notice */}
          <p className="text-sm text-slate-500 mb-8">
            This page checks for updates automatically
          </p>

          {/* Logout button */}
          <button
            onClick={handleLogout}
            className="w-full bg-gradient-to-r from-slate-600 to-slate-700 hover:from-slate-700 hover:to-slate-800 text-white font-medium py-3 px-6 rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5"
          >
            Sign Out
          </button>
        </div>
      </div>
    </div>
  );
};

export default PendingApproval;