import { FormEvent } from "react";
import { Navigate, useNavigate } from "react-router";

import { Button } from "@/components/ui/Button/Button";
import { ChoiceList } from "@/components/ui/CheckboxAndRadio/ChoiceList";
import { Form } from "@/components/ui/Form/Form";
import { FormLayout } from "@/components/ui/Form/FormLayout";
import { t } from "@/i18n/translate";

import { useElectionCreateContext } from "../hooks/useElectionCreateContext";

/*
 * NOTE: DSO is currently unsupported by Abacus, so it is disabled by default
 */
export function CountingMethodType() {
  const { state, dispatch } = useElectionCreateContext();
  const navigate = useNavigate();

  // if no election data was stored, navigate back to beginning
  if (!state.election) {
    return <Navigate to="/elections/create" />;
  }

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    dispatch({
      type: "SET_COUNTING_METHOD_TYPE",
      // This is hardcoded to CSO until we have support for DSO
      countingMethod: "CSO",
    });
    await navigate("/elections/create/number-of-voters");
  }

  return (
    <section className="md">
      <Form
        title={t("election.voting_method_type.title") + " " + state.election.location}
        onSubmit={(e) => void handleSubmit(e)}
      >
        <FormLayout>
          <FormLayout.Section>
            <p>
              {t("election.voting_method_type.description", {
                election: state.election.name,
                location: state.election.location,
              })}
            </p>

            <ChoiceList>
              <ChoiceList.Radio
                id="cso"
                label={t("election.voting_method_type.cso")}
                checked={true}
                onChange={() => {
                  /*
              We need this to suppress an error because we explicitly set the `checked` property.
              We'll actually implement this handler once we support DSO
            */
                }}
              >
                {t("election.voting_method_type.cso_description")}
              </ChoiceList.Radio>
              <ChoiceList.Radio
                id="dso"
                label={
                  <span>
                    {t("election.voting_method_type.dso")} (<b>{t("election.voting_method_type.dso_not_supported")}</b>)
                  </span>
                }
                checked={false}
                disabled
              >
                {t("election.voting_method_type.dso_description")}
              </ChoiceList.Radio>
            </ChoiceList>
          </FormLayout.Section>

          <FormLayout.Controls>
            <Button type="submit">{t("next")}</Button>
          </FormLayout.Controls>
        </FormLayout>
      </Form>
    </section>
  );
}
