import { useContext, useEffect, useState } from '@wordpress/element';
import { ScrollList } from '@components/ui/ScrollList';
import { DesignContext } from '@components/DesignPanel/DesignStore';
import { Button } from '@components/ui/Button';
import { Badge } from '@components/ui/Badge';

import EraserIcon from 'blockbite-icons/dist/Eraser';
import Pencil1Icon from 'blockbite-icons/dist/Pencil1';
import ClipboardIcon from 'blockbite-icons/dist/Clipboard';
import ClipboardCopy from 'blockbite-icons/dist/ClipboardCopy';

import { useStore } from 'zustand';
import { PanelCurrentProps } from '@components/DesignPanel/types';
import { DesignClassToStore } from '@components/DesignPanel/DesignStoreActions';
import { mergeModifierPanels } from '@components/DesignPanel/Helpers';
import { ResponsiveOptions } from '@components/DesignPanel/ResponsivePanel';

import ChevronLeftIcon from 'blockbite-icons/dist/ChevronLeft';
import TailwindIcon from 'blockbite-icons/dist/Tailwind';
import { ButtonToggle, ButtonToggleGroup } from '@components/ui/ButtonToggle';
import { Icon } from '@components/ui/Icon';

export const PanelCurrent: React.FC<PanelCurrentProps> = ({
  panels,
  setCurrentTab = null,
  setPanelId = null,
}) => {
  const store = useStore(useContext(DesignContext));
  const {
    currentDesign,
    currentClass,
    setCurrentDesign,
    setDesignReset,
    setCurrentControl,
  } = store;

  // create a copy of list
  const [list, setList] = useState([]);

  /**
   * Synchronise the currentDesign with extra attributes
   * like icons, etc
   */
  useEffect(() => {
    const filteredCurrentDesign = currentDesign.filter((d: any) => d?.id);

    const newList = mergeModifierPanels(filteredCurrentDesign, panels);

    setList(newList);
    // Using an empty dependency array results in list being empty when "current" tab is programmatically opened
  }, [currentDesign]);

  const removeAllDesign = () => {
    setCurrentDesign([]);
    DesignClassToStore([], store);
    setDesignReset(true);
    setList([]);
  };

  const removeOneDesign = (index: number) => {
    const newDesign = [...currentDesign];
    newDesign.splice(index, 1);

    if (newDesign.length === 0) {
      setCurrentDesign([]);
      setDesignReset(true);
      setList([]);
    } else {
      setCurrentDesign(newDesign);
      DesignClassToStore(newDesign, store);
      setList([...newDesign]);
    }
  };

  const copyAllDesign = () => {
    const design = [...currentDesign];
    const designString = JSON.stringify(design, null, 2);
    navigator.clipboard.writeText(designString);
  };

  const pasteAllDesign = () => {
    navigator.clipboard.readText().then((text) => {
      try {
        const design = JSON.parse(text);
        setCurrentDesign(design);
        DesignClassToStore(design, store);
        setList(design);
      } catch (e) {
        console.error('Error parsing clipboard text', e);
      }
    });
  };

  const CopyPastEraseButtons = [
    {
      label: 'Copy Design',
      value: 'copyDesign',
      icon: ClipboardIcon,
    },
    {
      label: 'Paste Design',
      value: 'pasteDesign',
      icon: ClipboardCopy,
    },
    {
      label: 'Remove Design',
      value: 'removeDesign',
      icon: EraserIcon,
    },
  ];

  return (
    <div className="py-4">
      <div className="flex items-center gap-2">
        <ButtonToggle
          label="Back"
          defaultPressed={null}
          icon={ChevronLeftIcon}
          value="back"
          onPressedChange={() => {
            setCurrentTab('design');
          }}
        />
        <div className="font-medium">Current Styles</div>
      </div>
      <ButtonToggleGroup
        options={CopyPastEraseButtons}
        defaultPressed={null}
        className="mt-2"
        display="icon"
        onPressedChange={(value) => {
          switch (value) {
            case 'copyDesign':
              copyAllDesign();
              break;
            case 'pasteDesign':
              pasteAllDesign();
              break;
            case 'removeDesign':
              removeAllDesign();
              break;
          }
        }}
      />
      <ScrollList>
        {list.map((design: any, index: number) => {
          const currentResponsive = ResponsiveOptions.find(
            (option: any) => option.value === design.screen
          );

          return (
            <div
              key={`style__${index}`}
              className="hover:bg-gray-light border-gray-light relative mb-1 flex flex-col gap-1 border-b-2 p-2 text-[12px]"
            >
              <div className="flex items-center gap-1">
                {currentResponsive && (
                  <div className="font-medium">{currentResponsive.icon}</div>
                )}
                <div className="font-medium"> {design.control}</div>
              </div>

              <div className="max-w-[128px] overflow-hidden text-[10px] font-medium uppercase opacity-50">
                {design.label}
              </div>
              <div className="flex justify-between gap-4">
                <Badge>
                  {design.selector}
                  {design.value}
                </Badge>
                {design.interaction && <span>{design.interaction}</span>}
                <div className="absolute right-2 top-0 flex max-w-[60px] items-center gap-1">
                  <Button
                    className="hover:bg-primary"
                    size="small"
                    onClick={() => {
                      setCurrentTab('design');
                      const panelControls = design.panelControls;

                      const control = panelControls.find((c: any) => {
                        const controlModifiers = c.modifiers || [];
                        const subcontrols = c.subcontrols || [];

                        return (
                          c.id === design.id ||
                          controlModifiers.find(
                            (m: any) => m.id === design.id
                          ) ||
                          subcontrols.find((s: any) => s.id === design.id)
                        );
                      });
                      setPanelId(design.panelId);
                      setCurrentControl(control);
                    }}
                  >
                    <Pencil1Icon />
                  </Button>
                  <Button
                    className="hover:bg-primary"
                    size="small"
                    onClick={() => removeOneDesign(index)}
                  >
                    <EraserIcon />
                  </Button>
                </div>
              </div>
            </div>
          );
        })}
      </ScrollList>

      <div className="flex items-center justify-center">
        <Icon className="h-9 w-9" icon={TailwindIcon} />
        <small className="w-[90%]">{currentClass}</small>
      </div>
    </div>
  );
};

export default PanelCurrent;
