"use client";

import * as Collapsible from "@radix-ui/react-collapsible";
import { CheckIcon } from "lucide-react";
import React from "react";
import { UseFormReturn } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { TSurveyStyling, TSurveyType } from "@formbricks/types/surveys/types";
import { TWorkspaceStyling } from "@formbricks/types/workspace";
import { cn } from "@/lib/cn";
import { STYLE_DEFAULTS } from "@/lib/styling/constants";
import { getDarkDisplayColor } from "@/lib/styling/dark-mode";
import { CardArrangementTabs } from "@/modules/ui/components/card-arrangement-tabs";
import { CardWidthTabs } from "@/modules/ui/components/card-width-tabs";
import { ColorPicker } from "@/modules/ui/components/color-picker";
import { FormControl, FormDescription, FormField, FormItem, FormLabel } from "@/modules/ui/components/form";
import { useStylingAppearance } from "@/modules/ui/components/styling-appearance";
import { ColorField, DimensionInput } from "@/modules/ui/components/styling-fields";
import { Switch } from "@/modules/ui/components/switch";

type CardStylingSettingsProps = {
  readonly open: boolean;
  readonly setOpen: React.Dispatch<React.SetStateAction<boolean>>;
  readonly isSettingsPage?: boolean;
  readonly surveyType?: TSurveyType;
  readonly disabled?: boolean;
  readonly form: UseFormReturn<TWorkspaceStyling | TSurveyStyling>;
};

