import { useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import {
  Button,
  TextControl,
  ToggleControl,
  ToolbarDropdownMenu,
} from '@wordpress/components';
import { DropdownOption } from '@wordpress/components/build-types/dropdown-menu/types';
import { truncateString } from '@utils/strings';

import PageIcon from 'blockbite-icons/dist/Pencil1';

import { Icon as IconComp } from '@components/ui/Icon';

interface LinkPickerProps {
  linkUrl: string;
  linkTitle: string;
  linkTarget: string;
  linkTile: string;
  showLinkTile: boolean;
  parentCallback: (inlineSvg: any) => void;
}

interface Link {
  id: number;
  post_type: string;
  title: string;
  label?: string;
  url: string;
}

function LinkList({
  linkData,
  onActiveLink,
}: {
  linkData: Link[];
  onActiveLink: (l: Link) => void;
}) {
  const list: DropdownOption[] = [];
  if (linkData == null) return [];

  linkData.forEach((l) => {
    // let usedIcon: IconType = () => <PageIcon />;
    let title = `${l.label || l.title} – ${l.url}`;

    /*
    switch (l.post_type) {
      case 'page':
        usedIcon = PageIcon;
        break;
      case 'post':
        usedIcon = PageIcon;
        break;
      case 'blockbites':
        usedIcon = PageIcon;
        break;
      case 'custom':
        usedIcon = PageIcon;
        break;
      default:
        usedIcon = PageIcon;
    }
    */
    // truncate title if too long
    title = truncateString(title, 72);

    list.push({
      title,
      onClick: () => onActiveLink(l),
    });
  });

  return list;
}

export default function LinkPicker({
  linkUrl,
  linkTitle,
  linkTarget,
  linkTile,
  showLinkTile,
  parentCallback,
}: LinkPickerProps) {
  const [isError] = useState(false);
  const [isEditing, setIsEditing] = useState(true);
  const [stateUrl, setStateUrl] = useState('');
  const [stateTitle, setStateTitle] = useState('');
  const [stateTarget, setStateTarget] = useState(false);
  const [stateTile, setStateTile] = useState(false);
  const [activeKeyword, setActiveKeyword] = useState('');
  const [linkData, setLinkData] = useState([]);
  const [activeLink, setActiveLink] = useState(null);

  useEffect(() => {
    if (linkTarget === '_blank') {
      setStateTarget(true);
    }
    if (linkTile) {
      setStateTile(true);
    }
    if (linkUrl) {
      setStateUrl(linkUrl);
      setIsEditing(false);
    }
    if (linkTitle) {
      setStateTitle(linkTitle);
    }
  }, []);

  // get link object
  const getLinkObject = () => {
    const link = {
      linkTile: '',
      linkTarget: '_self',
    } as {
      linkTitle?: string;
      linkUrl?: string;
      linkTile?: string;
      linkTarget?: string;
    };

    if (stateTitle) {
      link['linkTitle'] = stateTitle;
    }
    if (stateUrl) {
      link['linkUrl'] = stateUrl;
    }
    link.linkTile = linkTile;
    link.linkTarget = stateTarget ? '_blank' : '_self';

    return link;
  };

  useEffect(() => {
    let newLink = { ...getLinkObject() };
    parentCallback(newLink);
  }, [stateTitle, stateUrl, stateTarget, stateTile]);

  useEffect(() => {
    if (activeKeyword === '') return;
    setLinkData(null);
    apiFetch({
      path: `/blockbite/v1/block-helpers/get-links/${activeKeyword}`,
    }).then((links: Link[]) => {
      if (links.length) {
        setLinkData([...links]);
      } else {
        setLinkData([]);
      }
    });
  }, [activeKeyword]);

  useEffect(() => {
    if (activeLink?.url != null && activeLink?.url !== '') {
      const newLink = { ...getLinkObject() };
      newLink.linkTitle = activeLink.title;
      newLink.linkUrl = activeLink.url;
      setStateTitle(activeLink.title);
      setStateUrl(activeLink.url);
      parentCallback(newLink);
    }
  }, [activeLink]);

  const linksList = [
    ...LinkList({
      linkData: [
        ...(linkData ? linkData : []),
        ...(activeKeyword
          ? [
              {
                id: 0,
                post_type: 'custom',
                title: '',
                label: 'Custom link',
                url: activeKeyword,
              },
            ]
          : []),
      ],
      onActiveLink: (link) => {
        setActiveLink({ ...link });
        setIsEditing(false);
        setActiveKeyword('');
      },
    }),
  ];

  return (
    <ToolbarDropdownMenu
      icon={<IconComp icon={PageIcon} />}
      label="Change link"
      controls={isEditing ? linksList : []}
      children={() => {
        return (
          <div className="min-w-48 p-2">
            {isError && <span style={{ color: 'red' }}>{isError}</span>}
            {isEditing ? (
              <TextControl
                label={__('Search link', 'blockbitelinks')}
                value={activeKeyword}
                placeholder="Example: About"
                onChange={(value) => setActiveKeyword(value)}
                help={__('Type a post, page, title', 'blockbitelinks')}
                autoComplete="off"
              />
            ) : (
              <div>
                <span className="font-semibold">{stateTitle}</span>
                {stateTitle && stateUrl && <br />}
                <span>{stateUrl}</span>
                <div className="mt-4">
                  <Button
                    variant="secondary"
                    onClick={() => setIsEditing(true)}
                  >
                    Edit link
                  </Button>
                </div>
              </div>
            )}
            {showLinkTile && (
              <ToggleControl
                label="Link as Tile"
                help={
                  stateTile
                    ? 'Make the whole area clickable'
                    : 'Make only the button clickable'
                }
                checked={stateTile}
                onChange={(value) => setStateTile(value)}
              />
            )}
          </div>
        );
      }}
    />
  );
}
