import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { CiShop } from 'react-icons/ci';
import { Tooltip } from 'antd';
import { getCompBranchData } from '../../../Features/BrachLogin/BranchLogin';
import { StoredSessionData } from '../../../Features/ThemeChange/ThemeChange';
import defaultItemImg from '../../../Images/defaultItemImg.png';

const BranchName = ({ IconStatus }) => {
  const dispatch = useDispatch();
  const SessionData = useSelector(StoredSessionData);
  const AppId = SessionData?.AppId;
  const CompId = SessionData?.CompId;
  const BranchId = SessionData?.BranchId;
  const UserId = SessionData?.UserId;

  const [branchName, setBranchName] = useState('Guest');
  const [BranchUrl, setBranchUrl] = useState(defaultItemImg);
  const [imageLoaded, setImageLoaded] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  useEffect(() => {
    if (AppId && CompId && BranchId && UserId) {
      fetchBranchName();
    } else {
      setIsLoading(false);
    }
  }, [AppId, CompId, BranchId, UserId]);

  // Preload image
  useEffect(() => {
    if (BranchUrl && BranchUrl !== defaultItemImg) {
      setImageLoaded(false);
      const img = new Image();
      img.onload = () => setImageLoaded(true);
      img.onerror = () => {
        setBranchUrl(defaultItemImg);
        setImageLoaded(true);
      };
      img.src = BranchUrl;
    } else {
      setImageLoaded(true);
    }
  }, [BranchUrl]);

  const fetchBranchName = async () => {
    try {
      setIsLoading(true);
      const response = await dispatch(
        getCompBranchData({ AppId, UserId, CompId })
      ).unwrap();

      if (response?.data?.statusCode === 1) {
        // Use find() instead of filter()[0] for better performance
        const branchData = response?.data?.data?.find(
          (item) => item?.BrId == BranchId
        );

        if (branchData) {
          setBranchName(branchData.IndividualBrName || 'Guest');
          setBranchUrl(branchData.CompLogo || defaultItemImg);
        }
      }
    } catch (error) {
      console.error('Error fetching branch data:', error);
      setBranchName('Guest');
      setBranchUrl(defaultItemImg);
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div
        className="nameofBracnchmain"
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: '10px',
          width: '180px',
        }}
      >
        Loading...
      </div>
    );
  }

  return (
    <>
      {!IconStatus ? (
        <Tooltip title={branchName}>
          <div
            className="nameofBracnchmain"
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '10px',
              cursor: 'pointer',
              width: '180px',
            }}
          >
            <span
              style={{
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                maxWidth: '100%',
                fontFamily: 'Poppins',
                fontWeight: '500',
              }}
            >
              {branchName}
            </span>
          </div>
        </Tooltip>
      ) : (
        <Tooltip title={branchName}>
          <div
            className="nameofBracnchmain"
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '10px',
              width: '180px',
            }}
          >
            {!imageLoaded && (
              <div
                style={{
                  width: '40px',
                  height: '40px',
                  background: '#f0f0f0',
                  borderRadius: '4px',
                  flexShrink: 0,
                }}
              />
            )}
            <img
              src={BranchUrl}
              alt="company logo"
              style={{
                display: imageLoaded ? 'block' : 'none',
                maxWidth: '40px',
                maxHeight: '40px',
                objectFit: 'contain',
                flexShrink: 0,
              }}
              onLoad={() => setImageLoaded(true)}
              onError={() => setBranchUrl(defaultItemImg)}
            />
            <p
              style={{
                fontSize: '20px',
                fontWeight: '500',
                cursor: 'pointer',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                margin: 0,
                flex: 1,
              }}
            >
              {branchName}
            </p>
          </div>
        </Tooltip>
      )}
    </>
  );
};

export default React.memo(BranchName);
