import {
  PanelRow,
  TextControl,
  ToggleControl,
  Button,
} from '@wordpress/components';

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

export default function BiteLinkPanel({
  linkUrl,
  linkTitle,
  linkTarget,
  linkTile,
  showLinkTile,
  parentCallback,
}) {
  const [stateUrl, setStateUrl] = useState('');
  const [stateTitle, setStateTitle] = useState('');
  const [stateTarget, setStateTarget] = useState(false);
  const [stateTile, setStateTile] = useState(false);

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

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

  // get link object
  const getLinkObject = () => {
    const link: {
      linkTitle?: string;
      linkUrl?: string;
      linkTile?: boolean;
      linkTarget?: string;
    } = {};
    if (stateTitle) {
      link.linkTitle = stateTitle;
    }
    if (stateUrl) {
      link.linkUrl = stateUrl;
    }
    link.linkTile = linkTile;
    link.linkTarget = stateTarget ? '_blank' : '_self';

    return link;
  };

  // reset link
  const removeLink = () => {
    const newLink = { ...getLinkObject() };
    newLink.linkTitle = '';
    newLink.linkUrl = '';
    setStateUrl('');
    setStateTitle('');
    parentCallback(newLink);
  };

  return (
    <>
      <PanelRow>
        <fieldset>
          <TextControl
            label={__('Title', 'blockbite-icon')}
            value={stateTitle}
            onChange={(value) => setStateTitle(value)}
            help={__('Change your button title...', 'blockbite-icon')}
          />
          <TextControl
            label={__('Url', 'blockbite-icon')}
            value={stateUrl}
            onChange={(value) => setStateUrl(value)}
            help={__('Change your button url...', 'blockbite-icon')}
          />
          <Button variant="secondary" onClick={removeLink}>
            Clear link
          </Button>
        </fieldset>
      </PanelRow>
      <PanelRow>
        <ToggleControl
          label="Open in tab"
          help={stateTarget ? 'Open in tab' : 'Within site'}
          checked={stateTarget}
          onChange={(value) => setStateTarget(value)}
        />
      </PanelRow>
      {showLinkTile && (
        <PanelRow>
          <ToggleControl
            label="Link as Tile"
            help={
              stateTile
                ? 'Make the whole area clickable'
                : 'Make only the button clickable'
            }
            checked={stateTile}
            onChange={(value) => setStateTile(value)}
          />
        </PanelRow>
      )}
    </>
  );
}
