import * as React from "react";
import { Modal, Button } from "@wordpress/components";
import { useState, useRef, useEffect, useContext } from "@wordpress/element";
import type { TitleSelection } from "../../types";
import { TitleControls } from "../title-controls/TitleControls";
import { __, sprintf } from "@wordpress/i18n";
import JustWatchContext from "../../context/context";
import config from "../../context/config";

export type TitleDialogProps = {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (selection: TitleSelection | undefined) => void;
  titleSelection?: TitleSelection;
};

export const TitleDialog = ({
  isOpen,
  onClose,
  onConfirm
}: TitleDialogProps): JSX.Element => {
    const [titleSelection, setTitleSelection] = useState<TitleSelection>();
    const inputRef = useRef<HTMLInputElement>(null);
    const settings = useContext(JustWatchContext);
    useEffect(() => {
        if (isOpen) {
            // Reset the title selection state
            setTitleSelection(undefined);

            // Focus the input field if the ref is available
            if (inputRef.current) {
                inputRef.current.focus();
                inputRef.current.value = ""; // Clear the input value
            }
        }
    }, [isOpen]);

    return isOpen ? (
      <Modal
        isDismissible={true}
        title={__("Select a title", "justwatch-partner-integrations")}
        onRequestClose={onClose}
        size="medium"
      >
        <div>
          {!settings.apiKey && (
            <p className="jw-error" dangerouslySetInnerHTML={{
              __html: sprintf(
                __(
                  "Please provide a valid Justwatch API key in the %s.",
                  "justwatch-partners"
                ),
                `<a href="${config.settingsUrl || '#'}" target="_blank" rel="noopener noreferrer">plugin settings</a>`
              )
            }} />
          )}
          <p>Enter a movie or TV show title to search for it on Justwatch.</p>
          <TitleControls
            titleSelection={titleSelection}
            onTitleSelectionChange={setTitleSelection}
            inputRef={inputRef}
          />
        </div>
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <Button variant="secondary" onClick={onClose}>
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={() => {
              onConfirm(titleSelection);
            }}
            disabled={!titleSelection?.id}
          >
            {__("Confirm", 'justwatch-partner-integrations')}
          </Button>
        </div>
      </Modal>
    ) : <></>;
};

export default TitleDialog;