import React, { useState } from "react";
import { useLoaderData } from "react-router-dom";
import { Action } from "../types/Action";
import { isInEnum } from "../utils/EnumUtils";
import AuthFlow from "../components/AuthFlow";
import { ColumnLayout, Container, FileUpload, FormField, Select } from "@cloudscape-design/components";
import { getHandler } from "../handlers/HandlerRegistry";
import { DownloadMetadata } from "../handlers/DownloadFileHandler";

export interface IAuthPageLoader {
  action: Action;
}

export async function loader({ params }: any) {
  if (!isInEnum(Action, params.action)) {
    throw new Error("Not a valid action");
  }
  return { action: params.action };
}

interface SelectOption {
  label?: string;
  value?: string;
}

const selectOptions: SelectOption[] = [
  { label: "backup", value: "backup" },
  { label: "key", value: "key" },
];

export function AuthPage() {
  const { action } = useLoaderData() as IAuthPageLoader;
  const [selectedOption, setSelectedOption] = useState<SelectOption>({value: ""});

  const [files, setFiles] = useState<File[]>([]);

  const fileReady = action !== Action.UPLOAD || files.length > 0;

  let options: RequestInit = {};
  let handlerMetadata: DownloadMetadata = {
    name: selectedOption.value || "file",
    type: "dat",
  }

  if (action === Action.DELETE) {
    options = {
      method: 'delete'
    }
  }

  if (action === Action.UPLOAD) {
    if (files.length > 0) {
      const formData = new FormData();
      formData.append("file", files[0]);

      options = {
        method: 'post',
        body: formData,
      }
      console.log(options);
    }    
  }

  return (
    <Container>
      <ColumnLayout columns={1}>
        <FormField label={"Domain"} description={"Select which domain to access"} stretch>
          <Select
            selectedOption={selectedOption} 
            onChange={({ detail }) => setSelectedOption(detail.selectedOption)} 
            options={selectOptions}
          />
        </FormField>

        {action === Action.UPLOAD && 
          <FileUpload 
            value={files} 
            onChange={({ detail }) => setFiles(detail.value)} 
            i18nStrings={{ 
              uploadButtonText:e=>e?"Choose files":"Choose file",
              dropzoneText:e=>e?"Drop files to upload":"Drop file to upload",
              removeFileAriaLabel:e=>`Remove file ${e+1}`,
              limitShowFewer:"Show fewer files",
              limitShowMore:"Show more files",
              errorIconAriaLabel:"Error" 
            }}
          />
        }
        
        {fileReady && selectedOption.value && 
          <AuthFlow 
            action={action} 
            subdomain={selectedOption.value} 
            responseHandler={getHandler(action)} 
            options={options} 
            handlerMetadata={handlerMetadata}
          />
        }
      </ColumnLayout>
      
    </Container>
  );
}