import React, { useEffect, useState } from 'react';
import { useParams, useNavigate, Outlet, Navigate } from 'react-router-dom';
import { useAuthStore } from '../state/stores/useAuthStore';
import SystemSelectionModal from '../components/SystemSelectionModal';
import TenantProfile from '../components/TenantProfile';
import Sidebar from './Sidebar';
import LoginModal from '../components/LoginModal';

const   DualModalComponent = () => {
  const { systemId } = useParams();
  const navigate = useNavigate();
  const { isLoggedIn } = useAuthStore();
  const [isExpanded, setIsExpanded] = useState(false);
  const [showOutlet, setShowOutlet] = useState(false);
  const [logoPath, setLogoPath] = useState('');
  const [systemDetails, setSystemDetails] = useState(null);
  const [animationFinished, setAnimationFinished] = useState(false);
  const animationSpeed = 500;

  const [redirectTo, setRedirectTo] = useState<string | null>(null);

  useEffect(() => {
    console.log(`useEffect triggered: systemId=${systemId}, isLoggedIn=${isLoggedIn}`);
    if (!isLoggedIn) {
      setIsExpanded(false);
      setShowOutlet(false);
      setAnimationFinished(false); // Reset animation
    } else if (systemId && systemId !== 'default') {
      setIsExpanded(true);
      setShowOutlet(true);
      setTimeout(() => setAnimationFinished(true), animationSpeed);
    } else {
      setIsExpanded(false);
      setShowOutlet(false);
      setAnimationFinished(false); // Reset animation
    }
  }, [systemId, isLoggedIn]);

  const handleSystemSelected = (systemData) => {
    console.log(`System selected: ${systemData.urlSlug}`);
    setRedirectTo(`/dashboard/${systemData.urlSlug}`);
    setIsExpanded(true);
    setShowOutlet(true);
    setLogoPath(systemData.logo);
    setSystemDetails(systemData);
    setAnimationFinished(false);
  };

  const handleLogoChange = (newLogoPath) => {
    setLogoPath(newLogoPath);
  };

  const [isCollapsed, setIsCollapsed] = useState(false);

  if (redirectTo) {
    return <Navigate to={redirectTo} replace />;
  }

  return (
    <div className='flex items-center justify-center h-screen bg-gradient-to-br from-gray-700 to-teal-900' data-system={systemId}>
      <div
        className={`transition-all ease-in-out duration-500 rounded ${isExpanded
          ? 'w-1/5 h-screen px-4'
          : `${isLoggedIn ? 'w-1/2 h-3/4' : 'w-1/3 h-2/4'} my-12 mx-6 px-4`
          } m-2 bg-white shadow-xl flex justify-center items-center px-4`}
      >
        {isLoggedIn ? (
          showOutlet && systemId && animationFinished ? (
            <Sidebar
              systemId={systemId}
              isCollapsed={isCollapsed}
              setIsCollapsed={setIsCollapsed}
            />
          ) : (
            <p
              className={`h-full w-full transition-opacity duration-50 ${isExpanded ? 'opacity-0' : 'opacity-100'
                }`}
            >
              <TenantProfile />
            </p>
          )
        ) : (
          <LoginModal />
        )}
      </div>

      <div
        className={`relative flex-1 w-full overflow-auto transition-all ease-in-out duration-500 flex rounded ${isExpanded ? 'w-1/3 max-w-none h-full' : 'w-1/3 h-1/2 mx-6'
          } bg-white shadow-xl justify-center items-center ${isLoggedIn ? '' : 'hidden'}`}
      >
        {isLoggedIn && showOutlet && systemId ? (
          <Outlet />
        ) : (
          <>
            <SystemSelectionModal
              onSystemSelected={handleSystemSelected}
              onLogoChange={handleLogoChange}
              systemDetails={systemDetails}
            />
            {logoPath && (
              <img
                src={logoPath}
                alt='Selected System Logo'
                style={{ maxHeight: '150px', padding: '0 40px 0 0', overflow: 'hidden' }}
              />
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default DualModalComponent;
