import * as React from "react";
import { useBlockProps, InspectorControls } from "@wordpress/block-editor";
import type { BlockEditProps } from "@wordpress/blocks";
import { useState, useMemo } from "@wordpress/element";
import {
  Button,
  PanelBody,
  CheckboxControl,
  Placeholder,
  __experimentalVStack as VStack,
  __experimentalInputControl as InputControl,
} from "@wordpress/components";
import { __, sprintf } from '@wordpress/i18n';
import config from "../context/config";
import type { Title, TitleSelection } from "../types";
import { TitleControls } from "../components/title-controls/TitleControls";
import { WidgetPreview } from "../components/widget-preview/WidgetPreview";
import { JustwatchProvider } from "../context/context";
import { generateShortcode } from "./save";

export default ({
	attributes,
	setAttributes,
}: BlockEditProps<TitleSelection>): JSX.Element => {
  const { settings } = config || {};
  const { id, objectType } = attributes;
  const [tmpSelection, setTmpSelection] = useState<TitleSelection>();
  const [isEditing, setIsEditing] = useState(!id);
  const [showShortcode, setShowShortcode] = useState(false);
  const [copied, setCopied] = useState(false);

  const code = generateShortcode(attributes);

  const handleCopy = () => {
    navigator.clipboard.writeText(code).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000); // Reset after 2 sec
    });
  };

  const handleConfirm = () => {
    if (!tmpSelection) {
      return;
    }
    handleSelect(tmpSelection);
    setTmpSelection(undefined);
    setIsEditing(false);
  };

  const isValid = !!id && !!objectType;
  const preview = useMemo(() =>
    !isEditing && isValid && (
      !showShortcode ? (
        <WidgetPreview {...attributes} />
      ) : (
        <Placeholder
          icon="shortcode"
          label={__("Justwatch Shortcode", "justwatch-partner-integrations")}
        >
          <div style={{ position: "relative", width: "100%" }}>
            <InputControl
              __unstableInputWidth="100%"
              __next40pxDefaultSize
              type="readonly"
              value={code}
              onMouseDown={(e) => e.preventDefault()}
              onChange={() => {}}
              suffix={(
                <Button
                  icon={copied ? "yes" : "clipboard"}
                  onClick={handleCopy}
                  variant='tertiary'
                />
              )}
            />
          </div>
        </Placeholder>
      )
    ),
    [isEditing, showShortcode, code, copied]
  );

  const handleSelect = (titleSelection: TitleSelection) => {
    const { objectType, id, idType, meta } = titleSelection;
    const imdbId = idType === "imdb" ? String(id) : "";
    const tmdbId = idType === "tmdb" ? String(id) : "";
    const justwatchId = idType === "justwatch" ? Number(id) : 0;

    const selectedTitle: Title = {
      ...(attributes.meta || {}),
      objectType,
      justwatchId,
      imdbId,
      tmdbId,
      ...meta,
    } as Title;

    const newTitleSelection = { ...titleSelection, meta: selectedTitle };

    setAttributes(newTitleSelection);
  };

  return (
    <JustwatchProvider {...settings}>
      {!isEditing && (
        <InspectorControls>
          <PanelBody title="Justwatch Settings">
            {!config?.settings?.apiKey && (
              <p className="jw-error" dangerouslySetInnerHTML={{
                __html: sprintf(
                  __(
                    "Please provide a valid Justwatch API key in the %s.",
                    "justwatch"
                  ),
                  `<a href="${config.settingsUrl}" target="_blank" rel="noopener noreferrer">plugin settings</a>`
                )
              }} />
            )}
            <TitleControls
              titleSelection={attributes}
              onTitleSelectionChange={handleSelect}
            />
            <CheckboxControl
              label={__("View Shortcode", "justwatch-partner-integrations")}
              checked={showShortcode}
              onChange={setShowShortcode}
            />
          </PanelBody>
        </InspectorControls>
      )}
      {isEditing && (
        <Placeholder
            instructions={__(
              "Enter a movie or TV show title to search for it on Justwatch.",
              "justwatch"
            )}
            icon="search"
            label={__("Select a title", "justwatch-partner-integrations")}
          >
            <div style={{ position: "relative", width: "100%" }}>
              <VStack>
                <TitleControls
                  titleSelection={tmpSelection}
                  onTitleSelectionChange={(titleSelection) => {
                    setTmpSelection(titleSelection);
                  }}
                />
                <div style={{ width: 'max-content' }}>
                  <Button
                    variant="primary"
                    onClick={handleConfirm}
                    disabled={!tmpSelection}
                  >
                    {__("Confirm", "justwatch-partner-integrations")}
                  </Button>
                </div>
              </VStack>
            </div>
        </Placeholder>
      )}
      <div {...useBlockProps()}>
        {preview}
      </div>
    </JustwatchProvider>
  );
};