import { useEffect, useState } from "react";

import { Button, Dropdown, Popover, Skeleton } from "antd";

import { DownOutlined, LogoutOutlined, UserOutlined } from "@ant-design/icons";
import { BiSolidGridAlt } from "react-icons/bi";
import { RiFullscreenExitLine, RiFullscreenLine } from "react-icons/ri";
import { Link, useNavigate } from "react-router-dom";

import {
  loadAllStoreByUser,
  updateDefaultStore,
} from "@/redux/rtk/features/store/storeSlice";
import { FaStore } from "react-icons/fa";
import { useDispatch, useSelector } from "react-redux";
import BreadcrumbCustom from "./BreadcrumbCustom";
import QuickLink from "./QuickLink";
import dayjs from "dayjs";
import { loadDashboardData } from "@/redux/rtk/features/dashboard/dashboardSlice";

const userId = localStorage.getItem("id");

const toggler = [
  <svg
    width='20'
    height='20'
    xmlns='http://www.w3.org/2000/svg'
    viewBox='0 0 448 512'
    key={0}
  >
    <path d='M16 132h416c8.837 0 16-7.163 16-16V76c0-8.837-7.163-16-16-16H16C7.163 60 0 67.163 0 76v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16z'></path>
  </svg>,
];

function Header({ onPress, data, loading }) {
  const dispatch = useDispatch();

  const { list, defaultStore } = useSelector((state) => state.store);
  const [open, setOpen] = useState(false);
  const isLogged = localStorage.getItem("isLogged");
  const user = localStorage.getItem("user");
  const [isDarkMode, setDarkMode] = useState(false);
  const navigate = useNavigate();
  const [fullScreen, setFullScreen] = useState(false);
  const [imageError, setImageError] = useState();
  
  const [pageConfig, setPageConfig] = useState({
    storeId: [],
    startDate: dayjs().startOf("month").format("YYYY-MM-DD"),
    endDate: dayjs().endOf("month").format("YYYY-MM-DD"),
  });

  const element = document.documentElement;

  const handleFullScreenClick = () => {
    setFullScreen(true);
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen();
    }
  };
  const handleExitFullScreenClick = () => {
    setFullScreen(false);
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  };

  const handleClick = async ({ key }) => {
    const resp = await dispatch(
      updateDefaultStore({
        id: userId,
        values: {
          defaultStoreId: key,
        },
      })
    );

    if (resp.payload.message === "success") {
      window.location.reload();
    }
    setOpen(false);
  };

  useEffect(() => {
    if (isDarkMode) document.body.className = "dark-theme dark";
    if (!isDarkMode) document.body.className = "light-theme light";
  }, [isDarkMode]);

  useEffect(() => {
    document.addEventListener("fullscreenchange", () => {
      if (document.fullscreenElement) {
      } else {
        setFullScreen(false);
      }
    });
  }, []);

  useEffect(() => {
    dispatch(loadAllStoreByUser());
  }, [dispatch]);

  
    useEffect(() => {
      dispatch(loadDashboardData(pageConfig));
    }, [dispatch, pageConfig]);

  return (
    <>
      <div className='sticky top-0 z-10 flex flex-col w-full py-2 sm:py-3 px-2 sm:px-4 lg:px-6 bg-headerBg dark:bg-[#1C1B20] border-b'>
        {/* Top Row - Logo and Actions (Mobile Only) */}
        <div className='flex md:hidden w-full justify-between items-center mb-2'>
          {/* Logo Section - Mobile Only */}
          <div className='flex-shrink-0'>
            <Skeleton loading={loading}>
              {data?.logo && !imageError ? (
                <img
                  className='text-white'
                  alt='logo'
                  src={data.logo}
                  style={{ 
                    width: "70px", 
                    height: "auto",
                    maxHeight: "35px"
                  }}
                  onError={() => setImageError(true)}
                />
              ) : (
                <h2
                  className='text-gray-300 flex items-center gap-1'
                  style={{ fontSize: "14px" }}
                >
                  OS
                  <strong style={{ color: "#55F", fontWeight: "bold" }}>
                    Inventory
                  </strong>
                </h2>
              )}
            </Skeleton>
          </div>

          {/* Mobile Action Buttons */}
          <div className='flex items-center gap-2'>
            {isLogged && (
              <div className='hidden xs:block sm:block'>
                {fullScreen ? (
                  <RiFullscreenExitLine
                    onClick={handleExitFullScreenClick}
                    size={18}
                    className='cursor-pointer dark:text-white transition-all hover:scale-110'
                  />
                ) : (
                  <RiFullscreenLine
                    onClick={handleFullScreenClick}
                    size={18}
                    className='cursor-pointer dark:text-white transition-all hover:scale-110'
                  />
                )}
              </div>
            )}

            {isLogged && (
              <Button
                type='link'
                className='p-0 h-auto'
                onClick={() => onPress()}
                style={{ boxShadow: "none" }}
              >
                {toggler}
              </Button>
            )}

            {isLogged && (
              <Popover
                placement='bottomRight'
                trigger='click'
                overlayClassName='header-user-popover'
                content={
                  <div className='min-w-[160px] sm:min-w-[180px] rounded-lg'>
                    <p className='flex items-center gap-2 px-2 sm:px-3 py-2 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-lg cursor-pointer transition-colors'>
                      <UserOutlined style={{ fontSize: "14px" }} />{" "}
                      <Link
                        to={`/admin/hr/staffs/${userId}`}
                        className='logout-text uppercase font-weight-bold truncate flex-1 text-xs sm:text-sm'
                      >
                        {user}
                      </Link>
                    </p>
                    {defaultStore && (
                      <div className='px-2 sm:px-3 py-2 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-lg transition-colors'>
                        <Dropdown
                          className='bg-transparent w-full'
                          trigger={["click"]}
                          menu={{
                            items:
                              list?.map((item) => ({
                                label: item.name,
                                key: item.id,
                              })) || [],
                            onClick: handleClick,
                          }}
                        >
                          <a
                            onClick={(e) => e.preventDefault()}
                            className='flex gap-1 sm:gap-2 items-center justify-between w-full text-xs sm:text-sm'
                          >
                            <div className='flex items-center gap-1 sm:gap-2 flex-1 min-w-0'>
                              <FaStore className='flex-shrink-0 text-xs sm:text-sm' />
                              <span className='truncate'>{defaultStore?.name}</span>
                            </div>
                            <DownOutlined className='flex-shrink-0 ml-1 sm:ml-2 text-xs' />
                          </a>
                        </Dropdown>
                      </div>
                    )}
                    <Link
                      to='/admin/auth/logout'
                      className='flex items-center gap-2 px-2 sm:px-3 py-2 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-lg transition-colors'
                    >
                      <LogoutOutlined className='text-red-500 text-sm' />
                      <span className='logout-text font-weight-bold text-xs sm:text-sm'>
                        Log Out
                      </span>
                    </Link>
                  </div>
                }
                arrow={false}
              >
                <UserOutlined className='text-base sm:text-lg cursor-pointer dark:text-white transition-all hover:scale-110' />
              </Popover>
            )}
          </div>
        </div>

        {/* Main Row - QuickLink and Actions */}
        <div className='flex w-full justify-between items-center gap-2 sm:gap-3 md:gap-4'>
          {/* QuickLink Component - Responsive Width */}
          <div className='flex-1 min-w-0 overflow-x-auto scrollbar-thin scrollbar-thumb-gray-300 dark:scrollbar-thumb-gray-600 scrollbar-track-transparent'>
            <div className='w-full'>
              <QuickLink pageConfig={pageConfig} setPageConfig={setPageConfig} />
            </div>
          </div>

          {/* Desktop Action Buttons - Hidden on Mobile */}
          <div className='hidden md:flex items-center gap-2 sm:gap-3 lg:gap-4 flex-shrink-0'>
            {isLogged && (
              <div>
                {fullScreen ? (
                  <RiFullscreenExitLine
                    onClick={handleExitFullScreenClick}
                    size={20}
                    className='cursor-pointer dark:text-white transition-all hover:scale-110'
                  />
                ) : (
                  <RiFullscreenLine
                    onClick={handleFullScreenClick}
                    size={20}
                    className='cursor-pointer dark:text-white transition-all hover:scale-110'
                  />
                )}
              </div>
            )}

            {isLogged && (
              <Popover
                placement='bottomRight'
                trigger='click'
                overlayClassName='header-user-popover'
                content={
                  <div className='min-w-[200px] rounded-lg'>
                    <p className='flex items-center gap-2 px-3 py-2 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-lg cursor-pointer transition-colors'>
                      <UserOutlined style={{ fontSize: "16px" }} />{" "}
                      <Link
                        to={`/admin/hr/staffs/${userId}`}
                        className='logout-text uppercase font-weight-bold truncate flex-1'
                      >
                        {user}
                      </Link>
                    </p>
                    {defaultStore && (
                      <div className='px-3 py-2 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-lg transition-colors'>
                        <Dropdown
                          className='bg-transparent w-full'
                          trigger={["click"]}
                          menu={{
                            items:
                              list?.map((item) => ({
                                label: item.name,
                                key: item.id,
                              })) || [],
                            onClick: handleClick,
                          }}
                        >
                          <a
                            onClick={(e) => e.preventDefault()}
                            className='flex gap-2 items-center justify-between w-full'
                          >
                            <div className='flex items-center gap-2 flex-1 min-w-0'>
                              <FaStore className='flex-shrink-0' />
                              <span className='truncate'>{defaultStore?.name}</span>
                            </div>
                            <DownOutlined className='flex-shrink-0 ml-2' />
                          </a>
                        </Dropdown>
                      </div>
                    )}
                    <Link
                      to='/admin/auth/logout'
                      className='flex items-center gap-2 px-3 py-2 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-lg transition-colors'
                    >
                      <LogoutOutlined className='text-red-500' />
                      <span className='logout-text font-weight-bold'>
                        Log Out
                      </span>
                    </Link>
                  </div>
                }
                arrow={false}
              >
                <UserOutlined className='text-xl cursor-pointer dark:text-white transition-all hover:scale-110' />
              </Popover>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

export default Header;
