"use client";

import { RotateCcwIcon } from "lucide-react";
import Link from "next/link";
import React, { useEffect, useMemo, useState } from "react";
import { UseFormReturn, useForm } from "react-hook-form";
import toast from "react-hot-toast";
import { Trans, useTranslation } from "react-i18next";
import { type TCustomCssStored } from "@formbricks/types/custom-css";
import { TSurvey, TSurveyStyling } from "@formbricks/types/surveys/types";
import { TWorkspaceStyling } from "@formbricks/types/workspace";
import { COLOR_DEFAULTS, STYLE_DEFAULTS, getSuggestedColors } from "@/lib/styling/constants";
import { type TStylingAppearance } from "@/lib/styling/dark-mode";
import { type TCustomCssValidationState } from "@/modules/custom-css/components/lib/validation";
import { SurveyCustomCssCard } from "@/modules/custom-css/components/survey-custom-css-card";
import { type TSurveyCustomCssEditorConfig } from "@/modules/custom-css/components/types";
import { type TWorkspaceWithoutCustomCss } from "@/modules/custom-css/lib/types";
import { FormStylingSettings } from "@/modules/survey/editor/components/form-styling-settings";
import { LogoSettingsCard } from "@/modules/survey/editor/components/logo-settings-card";
import { AlertDialog } from "@/modules/ui/components/alert-dialog";
import { BackgroundStylingCard } from "@/modules/ui/components/background-styling-card";
import { Button } from "@/modules/ui/components/button";
import { CardStylingSettings } from "@/modules/ui/components/card-styling-settings";
import {
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormProvider,
} from "@/modules/ui/components/form";
import {
  DarkContrastWarnings,
  StylingAppearanceProvider,
  StylingAppearanceToggle,
} from "@/modules/ui/components/styling-appearance";
import { Switch } from "@/modules/ui/components/switch";

interface StylingViewProps {
  readonly workspaceId: string;
  readonly workspace: TWorkspaceWithoutCustomCss;
  readonly localSurvey: TSurvey;
  readonly setLocalSurvey: React.Dispatch<React.SetStateAction<TSurvey>>;
  readonly colors: string[];
  readonly styling: TSurveyStyling | null;
  readonly setStyling: React.Dispatch<React.SetStateAction<TSurveyStyling | null>>;
  readonly localStylingChanges: TSurveyStyling | null;
  readonly setLocalStylingChanges: React.Dispatch<React.SetStateAction<TSurveyStyling | null>>;
  readonly isUnsplashConfigured: boolean;
  readonly isCxMode: boolean;
  readonly isStorageConfigured: boolean;
  /** Which palette the form edits and the preview shows. Only app surveys can render dark (D4). */
  readonly appearance?: TStylingAppearance;
  readonly setAppearance?: (appearance: TStylingAppearance) => void;
  readonly customCssEditor: TSurveyCustomCssEditorConfig;
  readonly customCssValidation: TCustomCssValidationState;
  /** The survey's Custom CSS as last persisted. */
  readonly savedCustomCss: TCustomCssStored | null;
}

