import * as React from "react";
import { Form, Flex, FormatType, useForm, Icons } from "@solace-health/ui";
import {
  Prospect,
  ProspectPayload,
  FormDataFields,
  HereFor,
  EventTypes,
} from "../types";
import { post } from "../utils/api";
import { Container, SubmitButton } from "./styles";
import { track } from "../utils/analytics";

const SearchWidget = () => {
  const urlString = window?.location?.search || "";
  const urlParams = new URLSearchParams(urlString);
  const formMethods = useForm();
  const [isSubmitting, setIsSubmitting] = React.useState(false);

  const hereForOptions = [
    { label: "Myself", value: HereFor.SELF },
    { label: "Someone Else", value: HereFor.LOVED_ONE },
  ];

  const removeNullValues = <T extends { [key: string]: unknown }>(
    obj: T
  ): Partial<T> =>
    Object.entries(obj)
      .filter(([_, v]) => v != null)
      .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});

  const onHandleSubmit = async () => {
    await formMethods.trigger();

    const hasErrors = Object.keys(formMethods.formState.errors).length > 0;
    if (hasErrors) return;

    const values = formMethods.getValues();
    const sanitizedValues = removeNullValues(values) as ProspectPayload;

    setIsSubmitting(true);
    post<Prospect>({
      path: "/api/prospects",
      body: {
        ...sanitizedValues,
        payload: {
          ...sanitizedValues,
          [FormDataFields.PatientDOB]: values[FormDataFields.PatientDOB],
        },
      },
    })
      .then((data: Prospect) => {
        urlParams.append("p_id", data.id);

        track(EventTypes.FUNNEL_ENTRY, {
          prospect_id: data.id,
        });
        const redirect = `${
          process.env.FUNNEL_URL
        }/medicare?${urlParams.toString()}`;
        window.location.href = redirect;
      })
      .finally(() => {
        setIsSubmitting(false);
      });
  };

  const onSubmit: React.MouseEventHandler = async (e) => {
    e.preventDefault();
    onHandleSubmit();
  };

  return (
    <Container>
      <Form.Container onSubmit={() => null} formMethods={formMethods}>
        <Flex gap={16} vertical>
          <Form.RadioGroup
            name={FormDataFields.HereFor}
            label="Who do you need help for?"
            options={hereForOptions}
            formOptions={{ required: true }}
            showErrorMessage={false}
          />
          <Form.Text
            name={FormDataFields.FirstName}
            formOptions={{ required: true }}
            label="First Name"
            showErrorMessage={false}
          />
          <Form.Text
            name={FormDataFields.LastName}
            formOptions={{ required: true }}
            label="Last Name"
            showErrorMessage={false}
          />
          <Form.Text
            name={FormDataFields.Email}
            formOptions={{ required: true }}
            pattern={FormatType.Email}
            label="Email"
            showErrorMessage={false}
          />
          <Form.DateTextMaskInput
            name={FormDataFields.PatientDOB}
            label="Date of Birth"
            formOptions={{ required: true }}
            showErrorMessage={false}
          />
          <SubmitButton
            htmlType="submit"
            onClick={onSubmit}
            isSubmitting={isSubmitting}
          >
            <Flex gap=".5rem" align="center">
              Get Started <Icons.Arrow color="#d9d9d9" />
            </Flex>
          </SubmitButton>
        </Flex>
      </Form.Container>
    </Container>
  );
};
export default SearchWidget;