export const CardStylingSettings = ({
  isSettingsPage = false,
  surveyType,
  disabled,
  open,
  setOpen,
  form,
}: CardStylingSettingsProps) => {
  const { t } = useTranslation();
  const appearance = useStylingAppearance();
  const isAppSurvey = surveyType === "app";
  const surveyTypeDerived = isAppSurvey ? "App" : "Link";

  const linkCardArrangement = form.watch("cardArrangement.linkSurveys") ?? "straight";
  const appCardArrangement = form.watch("cardArrangement.appSurveys") ?? "straight";
  const linkSurveyCardWidth = form.watch("linkSurveyCardWidth") ?? "default";
  const hideProgressBar = form.watch("hideProgressBar");

  return (
    <Collapsible.Root
      open={open}
      onOpenChange={(openState) => {
        if (disabled) return;
        setOpen(openState);
      }}
      className="w-full rounded-lg border border-slate-300 bg-white">
      <Collapsible.CollapsibleTrigger
        asChild
        disabled={disabled}
        className={cn(
          "w-full cursor-pointer rounded-lg hover:bg-slate-50",
          disabled && "cursor-not-allowed opacity-60 hover:bg-white"
        )}>
        <div className="inline-flex px-4 py-4">
          {!isSettingsPage && (
            <div className="flex items-center pr-5 pl-2">
              <CheckIcon
                strokeWidth={3}
                className="size-7 rounded-full border border-green-300 bg-green-100 p-1.5 text-green-600"
              />
            </div>
          )}

          <div>
            <p className={cn("font-semibold text-slate-800", isSettingsPage ? "text-sm" : "text-base")}>
              {t("workspace.surveys.edit.card_styling")}
            </p>
            <p className={cn("mt-1 text-slate-500", isSettingsPage ? "text-xs" : "text-sm")}>
              {t("workspace.surveys.edit.style_the_survey_card")}
            </p>
          </div>
        </div>
      </Collapsible.CollapsibleTrigger>

      <Collapsible.CollapsibleContent className="flex flex-col overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">
        <hr className="py-1 text-slate-600" />

        <div className="grid grid-cols-2 gap-4 p-6 pt-2">
          {/* Roundness */}
          <DimensionInput
            form={form}
            name="roundness"
            label={t("workspace.surveys.edit.roundness")}
            description={t("workspace.surveys.edit.roundness_description")}
          />

          <ColorField
            form={form}
            name="cardBackgroundColor.light"
            label={t("workspace.surveys.edit.card_background_color")}
            description={t("workspace.surveys.edit.card_background_color_description")}
            fallbackColor={STYLE_DEFAULTS.cardBackgroundColor?.light || "#ffffff"}
            containerClass="max-w-xs"
          />

          <ColorField
            form={form}
            name="cardBorderColor.light"
            label={t("workspace.surveys.edit.card_border_color")}
            description={t("workspace.surveys.edit.card_border_color_description")}
            fallbackColor={STYLE_DEFAULTS.cardBorderColor?.light || "#f8fafc"}
            containerClass="max-w-xs"
          />

          <FormField
            control={form.control}
            name={"cardArrangement"}
            render={() => (
              <FormItem className="col-span-2">
                <div>
                  <FormLabel>
                    {t("workspace.surveys.edit.card_arrangement_for_survey_type_derived", {
                      surveyTypeDerived: surveyTypeDerived,
                    })}
                  </FormLabel>
                </div>
                <FormControl>
                  <CardArrangementTabs
                    key={isAppSurvey ? "app" : "link"}
                    surveyType={isAppSurvey ? "app" : "link"}
                    activeCardArrangement={isAppSurvey ? appCardArrangement : linkCardArrangement}
                    setActiveCardArrangement={(value, type) => {
                      if (type === "app") {
                        // "cardless" is not offered for app surveys, so it can be safely excluded here.
                        if (value !== "cardless") {
                          form.setValue("cardArrangement.appSurveys", value);
                        }
                      } else {
                        form.setValue("cardArrangement.linkSurveys", value);
                      }
                    }}
                  />
                </FormControl>
              </FormItem>
            )}
          />

          {!isAppSurvey && (
            <FormField
              control={form.control}
              name="linkSurveyCardWidth"
              render={() => (
                <FormItem className="col-span-2">
                  <div>
                    <FormLabel>{t("workspace.surveys.edit.card_width_for_link_surveys")}</FormLabel>
                  </div>
                  <FormControl>
                    <CardWidthTabs
                      activeCardWidth={linkSurveyCardWidth}
                      setActiveCardWidth={(value) => {
                        form.setValue("linkSurveyCardWidth", value);
                      }}
                    />
                  </FormControl>
                </FormItem>
              )}
            />
          )}
        </div>

        {/* Highlight Border Section */}
        <div className="flex flex-col gap-4 p-6 pt-0">
          <hr className="text-slate-600" />
          <div className="my-2">
            <FormField
              control={form.control}
              name="highlightBorderColor"
              render={({ field }) => (
                <FormItem className="flex w-full flex-col gap-4 gap-y-0">
                  <div className="flex items-center gap-2">
                    <FormControl>
                      <Switch
                        id="highlightBorderColor"
                        checked={!!field.value}
                        onCheckedChange={(checked) => {
                          if (!checked) {
                            field.onChange(null);
                            return;
                          }
                          field.onChange({
                            light: STYLE_DEFAULTS.highlightBorderColor?.light,
                          });
                        }}
                      />
                    </FormControl>
                    <div>
                      <FormLabel className="text-sm font-normal">
                        {t("workspace.surveys.edit.add_highlight_border")}
                      </FormLabel>
                      <FormDescription className="text-xs">
                        {t("workspace.surveys.edit.add_highlight_border_description")}
                      </FormDescription>
                    </div>
                  </div>

                  {!!field.value && (
                    <FormControl>
                      <ColorPicker
                        color={
                          appearance === "dark"
                            ? (field.value?.dark ??
                              getDarkDisplayColor(form.watch(), "highlightBorderColor.light") ??
                              "")
                            : (field.value?.light ?? STYLE_DEFAULTS.highlightBorderColor?.light)
                        }
                        onChange={(color: string) =>
                          field.onChange({
                            ...field.value,
                            [appearance]: color,
                          })
                        }
                        containerClass="w-1/2"
                      />
                    </FormControl>
                  )}
                  {!!field.value && appearance === "dark" && (
                    <div className="text-xs text-slate-500">
                      {field.value.dark ? (
                        <button
                          type="button"
                          className="underline underline-offset-2 hover:text-slate-700"
                          onClick={() => field.onChange({ ...field.value, dark: null })}>
                          {t("workspace.look.appearance_use_automatic")}
                        </button>
                      ) : (
                        <span>{t("workspace.look.appearance_automatic")}</span>
                      )}
                    </div>
                  )}
                </FormItem>
              )}
            />
          </div>
        </div>

        {/* Progress Bar Section */}
        <div className="flex flex-col gap-6 p-6 pt-0">
          <hr className="text-slate-600" />
          <div className="flex flex-col gap-4">
            <div className="my-2">
              <FormField
                control={form.control}
                name="hideProgressBar"
                render={({ field }) => (
                  <FormItem className="flex w-full items-center gap-2 gap-y-0">
                    <FormControl>
                      <Switch
                        id="hideProgressBar"
                        checked={!!field.value}
                        onCheckedChange={(checked) => field.onChange(checked)}
                      />
                    </FormControl>

                    <div>
                      <FormLabel className="text-sm font-normal">
                        {t("workspace.surveys.edit.hide_progress_bar")}
                      </FormLabel>
                      <FormDescription className="text-xs">
                        {t("workspace.surveys.edit.disable_the_visibility_of_survey_progress")}
                      </FormDescription>
                    </div>
                  </FormItem>
                )}
              />
            </div>
            {!hideProgressBar && (
              <div className="grid grid-cols-2 gap-4">
                <ColorField
                  form={form}
                  name="progressTrackBgColor.light"
                  label={t("workspace.look.advanced_styling_field_track_bg")}
                  description={t("workspace.look.advanced_styling_field_track_bg_description")}
                />
                <ColorField
                  form={form}
                  name="progressIndicatorBgColor.light"
                  label={t("workspace.look.advanced_styling_field_indicator_bg")}
                  description={t("workspace.look.advanced_styling_field_indicator_bg_description")}
                />
                <DimensionInput
                  form={form}
                  name="progressTrackHeight"
                  label={t("workspace.look.advanced_styling_field_track_height")}
                  description={t("workspace.look.advanced_styling_field_track_height_description")}
                />
              </div>
            )}
          </div>
        </div>
      </Collapsible.CollapsibleContent>
    </Collapsible.Root>
  );
};