export const StylingView = ({
  colors,
  workspaceId,
  workspace,
  localSurvey,
  setLocalSurvey,
  setStyling,
  styling,
  localStylingChanges,
  setLocalStylingChanges,
  isUnsplashConfigured,
  isCxMode,
  isStorageConfigured = true,
  appearance = "light",
  setAppearance,
  customCssEditor,
  customCssValidation,
  savedCustomCss,
}: StylingViewProps) => {
  const workspaceBasePath = `/workspaces/${workspace.id}`;
  const { t } = useTranslation();

  const savedWorkspaceStyling = workspace.styling as Partial<TWorkspaceStyling> | null;

  // Strip null/undefined values so they don't override STYLE_DEFAULTS.
  const cleanWorkspace = savedWorkspaceStyling
    ? Object.fromEntries(Object.entries(savedWorkspaceStyling).filter(([, v]) => v != null))
    : {};
  const cleanSurvey = localSurvey.styling
    ? Object.fromEntries(Object.entries(localSurvey.styling).filter(([, v]) => v != null))
    : {};

  const form = useForm<TSurveyStyling>({
    defaultValues: {
      ...STYLE_DEFAULTS,
      ...cleanWorkspace,
      ...cleanSurvey,
    },
  });

  const overwriteThemeStyling = form.watch("overwriteThemeStyling");
  const setOverwriteThemeStyling = (value: boolean) => form.setValue("overwriteThemeStyling", value);

  const [formStylingOpen, setFormStylingOpen] = useState(false);
  const [logoSettingsOpen, setLogoSettingsOpen] = useState(false);
  const [cardStylingOpen, setCardStylingOpen] = useState(false);
  const [stylingOpen, setStylingOpen] = useState(false);
  const [confirmResetStylingModalOpen, setConfirmResetStylingModalOpen] = useState(false);
  const [confirmSuggestColorsOpen, setConfirmSuggestColorsOpen] = useState(false);
  const [customCssOpen, setCustomCssOpen] = useState(false);
  // Only app surveys render dark (D4), so a link survey edits and previews base CSS only.
  const effectiveAppearance = localSurvey.type === "app" ? appearance : "light";

  const handleSuggestColors = () => {
    const currentBrandColor =
      form.getValues().brandColor?.light ?? STYLE_DEFAULTS.brandColor?.light ?? COLOR_DEFAULTS.brandColor;
    const suggested = getSuggestedColors(currentBrandColor);

    for (const [key, value] of Object.entries(suggested)) {
      form.setValue(key as keyof TSurveyStyling, value, { shouldDirty: true });
      // The dark palette derives from the new light colors, so stale dark overrides are cleared.
      if (key.endsWith(".light")) {
        form.setValue(key.replace(/\.light$/, ".dark") as keyof TSurveyStyling, null, { shouldDirty: true });
      }
    }

    // Footer link color auto-adjusts for contrast when unset; clear any override so it
    // follows the freshly suggested palette instead of a stale custom value.
    form.setValue("footerLinkColor", undefined, { shouldDirty: true });

    toast.success(t("workspace.look.suggested_colors_applied_please_save"));
    setConfirmSuggestColorsOpen(false);
  };

  const onResetThemeStyling = () => {
    const { allowStyleOverwrite: _allowStyleOverwrite, ...baseStyling } = workspace.styling ?? {};

    setStyling({
      ...baseStyling,
      overwriteThemeStyling: true,
    });

    form.reset({
      ...baseStyling,
      overwriteThemeStyling: true,
    });

    setConfirmResetStylingModalOpen(false);
    toast.success(t("workspace.surveys.edit.styling_set_to_theme_styles"));
  };

  useEffect(() => {
    if (!overwriteThemeStyling) {
      setFormStylingOpen(false);
      setLogoSettingsOpen(false);
      setCardStylingOpen(false);
      setStylingOpen(false);
      setCustomCssOpen(false);
    }
  }, [overwriteThemeStyling]);

  useEffect(() => {
    const subscription = form.watch((data) => {
      setLocalSurvey((prev) => ({
        ...prev,
        styling: {
          ...prev.styling,
          ...(data as TSurveyStyling),
        },
      }));
    });

    return () => subscription.unsubscribe();
  }, [form, setLocalSurvey]);

  const defaultWorkspaceStyling = useMemo(() => {
    const { styling: workspaceStyling } = workspace;
    const { allowStyleOverwrite: _allowStyleOverwrite, ...baseStyling } = workspaceStyling ?? {};

    return baseStyling;
  }, [workspace]);

  const handleOverwriteToggle = (value: boolean) => {
    // survey styling from the server is surveyStyling, it could either be set or not
    // if its set and the toggle is turned off, we set the local styling to the server styling

    setOverwriteThemeStyling(value);

    // if the toggle is turned on, we set the local styling to the workspace styling
    if (value) {
      if (!styling) {
        // copy the workspace styling to the survey styling
        setStyling({
          ...defaultWorkspaceStyling,
          overwriteThemeStyling: true,
        });
        return;
      }

      // if there are local styling changes, we set the styling to the local styling changes that were previously stored
      if (localStylingChanges) {
        setStyling(localStylingChanges);
      }
      // if there are no local styling changes, we set the styling to the workspace styling
      else {
        setStyling({
          ...defaultWorkspaceStyling,
          overwriteThemeStyling: true,
        });
      }
    }

    // if the toggle is turned off, we store the local styling changes and set the styling to the workspace styling
    else {
      // copy the styling to localStylingChanges
      setLocalStylingChanges(styling);

      // copy the workspace styling to the survey styling
      setStyling({
        ...defaultWorkspaceStyling,
        overwriteThemeStyling: false,
      });
    }
  };

  return (
    <FormProvider {...form}>
      <form onSubmit={(e) => e.preventDefault()}>
        <div className="mt-12 space-y-3 p-5">
          <div className="flex items-center gap-4 rounded-lg border border-slate-300 bg-white p-4">
            <FormField
              control={form.control}
              name="overwriteThemeStyling"
              render={({ field }) => (
                <FormItem className="flex items-center gap-4 gap-y-0">
                  <FormControl>
                    <Switch
                      id="overwrite-theme-styling"
                      checked={!!field.value}
                      onCheckedChange={handleOverwriteToggle}
                    />
                  </FormControl>

                  <div>
                    <FormLabel
                      htmlFor="overwrite-theme-styling"
                      className="text-base font-semibold text-slate-900">
                      {t("workspace.surveys.edit.use_custom_styling_for_this_survey")}
                    </FormLabel>
                    <FormDescription className="text-sm text-slate-500">
                      {t("workspace.surveys.edit.override_theme_with_individual_styles_for_this_survey")}
                    </FormDescription>
                  </div>
                </FormItem>
              )}
            />
          </div>

          {localSurvey.type === "app" && setAppearance && (
            <StylingAppearanceToggle appearance={appearance} onChange={setAppearance} />
          )}

          <StylingAppearanceProvider appearance={effectiveAppearance}>
            <FormStylingSettings
              open={formStylingOpen}
              setOpen={setFormStylingOpen}
              disabled={!overwriteThemeStyling}
              form={form as UseFormReturn<TWorkspaceStyling | TSurveyStyling>}
              onSuggestColorsClick={() => setConfirmSuggestColorsOpen(true)}
              brandColorNotice={
                localSurvey.type === "app" &&
                setAppearance &&
                overwriteThemeStyling && (
                  <DarkContrastWarnings appearance={appearance} styling={form.watch()} />
                )
              }
              pageFontFallback={
                localSurvey.type === "app" ? savedWorkspaceStyling?.pageFont === true : undefined
              }
            />

            <CardStylingSettings
              open={cardStylingOpen}
              setOpen={setCardStylingOpen}
              surveyType={localSurvey.type}
              disabled={!overwriteThemeStyling}
              form={form as UseFormReturn<TWorkspaceStyling | TSurveyStyling>}
            />
          </StylingAppearanceProvider>

          {localSurvey.type === "link" && (
            <>
              <BackgroundStylingCard
                open={stylingOpen}
                setOpen={setStylingOpen}
                workspaceId={workspaceId}
                colors={colors}
                disabled={!overwriteThemeStyling}
                isUnsplashConfigured={isUnsplashConfigured}
                form={form as UseFormReturn<TWorkspaceStyling | TSurveyStyling>}
                isStorageConfigured={isStorageConfigured}
              />

              <LogoSettingsCard
                open={logoSettingsOpen}
                setOpen={setLogoSettingsOpen}
                disabled={!overwriteThemeStyling}
                workspaceId={workspaceId}
                form={form as UseFormReturn<TWorkspaceStyling | TSurveyStyling>}
                isStorageConfigured={isStorageConfigured}
              />
            </>
          )}

          {/* Like the cards above, survey CSS only applies while the survey uses custom styling (ENG-3723). */}
          <SurveyCustomCssCard
            config={customCssEditor}
            localSurvey={localSurvey}
            setLocalSurvey={setLocalSurvey}
            savedCustomCss={savedCustomCss}
            validation={customCssValidation}
            appearance={effectiveAppearance}
            appearanceHref={`${workspaceBasePath}/settings/workspace/look`}
            disabled={!overwriteThemeStyling}
            open={customCssOpen}
            setOpen={setCustomCssOpen}
          />

          {!isCxMode && (
            <div className="mt-4 flex h-8 items-center justify-between">
              <div>
                {overwriteThemeStyling && (
                  <Button
                    type="button"
                    variant="ghost"
                    className="flex items-center gap-2"
                    onClick={() => setConfirmResetStylingModalOpen(true)}>
                    {t("workspace.surveys.edit.reset_to_theme_styles")}
                    <RotateCcwIcon className="size-4" />
                  </Button>
                )}
              </div>
              <p className="text-sm text-slate-500">
                <Trans
                  i18nKey="workspace.surveys.edit.adjust_theme_in_look_and_feel_settings"
                  components={{
                    lookFeelLink: (
                      <Link
                        href={`${workspaceBasePath}/settings/workspace/look`}
                        target="_blank"
                        className="font-semibold underline"
                      />
                    ),
                  }}
                />
              </p>
            </div>
          )}
          <AlertDialog
            open={confirmResetStylingModalOpen}
            setOpen={setConfirmResetStylingModalOpen}
            headerText={t("workspace.surveys.edit.reset_to_theme_styles")}
            mainText={t("workspace.surveys.edit.reset_to_theme_styles_main_text")}
            confirmBtnLabel={t("common.confirm")}
            onDecline={() => setConfirmResetStylingModalOpen(false)}
            onConfirm={onResetThemeStyling}
          />

          <AlertDialog
            open={confirmSuggestColorsOpen}
            setOpen={setConfirmSuggestColorsOpen}
            headerText={t("workspace.look.generate_theme_header")}
            mainText={t("workspace.look.generate_theme_confirmation")}
            confirmBtnLabel={t("workspace.look.generate_theme_btn")}
            declineBtnLabel={t("common.cancel")}
            onConfirm={handleSuggestColors}
            onDecline={() => setConfirmSuggestColorsOpen(false)}
          />
        </div>
      </form>
    </FormProvider>
  );
};
