import apiFetch from '@wordpress/api-fetch';
import { ToggleSwitch } from '@components/ui/ToggleSwitch';

type DynamicBlockSupportProps = {
  blockname: string;
  defaultChecked: boolean;
  updateDynamicBlocks: (blocks: []) => void;
};

type Response = {
  saved: boolean;
  allowed_dynamic: [];
};

const DynamicBlockSupport = ({
  blockname,
  defaultChecked,
  updateDynamicBlocks,
}: DynamicBlockSupportProps) => {
  const onSave = (checked: boolean) => {
    apiFetch({
      path: `/blockbite/v1/block-support/dynamic`,
      method: 'POST',
      data: { blockname: blockname, allowed: checked },
    }).then((response: Response) => {
      if (response.saved) {
        updateDynamicBlocks(response.allowed_dynamic);
      }
    });
  };

  return (
    <div className="flex flex-col gap-4 p-4">
      <h4 className="font-bold">Blockbite Support</h4>
      <p className="flex gap-2">
        This is a dynamic block
        <a
          target="_blank"
          className="text-primary underline"
          href="https://developer.wordpress.org/block-editor/getting-started/fundamentals/static-dynamic-rendering/"
        >
          Read More
        </a>
      </p>
      <ToggleSwitch
        label={`Dynamic Block ${defaultChecked ? 'Enabled' : 'Disabled'}`}
        checked={defaultChecked}
        onChange={(checked) => onSave(checked)}
      />
    </div>
  );
};

export default DynamicBlockSupport;
