'use client';
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { Text } from '@/components/ui/text';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import CommonImage from '@/components/common/CommonImage';
import Benchmark from './utilities/Benchmark';
import ReleaseNotes from './utilities/ReleaseNotes';
import TimezoneSwitcher from './utilities/TimezoneSwitcher';
import { Switch } from '@/components/ui/switch';
import { store } from '@/store/store';
import { globalApiPost } from '@/services/global';
import { API_ENDPOINTS } from '@/constants';
import { hydrateSession } from '@/store/slices/sessionSlice'; // Import hydrateSession

const Utilities = () => {
  const dispatch = useDispatch();
  const user = store.getState().session.user;
  const [isCountryPanelVisible, setIsCountryPanelVisible] = useState(false);
  const [selectedCountry, setSelectedCountry] = useState<string>('');

  const toggleCountryPanel = () => {
    setIsCountryPanelVisible((prev) => !prev);
  };
  const [isOpen, setIsOpen] = useState(false);

  const [isMenuHorizontal, setIsMenuHorizontal] = useState(false);

  const getValidCountry = (value: string) => {
    if (!value || value.includes('undefined')) {
      return 'Select Timezone';
    }
    return value;
  };

  useEffect(() => {
    const userMenuType = user?.menu_type;
    if (userMenuType === '2') {
      setIsMenuHorizontal(true);
    } else if (userMenuType === '1') {
      setIsMenuHorizontal(false);
    }
  }, [user, isMenuHorizontal]);

  const menuHandleToggle = (checked: boolean) => {
    setIsMenuHorizontal(checked);

    const userMenuType = checked ? '2' : '1';
    globalApiPost(API_ENDPOINTS.USER.UPDATE_MENU_VIEW, {
      menu_type: userMenuType,
    })
      .then((response: any) => {
        const userData: any = response || {};

        const updatedUser = {
          ...userData,
          menu_type: userMenuType,
        };

        if (userMenuType === '2') {
          setIsMenuHorizontal(true);
        } else if (userMenuType === '1') {
          setIsMenuHorizontal(false);
        }

        dispatch(
          hydrateSession({
            user: updatedUser.user,
          }),
        );
      })
      .catch((error) => {
        console.error('Error updating user settings:', error);
      });
  };

  return (
    <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
      <DropdownMenuTrigger asChild>
        <Text className="shortCodeWidget">
          <CommonImage
            src={'/footer/icon-shortcut-utility.png'}
            width={24}
            height={24}
            alt={'Shortcuts'}
            classname={'Shortcuts'}
          />
          Shortcuts &amp; Utilities
        </Text>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        className="p-4 gap-4 flex flex-row utilities-widget"
        aria-describedby={undefined}
        onInteractOutside={(e) => e.preventDefault()}
      >
        <Text className="left-panel-utilities">
          {/* Country Panel Trigger */}
          <Text
            weight="semibold"
            onClick={toggleCountryPanel}
            className={`relative theme-select-text mb-2 cursor-pointer text-sm ${
              isCountryPanelVisible ? 'active' : ''
            } `}
          >
            <Text className="selectedCountry">
              {getValidCountry(selectedCountry).length > 33
                ? getValidCountry(selectedCountry).slice(0, 33) + '...'
                : getValidCountry(selectedCountry)}
            </Text>
            <CommonImage
              src="/footer/theme-arrow.webp"
              width={12}
              height={5}
              alt="arrow"
              classname="theme-arrow"
            />
          </Text>
          {/* <Benchmark /> */}
          {/* <ReleaseNotes /> */}
          <div
            className={`menu-control-arrangement-widget ${isMenuHorizontal ? 'horizontal-menu-active' : 'vertical-menu-active'}`}
          >
            Menu
            <Switch
              checked={isMenuHorizontal}
              onCheckedChange={menuHandleToggle}
            />
          </div>
        </Text>
        <TimezoneSwitcher
          setSelectedCountry={(country: string) => setSelectedCountry(country)}
          toggleCountryPanel={toggleCountryPanel}
          isCountryPanelVisible={isCountryPanelVisible}
        />

        <div className="shortcut-close-area">
          <div className="shortcut-left-icon">
            <CommonImage
              src={'/footer/icon-shortcut-utility.png'}
              width={24}
              height={24}
              alt={'Shortcuts'}
              classname={'Shortcuts'}
            />
            <span>Shortcuts &amp; Utilities</span>
          </div>
          <div
            className="close-shortcut-utility"
            onClick={() => setIsOpen(false)}
          >
            <CommonImage
              src={'/main/cross-arrow.webp'}
              width={15}
              height={15}
              alt={'close'}
              classname={'close'}
            />
          </div>
        </div>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
export default Utilities;
