import React, { useEffect, useState } from "react";
import { useForm, FormProvider } from "react-hook-form";
import apiFetch from "@wordpress/api-fetch";
import DesignTab from "./designTab";
import { BorderRadiusType, FontType } from "../../context/themeProvider";
import SubmitButton from "../form-elements/buttons/submitButton";
import ResetButton from "../form-elements/buttons/resetButton";
import { ObjectEncryptor } from "../../util/ObjectEncrypter";
import Modal from "../modal/modal";
import AlarmWarningLine from "../../resources/icons/alarm-warning-line";

export type FreemiumConfiguration = {
  primaryColor?: string;
  font?: FontType;
  borderRadius?: BorderRadiusType;
  email?: string;
  lawFirmName?: string;
};

type DefaultValues = {
  hex: string;
  borderState: string;
  font: string;
  freemiumHash: string;
  lawFirmName: string;
  emailAddress: string;
  confirmEmail: string;
};

const defaultValues: DefaultValues = {
  hex: "#0066FF",
  borderState: "Rounded",
  font: "Overpass",
  freemiumHash: "",
  lawFirmName: "",
  emailAddress: "",
  confirmEmail: "",
};

export default function LeadboosterDesign() {
  const methods = useForm<DefaultValues>({ mode: "onChange", defaultValues });
  const {
    handleSubmit,
    trigger,
    setValue,
    getValues,
    watch,
    reset,
    formState: { isDirty },
  } = methods;
  const [hasFetched, setHasFetched] = useState(false);
  const [isSubmitting] = useState(false);
  const [isChangeModalOpen, setIsChangeModalOpen] = useState(false);
  const [isResetModalOpen, setIsResetModalOpen] = useState(false);
  const lawFirmName = watch("lawFirmName");
  const emailAddress = watch("emailAddress");
  const hex = watch("hex");
  const font = watch("font");
  const borderState = watch("borderState");

  // Load existing options once
  useEffect(() => {
    if (hasFetched) return;
    apiFetch({ path: "/react-settings-page/v1/options", method: "GET" })
      .then((resp: any) => {
        setValue("lawFirmName", resp.justin_legal_lawFirmName);
        setValue("emailAddress", resp.justin_legal_emailAddress);
        setValue("confirmEmail", resp.justin_legal_emailAddress);
        setValue("hex", resp.justin_legal_hex || "");
        setValue("font", resp.justin_legal_font);
        setValue("borderState", resp.justin_legal_borderState);
        setValue("freemiumHash", resp.justin_legal_hash);
        setHasFetched(true);
      })
      .catch((err) => console.error("Error fetching design options:", err));
  }, [hasFetched, setValue]);

  // Save handler preserves Kanzleidaten
  const onSubmit = async (data: DefaultValues) => {
    try {
      const hash = await ObjectEncryptor.encrypt<FreemiumConfiguration>(
        {
          email: data.emailAddress,
          lawFirmName: data.lawFirmName,
          primaryColor: getValues("hex"),
          font: getValues("font") as FontType,
          borderRadius: getValues("borderState") as BorderRadiusType,
        },
        "3530942237"
      );
      await apiFetch({
        path: "/react-settings-page/v1/options",
        method: "POST",
        data: {
          justin_legal_lawFirmName: lawFirmName,
          justin_legal_emailAddress: emailAddress,
          justin_legal_hex: data.hex,
          justin_legal_font: data.font,
          justin_legal_borderState: data.borderState,
          justin_legal_hash: hash,
        },
      });
    } catch (err) {
      console.error("Error saving design options:", err);
    }
  };

  const validateAndSubmit = async () => {
    const valid = await trigger(undefined, { shouldFocus: false });
    if (!valid) return;
    return handleSubmit(onSubmit)();
  };

  if (!hasFetched) {
    return (
      <div className="flex justify-center items-center h-screen">
        Loading...
      </div>
    );
  }

  const onReset = () => {
    const lawFirmName = getValues("lawFirmName");
    const emailAddress = getValues("emailAddress");
    const freemiumHash = getValues("freemiumHash");

    reset({
      lawFirmName,
      emailAddress,
      confirmEmail: emailAddress,
      freemiumHash,
      hex: defaultValues.hex,
      borderState: defaultValues.borderState,
      font: defaultValues.font,
    });

    setIsResetModalOpen(false);
  };

  // when accVal != defVal
  const canReset =
    hex !== defaultValues.hex ||
    font !== defaultValues.font ||
    borderState !== defaultValues.borderState;

  return (
    <FormProvider {...methods}>
      <div
        id="tabbedForm"
        className="font-sans bg-white sm:px-8 py-8 px-4 rounded-xl border"
      >
        <DesignTab />

        <Modal
          isOpen={isResetModalOpen}
          onClose={() => setIsResetModalOpen(false)}
          onClickAccept={async () => {
            onReset();
            await validateAndSubmit();
          }}
          textAcceptButton="Bestätigen"
          textCancelButton="Abbrechen"
          closeOnAccept={true}
          onClickCancel={() => setIsResetModalOpen(false)}
          title=""
          description={
            <div className="flex flex-col">
              <div className="bg-red-500 bg-interactive-alarm-hover/80 w-fit mx-auto rounded-lg p-4">
                <AlarmWarningLine className="w-8 h-8 fill-white" />
              </div>

              <h2 className="text-2xl mt-4 font-bold"> Design Zurücksetzen </h2>
              <p className="mt-4">
                Sobald Sie bestätigen, werden Ihre Einstellungen auf den Justin
                Legal Standard zurückgesetzt.
              </p>
            </div>
          }
        />

        <div className="mt-12 flex justify-center">
          <ResetButton
            onReset={() => setIsResetModalOpen(true)}
            isDirty={canReset}
          />
        </div>

        <Modal
          isOpen={isChangeModalOpen}
          onClose={() => setIsChangeModalOpen(false)}
          onClickAccept={async () => {
            await validateAndSubmit();
            setIsChangeModalOpen(false);
          }}
          textAcceptButton="Bestätigen"
          textCancelButton="Abbrechen"
          closeOnAccept={true}
          onClickCancel={() => setIsChangeModalOpen(false)}
          title=""
          description={
            <div className="flex flex-col">
              <div className="bg-red-500 bg-interactive-alarm-hover/80 w-fit mx-auto rounded-lg p-4">
                <AlarmWarningLine className="w-8 h-8 fill-white" />
              </div>

              <h2 className="text-2xl mt-4 font-bold"> Design Anpassen </h2>
              <p className="mt-4">
                Sobald Sie bestätigen, werden Ihre Änderungen auf allen
                Formularen und Widgets aktiv.
              </p>
            </div>
          }
        />

        <SubmitButton
          isSubmitting={isSubmitting}
          onSubmit={async () => {
            setIsChangeModalOpen(true);
          }}
        />
      </div>
    </FormProvider>
  );
}
