"use client";

import { createId } from "@paralleldrive/cuid2";
import { TrashIcon } from "lucide-react";
import React, { useCallback } from "react";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { TSurveyQuota } from "@formbricks/types/quota";
import { TSurvey, TSurveyVariable } from "@formbricks/types/surveys/types";
import { findVariableUsedInLogic, isUsedInQuota, isUsedInRecall } from "@/modules/survey/editor/lib/utils";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";
import { Button } from "@/modules/ui/components/button";
import { FormControl, FormField, FormItem, FormProvider } from "@/modules/ui/components/form";
import { Input } from "@/modules/ui/components/input";
import { Label } from "@/modules/ui/components/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/modules/ui/components/select";

interface SurveyVariablesCardItemProps {
  variable?: TSurveyVariable;
  localSurvey: TSurvey;
  setLocalSurvey: React.Dispatch<React.SetStateAction<TSurvey>>;
  mode: "create" | "edit";
  quotas: TSurveyQuota[];
}

export const SurveyVariablesCardItem = ({
  variable,
  localSurvey,
  setLocalSurvey,
  mode,
  quotas,
}: SurveyVariablesCardItemProps) => {
  const { t } = useTranslation();
  const form = useForm<TSurveyVariable>({
    defaultValues: variable ?? {
      id: createId(),
      name: "",
      type: "number",
      value: 0,
    },
    mode: "onChange",
  });

  const { errors } = form.formState;
  const isNameError = !!errors.name?.message;
  const variableType = form.watch("type");

  const editSurveyVariable = useCallback(
    (data: TSurveyVariable) => {
      setLocalSurvey((prevSurvey) => {
        const updatedVariables = prevSurvey.variables.map((v) => (v.id === data.id ? data : v));
        return { ...prevSurvey, variables: updatedVariables };
      });
    },
    [setLocalSurvey]
  );

  const createSurveyVariable = (data: TSurveyVariable) => {
    setLocalSurvey({
      ...localSurvey,
      variables: [...localSurvey.variables, data],
    });
    form.reset({
      id: createId(),
      name: "",
      type: "number",
      value: 0,
    });
  };

  // Removed auto-submit effect

  const onVariableDelete = (variableToDelete: TSurveyVariable) => {
    const elements = getElementsFromBlocks(localSurvey.blocks);
    const elementIdx = findVariableUsedInLogic(localSurvey, variableToDelete.id);

    if (elementIdx !== -1) {
      toast.error(
        t(
          "environments.surveys.edit.variable_is_used_in_logic_of_question_please_remove_it_from_logic_first",
          {
            variable: variableToDelete.name,
            questionIndex: elementIdx + 1,
          }
        )
      );
      return;
    }
    const recallElementIdx = isUsedInRecall(localSurvey, variableToDelete.id);
    if (recallElementIdx === -2) {
      toast.error(
        t("environments.surveys.edit.variable_used_in_recall_welcome", { variable: variableToDelete.name })
      );
      return;
    }

    if (recallElementIdx === elements.length) {
      toast.error(
        t("environments.surveys.edit.variable_used_in_recall_ending_card", {
          variable: variableToDelete.name,
        })
      );
      return;
    }

    if (recallElementIdx !== -1) {
      toast.error(
        t("environments.surveys.edit.variable_used_in_recall", {
          variable: variableToDelete.name,
          questionIndex: recallElementIdx + 1,
        })
      );
      return;
    }

    const quotaIdx = quotas.findIndex((quota) => isUsedInQuota(quota, { variableId: variableToDelete.id }));

    if (quotaIdx !== -1) {
      toast.error(
        t("environments.surveys.edit.variable_is_used_in_quota_please_remove_it_from_quota_first", {
          variableName: variableToDelete.name,
          quotaName: quotas[quotaIdx].name,
        })
      );
      return;
    }

    setLocalSurvey((prevSurvey) => {
      const updatedVariables = prevSurvey.variables.filter((v) => v.id !== variableToDelete.id);
      return { ...prevSurvey, variables: updatedVariables };
    });
  };

  if (mode === "edit" && !variable) {
    return null;
  }

  return (
    <div>
      <FormProvider {...form}>
        <form
          className="mt-5"
          onSubmit={form.handleSubmit((data) => {
            if (mode === "create") {
              createSurveyVariable(data);
            } else {
              editSurveyVariable(data);
            }
          })}>
          {mode === "create" && (
            <Label htmlFor="headline">{t("environments.surveys.edit.add_variable")}</Label>
          )}

          <div className="mt-2 flex w-full items-center gap-2">
            {/* Name field: update on blur */}
            <FormField
              control={form.control}
              name="name"
              rules={{
                pattern: {
                  value: /^[a-z0-9_]+$/,
                  message: t(
                    "environments.surveys.edit.only_lower_case_letters_numbers_and_underscores_are_allowed"
                  ),
                },
                validate: (value) => {
                  if (mode === "create" && localSurvey.variables.find((v) => v.name === value)) {
                    return t(
                      "environments.surveys.edit.variable_name_is_already_taken_please_choose_another"
                    );
                  }
                  if (mode === "edit" && variable && variable.name !== value) {
                    if (localSurvey.variables.find((v) => v.name === value)) {
                      return t(
                        "environments.surveys.edit.variable_name_is_already_taken_please_choose_another"
                      );
                    }
                  }
                  if (!/^[a-z]/.test(value)) {
                    return t("environments.surveys.edit.variable_name_must_start_with_a_letter");
                  }
                  const hiddenFieldIds = localSurvey.hiddenFields?.fieldIds ?? [];
                  if (hiddenFieldIds.some((id) => id.toLowerCase() === value.toLowerCase())) {
                    return t("environments.surveys.edit.variable_name_conflicts_with_hidden_field");
                  }
                },
              }}
              render={({ field }) => (
                <FormItem className="flex-1">
                  <FormControl>
                    <Input
                      {...field}
                      isInvalid={isNameError}
                      placeholder={t("environments.surveys.edit.field_name_eg_score_price")}
                      onBlur={mode === "edit" ? () => form.handleSubmit(editSurveyVariable)() : undefined}
                    />
                  </FormControl>
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="type"
              render={({ field }) => (
                <FormItem
                  onBlur={mode === "edit" ? () => form.handleSubmit(editSurveyVariable)() : undefined}>
                  <Select
                    {...field}
                    onValueChange={(value) => {
                      form.setValue("value", value === "number" ? 0 : "");
                      field.onChange(value);
                    }}>
                    <SelectTrigger className="h-10 w-24">
                      <SelectValue placeholder={t("environments.surveys.edit.select_type")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="number">{t("common.number")}</SelectItem>
                      <SelectItem value="text">{t("common.text")}</SelectItem>
                    </SelectContent>
                  </Select>
                </FormItem>
              )}
            />

            <p className="text-slate-600">=</p>

            {/* Value field: update on blur */}
            <FormField
              control={form.control}
              name="value"
              render={({ field }) => (
                <FormItem className="flex-1">
                  <FormControl>
                    <Input
                      {...field}
                      onChange={(e) =>
                        field.onChange(variableType === "number" ? Number(e.target.value) : e.target.value)
                      }
                      placeholder={t("environments.surveys.edit.initial_value")}
                      type={variableType === "number" ? "number" : "text"}
                      onBlur={mode === "edit" ? () => form.handleSubmit(editSurveyVariable)() : undefined}
                    />
                  </FormControl>
                </FormItem>
              )}
            />

            {/* Create / Delete buttons */}
            {mode === "create" && (
              <Button variant="secondary" type="submit" className="h-10 whitespace-nowrap">
                {t("environments.surveys.edit.add_variable")}
              </Button>
            )}
            {mode === "edit" && variable && (
              <Button
                variant="ghost"
                type="button"
                size="sm"
                className="whitespace-nowrap"
                onClick={() => onVariableDelete(variable)}>
                <TrashIcon className="h-4 w-4" />
              </Button>
            )}
          </div>

          {isNameError && <p className="mt-1 text-sm text-red-500">{errors.name?.message}</p>}
        </form>
      </FormProvider>
    </div>
  );
};
