"use client";

import { PlusIcon } from "lucide-react";
import { type JSX, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { TSurveyCalElement, type TSurveyElement } from "@formbricks/types/surveys/elements";
import { TSurvey } from "@formbricks/types/surveys/types";
import { TUserLocale } from "@formbricks/types/user";
import { createI18nString, extractLanguageCodes } from "@/lib/i18n/utils";
import { ElementFormInput } from "@/modules/survey/components/element-form-input";
import { AdvancedOptionToggle } from "@/modules/ui/components/advanced-option-toggle";
import { Button } from "@/modules/ui/components/button";
import { Input } from "@/modules/ui/components/input";
import { Label } from "@/modules/ui/components/label";

interface CalElementFormProps {
  readonly localSurvey: TSurvey;
  readonly element: TSurveyCalElement;
  readonly elementIdx: number;
  readonly updateElement: (elementIdx: number, updatedAttributes: Partial<TSurveyElement>) => void;
  readonly lastElement: boolean;
  readonly isInvalid: boolean;
  readonly locale: TUserLocale;
  readonly isStorageConfigured: boolean;
  readonly isExternalUrlsAllowed?: boolean;
}

export const CalElementForm = ({
  localSurvey,
  element,
  elementIdx,
  updateElement,
  isInvalid,
  locale,
  isStorageConfigured = true,
  isExternalUrlsAllowed,
}: CalElementFormProps): JSX.Element => {
  const surveyLanguageCodes = extractLanguageCodes(localSurvey.languages);
  const [isCalHostEnabled, setIsCalHostEnabled] = useState(!!element.calHost);
  const { t } = useTranslation();
  useEffect(() => {
    if (!isCalHostEnabled) {
      updateElement(elementIdx, { calHost: undefined });
    } else {
      updateElement(elementIdx, { calHost: element.calHost ?? "cal.com" });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally only reacts to the toggle; adding element.calHost/updateElement/elementIdx would loop as it writes calHost back into the survey
  }, [isCalHostEnabled]);

  return (
    <form>
      <ElementFormInput
        id="headline"
        value={element.headline}
        label={t("workspace.surveys.edit.question") + "*"}
        localSurvey={localSurvey}
        elementIdx={elementIdx}
        isInvalid={isInvalid}
        updateElement={updateElement}
        locale={locale}
        isStorageConfigured={isStorageConfigured}
        focusOnMount={!element.headline?.default || element.headline.default.trim() === ""}
        isExternalUrlsAllowed={isExternalUrlsAllowed}
      />
      <div>
        {element.subheader !== undefined && (
          <div className="inline-flex w-full items-center">
            <div className="w-full">
              <ElementFormInput
                id="subheader"
                value={element.subheader}
                label={t("common.description")}
                localSurvey={localSurvey}
                elementIdx={elementIdx}
                isInvalid={isInvalid}
                updateElement={updateElement}
                locale={locale}
                isStorageConfigured={isStorageConfigured}
                focusOnMount={!element.subheader?.default || element.subheader.default.trim() === ""}
                isExternalUrlsAllowed={isExternalUrlsAllowed}
              />
            </div>
          </div>
        )}
        {element.subheader === undefined && (
          <Button
            size="sm"
            className="mt-3"
            variant="secondary"
            type="button"
            onClick={() => {
              updateElement(elementIdx, {
                subheader: createI18nString("", surveyLanguageCodes),
              });
            }}>
            <PlusIcon className="mr-1 size-4" />
            {t("workspace.surveys.edit.add_description")}
          </Button>
        )}
        <div className="mt-5 flex flex-col gap-6">
          <div className="flex flex-col gap-3">
            <Label htmlFor="calUserName">{t("workspace.surveys.edit.cal_username")}</Label>
            <div>
              <Input
                id="calUserName"
                name="calUserName"
                value={element.calUserName}
                onChange={(e) => updateElement(elementIdx, { calUserName: e.target.value })}
              />
            </div>
          </div>

          <AdvancedOptionToggle
            isChecked={isCalHostEnabled}
            onToggle={(checked: boolean) => setIsCalHostEnabled(checked)}
            htmlId="calHost"
            description={t("workspace.surveys.edit.needed_for_self_hosted_cal_com_instance")}
            childBorder
            title={t("workspace.surveys.edit.custom_hostname")}
            customContainerClass="p-0">
            <div className="p-4">
              <div className="flex items-center gap-2">
                <Label htmlFor="calHost">{t("workspace.surveys.edit.hostname")}</Label>
                <Input
                  id="calHost"
                  name="calHost"
                  placeholder="my-cal-instance.com"
                  value={element.calHost}
                  className="bg-white"
                  onChange={(e) => updateElement(elementIdx, { calHost: e.target.value })}
                />
              </div>
            </div>
          </AdvancedOptionToggle>
        </div>
      </div>
    </form>
  );
};
