import { useState } from "react";
import URL from "url";
import { ExpressionCard } from "../../components";
import { ExpressionDescription } from "../../components/ExpressionDescription";
import { addExpressionWithRelationships, Expression } from "../../model";
import { parseWiktionaryData } from "../../model/parseWiktionaryData";

export function AddExpressionView() {
  const [prompt, setPrompt] = useState("");
  const [expression, setExpression] = useState<Expression | null>(null);
  const [submitStatus, setSubmitStatus] =
    useState<string | undefined>(undefined);
  const [error, setError] = useState<any>(undefined);

  return (
    <div className="page-with-bottom-navigation">
      <section className="padding-small scroll">
        <div className="padding-small">
          {error ? <p className="text-error">{error.message}</p> : null}
          {submitStatus ? <p className="text-meta">{submitStatus}</p> : null}
        </div>
        {expression ? (
          <ExpressionCard
            prompt={expression.prompt}
            categories={[]}
            description={<ExpressionDescription expression={expression} />}
            show_description
          />
        ) : (
          <div className="content-query">
            <label htmlFor="query">Word: </label>
            <input
              type="text"
              id="query"
              name="query"
              value={prompt}
              placeholder="Type card prompt here"
              onChange={(event) => setPrompt(event.target.value)}
            />
          </div>
        )}
      </section>
      <section className="navigation-bottom">
        {!expression ? (
          <button
            className="navigation-item bottom text-navigation grow"
            type="submit"
            disabled={prompt === ""}
            onClick={async () => {
              try {
                // `https://en.wiktionary.org/w/api.php?action=parse&format=json&prop=text&page=${query}`;
                const url = URL.format({
                  protocol: "https",
                  hostname: "en.wiktionary.org",
                  pathname: "/w/api.php",
                  query: {
                    action: "parse",
                    format: "json",
                    page: prompt,
                    prop: "text",
                    origin: "*",
                  },
                });
                const result = await fetch(url);
                const data = await result.json();
                setExpression(
                  parseWiktionaryData(prompt, data.parse?.text?.["*"] || "")
                );
              } catch (error) {
                setError(error);
              }
            }}
          >
            Fetch Wiktionary data
          </button>
        ) : (
          <>
            <button
              className="navigation-item bottom text-navigation grow"
              type="button"
              onClick={() => {
                setExpression(null);
                setSubmitStatus(undefined);
                setError(undefined);
              }}
            >
              Discard card
            </button>
            <button
              className="navigation-item bottom text-navigation grow"
              type="button"
              onClick={async () => {
                if (!expression) {
                  console.error("Attempted to add expression but none exists");
                  return;
                }
                try {
                  await addExpressionWithRelationships({
                    expression,
                    expression_set_id: 1,
                    category_ids: [],
                  });
                  setExpression(null);
                  setSubmitStatus(`Card "${expression.prompt}" saved`);
                  setError(undefined);
                } catch (error) {
                  setSubmitStatus(undefined);
                  setError(error);
                }
              }}
            >
              Save card
            </button>
          </>
        )}
      </section>
    </div>
  );
}
