import classNames from 'classnames';

import { useState } from '@wordpress/element';
import TrashIcon from 'blockbite-icons/dist/Trash';
import StarIcon from 'blockbite-icons/dist/Star';
import StarFilledIcon from 'blockbite-icons/dist/StarFilled';
import { useSelect, useDispatch } from '@wordpress/data';
import { ButtonToggleGroup } from '@components/ui/ButtonToggle';

import { ItemProps, PresetContent } from '@components/DesignPanel/types';
import { ScrollList } from '@components/ui/ScrollList';
import { Notification } from '@components/ui/Notification';
import { Button, TextControl } from '@wordpress/components';
import { findPresetById } from './useDefaultPreset';
import has from 'lodash/has';
import capitalize from 'lodash/capitalize';

export const PresetPanel = (props: any) => {
  const { name, attributes, setAttributes } = props;

  const picked = [
    'biteStyle',
    'biteMotionStyle',
    'flexStyle',
    'mediaStyle',
    'biteClass',
    'biteMotionClass',
    'flexClass',
    'mediaClass',
  ];
  const saveProps = {} as any;
  picked.forEach((prop) => {
    if (has(attributes, prop)) {
      saveProps[prop] = attributes[prop];
    }
  });

  const [newPresetName, setNewPresetName] = useState<string>('');
  const [key, setKey] = useState<number>(0);
  const [error, setError] = useState<string>('');
  const [platform, setPlatform] = useState<string>('site');

  const presets = useSelect(
    (select) => {
      // @ts-ignore
      const results = select('biteStore/presets').getFiltered(platform, name);
      return results.filter((item: ItemProps) => item.blockname === name);
    },
    [platform, name]
  );

  const { upsertItem, deleteItem, toggleDefaultItem } =
    useDispatch('biteStore/presets');

  const addPreset = async () => {
    if (newPresetName !== '') {
      try {
        await upsertItem({
          title: newPresetName,
          handle: 'preset',
          platform: platform,
          blockname: name,
          version: '1.0.0',
          is_default: false,
          content: JSON.stringify(saveProps),
        });
        setNewPresetName('');
        setError('');
      } catch (error) {
        setError('Error adding preset');
      }
    }
  };

  return (
    <div className="my-4 flex flex-col gap-x-2 gap-y-2" key={key}>
      <ButtonToggleGroup
        display="label"
        onPressedChange={(value: string) => {
          setPlatform(value);
        }}
        size="default"
        options={['site', 'blockbite'].map((option: string) => ({
          value: option,
          icon: null,
          label: capitalize(option),
        }))}
        defaultPressed={platform}
      ></ButtonToggleGroup>

      <div className="font-medium">{`Presets for ${name}`}</div>
      {platform === 'site' && (
        <>
          <TextControl
            label="Add New Preset"
            className="!mb-0"
            value={newPresetName}
            onChange={(value) => {
              setNewPresetName(value);
            }}
          />
          <Button
            variant="secondary"
            className="mb-2 h-[32px]"
            onClick={() => addPreset()}
          >
            Add
          </Button>
        </>
      )}
      {error !== '' && platform !== 'blockbite' && <span>{error}</span>}

      <ScrollList>
        {presets.map((item: ItemProps) => {
          return (
            <span
              className="isolate inline-flex w-full"
              key={`${item.id}__${item.is_default}`}
            >
              <button
                className={classNames(
                  'bg-gray-light my-2 flex w-full cursor-pointer items-center justify-between px-3 py-2 hover:bg-opacity-50'
                )}
                onClick={() => {
                  const presetValues = findPresetById(presets, item.id);
                  if (presetValues) {
                    setAttributes(presetValues as PresetContent);
                  }
                }}
              >
                <h3 className="!m-0">{item.title}</h3>
              </button>
              <button
                className="bg-gray-light my-2 flex items-center justify-center p-2 hover:bg-opacity-50"
                onClick={() => {
                  toggleDefaultItem(item).then(() => {
                    setKey((prev) => prev + 1);
                  });
                }}
              >
                {item.is_default ? (
                  <StarFilledIcon className="h-4 w-4" />
                ) : (
                  <StarIcon className="h-4 w-4" />
                )}
              </button>
              <button
                className="bg-gray-light my-2 flex items-center justify-center rounded-r-xl p-2 hover:bg-opacity-50"
                onClick={() => deleteItem(item)}
              >
                <TrashIcon className="h-4 w-4" />
              </button>
            </span>
          );
        })}
        {presets.length === 0 && (
          <Notification color="blue">
            <span>No Presets Available</span>
          </Notification>
        )}
      </ScrollList>
    </div>
  );
};

export default PresetPanel;
