import React from "react";
import styled from "styled-components";
import {
  IChangeEvent, ISubmitEvent, ErrorSchema, Widget,
} from "@rjsf/core";
import { SignupForm } from "@models/Signup";
import Checkboxes from "@components/Widgets/Checkbox/Checkboxes";
import RadioButtonWidget from "@components/Widgets/RadioButton/RadioButtonWidget";
import { TextSection, ChangeLanguageButton } from "@components/index";
import colors from "@theme/colors";
import FormWrapper from "@views/common/FormWrapper";
import Loader from "@components/Loader";
import { buildFormSchema, buildUISchema, signupFormQuestionToQuestion } from "./FormUtils";
import { useTranslation } from "../../i18n";

const customWidgets = {
  radio: RadioButtonWidget as unknown as Widget,
  checkboxes: Checkboxes as unknown as Widget,
};

interface SignUpPageViewProps {
  signUpForm?: SignupForm;
  formData: any;
  onChange: (e: IChangeEvent<unknown>, es?: ErrorSchema) => unknown;
  onSubmit: (e: ISubmitEvent<unknown>) => unknown;
}

const StyledSection = styled(TextSection)`
  & > div {
    & > span {
      color: ${colors.orange1};
    }
  }

  & > aside {
    justify-content: start;

    li {
      padding-bottom: 0.3rem;
    }

    .reserved {
      color: ${colors.blue1};
    }
  }

  ${Loader} {
    margin: auto;
  }
`;

const LngButton = styled(ChangeLanguageButton)`
  align-self: flex-end;
  margin-right: 1rem;
`;

const SignUpPageView: React.FC<SignUpPageViewProps> = ({
  signUpForm,
  formData,
  onChange,
  onSubmit,
}) => {
  const { i18n, t } = useTranslation();
  const startDate = new Date(signUpForm?.start_time);
  const endDate = new Date(signUpForm?.end_time);
  const isFi = i18n.language === "fi";
  const {
    title, startDateStr, endDateStr,
  } = {
    title: isFi ? signUpForm?.title_fi : signUpForm?.title_en,
    startDateStr: startDate.toLocaleString(isFi ? "fi-FI" : "en-GB"),
    endDateStr: endDate.toLocaleString(isFi ? "fi-FI" : "en-GB"),
  };

  const renderList = () => (
    <aside>
      <div>
        <h6>
          {t("Ilmoittautuneet")} {signUpForm.quota > 0 && (` (${signUpForm.signups.length}/${signUpForm.quota})`)}:
        </h6>
        <ol data-e2e="signup-list">
          {signUpForm.signups.map((s, idx) => (
            <li key={idx} className={signUpForm.quota && idx + 1 > signUpForm.quota ? "reserved" : ""}>{s}</li>
          ))}
        </ol>
      </div>
    </aside>
  );

  let form: JSX.Element;
  let signups: JSX.Element = null;
  if (!signUpForm) {
    // Show loader if in edit mode and form has not yet loaded.
    // For normal signup page, form is always defined on this level.
    form = (
      <Loader $color={colors.darkBlue} />
    );
  } else if (startDate > new Date()) {
    form = (
      <>
        <p>{t("Ilmoittautuminen ei ole vielä auki!")}</p>
        <p>{`${t("Se aukeaa")}  ${startDateStr}`}.</p>
      </>
    );
  } else if (new Date() > endDate) {
    form = (
      <p>{t("Ilmoittauminen on umpeutunut!")}</p>
    );
    signups = renderList();
  } else {
    const formTitle = signUpForm.id ? signUpForm.title_fi : "Loading...";
    const questions = signUpForm.questions.map((q) => signupFormQuestionToQuestion(q, i18n.language));
    form = (
      <>
        <p>{`${t("Ilmoittautuminen sulkeutuu")} ${endDateStr}`}.</p>
        <FormWrapper
          schema={buildFormSchema(questions, formTitle) as unknown}
          uiSchema={buildUISchema(questions)}
          formData={formData}
          widgets={customWidgets}
          idPrefix="rjsf"
          onChange={onChange}
          onSubmit={onSubmit}
        />
      </>
    );
    signups = renderList();
  }

  return (
    <>
      <LngButton />
      <StyledSection>
        <h1>
          {title}
        </h1>

        <div>
          {form}
        </div>
        {signups}
      </StyledSection>
    </>
  );
};

export default SignUpPageView;
