import { useEffect, useState } from "react";
import {
  ActionFunctionArgs,
  LoaderFunctionArgs,
  useLoaderData,
} from "react-router";
import Uppy from "@uppy/core";
import Dashboard from "@uppy/dashboard";
import Form from "@uppy/form";
import Tus from "@uppy/tus";
import { FormRouter, FormSection } from "#components/forms";
import { InputHidden } from "#components/forms/inputs";
import { PageSkeleton, createAccountPageLoader } from "#components/pages";

import "@uppy/dashboard/dist/style.min.css";
import "@uppy/core/dist/style.min.css";

interface IProps {
  service?: string;
  profileID?: string;
}

export function Component() {
  const { service, profileID } = useLoaderData() as IProps;
  const [fileList, changeFileList] = useState<unknown[]>();
  const title = "Upload file";
  const heading = "Upload File";

  useEffect(() => {
    (async () => {
      try {
        const uppy = new Uppy({
          restrictions: {
            maxTotalFileSize: 2 * 1024 * 1024 * 1024,
            maxNumberOfFiles: 10,
            minNumberOfFiles: 1,
          },
        })
          .use(Dashboard, {
            note: "Up to 10 files permitted.",
            fileManagerSelectionType: "both",
            target: "#upload",
            // inline: true,
            inline: false,
            trigger: "#upload-button",
            theme: "dark",
          })
          .use(Tus, {
            // endpoint: 'https://tusd.tusdemo.net/files/',
            endpoint: "http://localhost:1080/files/",
            retryDelays: [0, 1000, 3000, 5000],
          })
          .use(Form, {
            resultName: "uppyResult",
            target: "#upload-form",
            submitOnSuccess: false,
          });

        uppy.on("complete", ({ successful }) => {
          const files = successful?.map(
            (file) => file.meta.name
          );

          changeFileList(files);
        });
      } catch (error) {
        console.error(error);
      }
    })();
  }, []);

  return (
    <PageSkeleton name="upload" title={title} heading={heading}>
      <div className="upload-view">
        <FormRouter
          id="upload-form"
          className="form"
          encType="multipart/form-data"
          method="POST"
          submitButton={() => "Finish"}
        >
          <FormSection>
            {Boolean(service && profileID) && (
              <>
                <InputHidden
                  id="service"
                  className="form__input"
                  name="service"
                  defaultValue={service}
                />
                <InputHidden
                  id="user"
                  className="form__input"
                  name="user"
                  defaultValue={profileID}
                />
              </>
            )}
          </FormSection>

          <FormSection>
            <label className="form__label" htmlFor="title">
              Title
            </label>
            <input
              className="form__input"
              type="text"
              name="title"
              id="title"
              maxLength={50}
              required
            />
            <small className="subtitle">example, "February 2020 Rewards"</small>
          </FormSection>

          <FormSection>
            <label className="form__label" htmlFor="content">
              Description
            </label>
            <textarea
              name="content"
              id="content"
              maxLength={5000}
              cols={48}
              rows={4}
              wrap="soft"
            ></textarea>
            <small className="subtitle">
              Specify what the file/archive is, where the original data can be
              found, include relevant keys/passwords, etc.
            </small>
          </FormSection>

          <ul id="file-list">
            {fileList?.map((name, index) => (
              <li key={index}>{name as string}</li>
            ))}
          </ul>

          <div id="upload-button" className="upload-button">
            Add files
          </div>
        </FormRouter>

        <div id="upload"></div>
      </div>
    </PageSkeleton>
  );
}

Component.displayName = "PostsUploadPage";

export const loader = createAccountPageLoader(async function loader({
  request,
}: LoaderFunctionArgs): Promise<IProps> {
  throw new Error("Not implemented");
  const searchParams = new URL(request.url).searchParams;

  const service = searchParams.get("service")?.trim();
  const profileID = searchParams.get("user")?.trim();

  return {
    service,
    profileID,
  };
});

export async function action({ request }: ActionFunctionArgs) {
  throw new Error("Not implemented");
  if (request.method !== "POST") {
    throw new Error(`Unknown method "${request.method}".`);
  }

  const formData = await request.formData();

  const service = (formData.get("service") as string | null)?.trim();
  const profileID = (formData.get("user") as string | null)?.trim();
  const content = (formData.get("content") as string | null)?.trim();
}
