'use client';
import React, { useEffect, useState } from 'react';
import { useTheme } from 'next-themes';
import { Text } from '@/components/ui/text';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { API_ENDPOINTS } from '@/constants';
import { store } from '@/store/store';
import { globalApiPost } from '@/services/global/globalApiCalls';
import { UnknownRecord } from '@/types';
import CommonImage from '@/components/common/CommonImage';

const themeClass: UnknownRecord = {
  'white-color-theme': 'marble',
  'black-color-theme': 'graphite',
  'darkblue-color-theme': 'sapphire',
  'purple-color-theme': 'lavender',
  'lightblue-color-theme': 'azure',
  'dark-color-theme': 'dark',
};

const ThemeSwitcher = () => {
  const selectedTheme = store.getState().session?.panelTheme?.themeColor;

  const { theme, setTheme, systemTheme } = useTheme();
  const current = theme === 'system' ? systemTheme : theme;
  const [isThemePanelVisible, setIsThemePanelVisible] = useState(false);

  const updateTheme = async (theme: string) => {
    await globalApiPost(API_ENDPOINTS.USER.UPDATE_THEME, {
      user_id: String(store.getState().session?.user?.id),
      theme: theme,
    });
  };

  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    setMounted(true);
    if (selectedTheme) {
      setTheme(themeClass[selectedTheme]);
    }
  }, [selectedTheme]);

  const toggleThemePanel = () => {
    setIsThemePanelVisible((prev) => !prev);
  };

  const themeIcons: Record<string, string> = {
    dark: 'fa-solid fa-moon',
    marble: 'fa-solid fa-sun',
  };

  return (
    <Text className="theme-footer-widget-ui m-0 p-0">
      <DropdownMenu
        open={isThemePanelVisible}
        onOpenChange={setIsThemePanelVisible}
      >
        <DropdownMenuTrigger asChild>
          <Text className="theme-choose-name">
            {/* Theme Panel Trigger */}
            <Text
              weight="semibold"
              onClick={toggleThemePanel}
              className={`m-0 p-0 items-center relative flex gap-2 theme-select-text mb-2 cursor-pointer text-sm ${
                isThemePanelVisible ? 'active' : ''
              }`}
            >
              Theme:
              <div
                className={`flex gap-2 border items-center rounded-md pl-2 pr-4 pt-1 pb-1 text-theme-name theme-${mounted ? current : ''}`}
              >
                {mounted ? (
                  <i
                    className={
                      themeIcons[current ?? ''] || 'fa-solid fa-circle'
                    }
                  />
                ) : (
                  <i className="fa-solid fa-sun" />
                )}

                {mounted ? current : 'Marble'}
                <span className="caret"></span>
              </div>
            </Text>
          </Text>
        </DropdownMenuTrigger>
        <DropdownMenuContent className="p-4 gap-4 flex flex-row theme-selection-name ml-72">
          <ul className="theme-list flex gap-4 ">
            {Object.entries(themeClass).map(([key, value]) => (
              <li
                key={value}
                onClick={() => {
                  setTheme(value);
                  setIsThemePanelVisible(false);
                  updateTheme(key);
                }}
                className={`border pl-4 pr-4 pt-1 pb-1 rounded-md theme-item cursor-pointer ${
                  value === theme ? 'active' : ''
                } theme-${value.charAt(0).toLowerCase() + value.slice(1)}`}
              >
                {value === theme ? (
                  <span className="check-ok">
                    <CommonImage
                      src={'/main/arrow-theme-tick.webp'}
                      width={12}
                      height={11}
                      alt={'theme-ok'}
                      classname={'theme-ok'}
                    />
                  </span>
                ) : null}
                {value === 'dark'
                  ? 'Dark Mode'
                  : value.charAt(0).toUpperCase() + value.slice(1)}
              </li>
            ))}
          </ul>
        </DropdownMenuContent>
      </DropdownMenu>
    </Text>
  );
};
export default ThemeSwitcher;
