"use client";

import { ArrowUpRight, EllipsisVerticalIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { toast } from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { Language } from "@formbricks/database/prisma-browser";
import { getLanguageLabel } from "@formbricks/i18n-utils/utils";
import { TSurvey, TSurveyLanguage } from "@formbricks/types/surveys/types";
import { TUserLocale } from "@formbricks/types/user";
import type { TAIUnavailableReason } from "@/lib/ai/service";
import { cn } from "@/lib/cn";
import { addMultiLanguageLabels, extractLanguageCodes, getEnabledLanguages } from "@/lib/i18n/utils";
import { checkAITranslationAvailableAction } from "@/modules/ee/ai-translation/lib/actions";
import { AdvancedOptionToggle } from "@/modules/ui/components/advanced-option-toggle";
import { Badge } from "@/modules/ui/components/badge";
import { Button } from "@/modules/ui/components/button";
import { ConfirmationModal } from "@/modules/ui/components/confirmation-modal";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/modules/ui/components/dropdown-menu";
import { Label } from "@/modules/ui/components/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/modules/ui/components/select";
import { Switch } from "@/modules/ui/components/switch";
import { applyAutoSelectLanguageRule } from "../lib/auto-select-language";
import { hasLockedTranslations } from "../lib/published-translation-lock";
import {
  computeTranslationProgress,
  extractTranslatableStrings,
  getProgressColor,
  getProgressTextColor,
  makeLanguageSoleDefault,
  removeAllTranslations,
  removeLanguageKeysFromSurvey,
} from "../lib/utils";
import { ManageTranslationsModal } from "./manage-translations-modal";

interface LanguageViewProps {
  readonly localSurvey: TSurvey;
  /** The survey as stored: what the published lock compares the translations against. */
  readonly persistedSurvey: TSurvey;
  readonly setLocalSurvey: (survey: TSurvey) => void;
  readonly workspaceLanguages: Language[];
  readonly locale: TUserLocale;
  readonly setHasIncompleteTranslations: (has: boolean) => void;
}

interface ConfirmationModalInfo {
  title: string;
  open: boolean;
  body: string;
  buttonText: string;
  buttonVariant?: "default" | "destructive";
  onConfirm: () => void;
}

export const LanguageView = ({
  localSurvey,
  persistedSurvey,
  setLocalSurvey,
  workspaceLanguages,
  locale,
  setHasIncompleteTranslations,
}: LanguageViewProps) => {
  const { t } = useTranslation();
  const { workspaceId } = localSurvey;

  const [isMultiLanguageActivated, setIsMultiLanguageActivated] = useState(localSurvey.languages.length > 0);
  const [isAIAvailable, setIsAIAvailable] = useState(false);
  const [aiUnavailableReason, setAiUnavailableReason] = useState<TAIUnavailableReason | undefined>();
  const [confirmationModalInfo, setConfirmationModalInfo] = useState<ConfirmationModalInfo>({
    title: "",
    open: false,
    body: "",
    buttonText: "",
    onConfirm: () => {},
  });
  const [translationModalOpen, setTranslationModalOpen] = useState(false);
  const [activeLanguageCode, setActiveLanguageCode] = useState<string>("");

  const defaultLanguage = useMemo(
    () => localSurvey.languages.find((l) => l.default)?.language,
    [localSurvey.languages]
  );

  const translatableStrings = useMemo(() => extractTranslatableStrings(localSurvey, t), [localSurvey, t]);

  const enabledLanguages = getEnabledLanguages(localSurvey.languages);

  // Every non-default language to show in the table: the union of workspace languages and languages
  // already stored on the survey. Including survey-only languages (e.g. one later removed from the
  // workspace) guarantees a language present in the survey object always stays visible here, so it
  // can be managed or removed instead of silently lingering in the data (ENG-2001).
  const nonDefaultLanguageCodes = useMemo(() => {
    const codes = new Set<string>();
    workspaceLanguages.forEach((l) => codes.add(l.code));
    localSurvey.languages.forEach((sl) => codes.add(sl.language.code));
    if (defaultLanguage) codes.delete(defaultLanguage.code);
    return [...codes];
  }, [workspaceLanguages, localSurvey.languages, defaultLanguage]);

  // Check AI availability once on mount
  useEffect(() => {
    let isCurrent = true;
    // eslint-disable-next-line react/set-state-in-effect -- fetch effect: availability is unknown until the request it starts answers
    setIsAIAvailable(false);

    checkAITranslationAvailableAction({ surveyId: localSurvey.id })
      .then((result) => {
        if (isCurrent) {
          setIsAIAvailable(result?.data?.available ?? false);
          setAiUnavailableReason(result?.data?.available ? undefined : result?.data?.reason);
        }
      })
      .catch(() => {
        if (isCurrent) {
          setIsAIAvailable(false);
        }
      });

    return () => {
      isCurrent = false;
    };
  }, [localSurvey.id]);

  // Sync multi-language state: languages emptied on the survey switch it off. Adjusted during render.
  const [syncedSurveyLanguages, setSyncedSurveyLanguages] = useState(localSurvey.languages);
  if (syncedSurveyLanguages !== localSurvey.languages) {
    setSyncedSurveyLanguages(localSurvey.languages);
    if (localSurvey.languages.length === 0) setIsMultiLanguageActivated(false);
  }

  // Track incomplete translations
  useEffect(() => {
    if (!isMultiLanguageActivated || localSurvey.languages.length <= 1) {
      setHasIncompleteTranslations(false);
      return;
    }
    const nonDefaultLangs = localSurvey.languages.filter((l) => !l.default && l.enabled);
    const hasIncomplete = nonDefaultLangs.some((lang) => {
      const progress = computeTranslationProgress(translatableStrings, lang.language.code);
      return progress.percentage < 100;
    });
    setHasIncompleteTranslations(hasIncomplete);
  }, [localSurvey.languages, translatableStrings, isMultiLanguageActivated, setHasIncompleteTranslations]);

  // Every language change made here goes through this, so "Use browser language by default" turns on
  // when multi-language is first activated and off when it is deactivated (see the rule's docs).
  const updateLocalSurvey = (updatedSurvey: TSurvey) => {
    setLocalSurvey(applyAutoSelectLanguageRule(localSurvey, updatedSurvey));
  };

  const updateSurveyTranslations = (survey: TSurvey, updatedLanguages: TSurveyLanguage[]) => {
    const translatedSurveyResult = addMultiLanguageLabels(survey, extractLanguageCodes(updatedLanguages));
    const updatedSurvey = { ...translatedSurveyResult, languages: updatedLanguages };
    updateLocalSurvey(updatedSurvey);
  };

  // Answers are stored as the option text, so a published survey keeps the translations it already has:
  // removing a language, or changing the default (which removes them all), would be refused on save.
  const isRemovalLocked = (languageCode?: string): boolean => {
    if (!hasLockedTranslations(persistedSurvey, languageCode)) return false;
    toast.error(t("workspace.surveys.edit.lock_explanation_option_text"));
    return true;
  };

  const handleActivationSwitch = () => {
    if (isMultiLanguageActivated) {
      if (localSurvey.languages.length > 0) {
        if (isRemovalLocked()) return;
        setConfirmationModalInfo({
          open: true,
          title: t("workspace.surveys.edit.remove_translations"),
          body: t("workspace.surveys.edit.this_action_will_remove_all_the_translations_from_this_survey"),
          buttonText: t("workspace.surveys.edit.remove_translations"),
          buttonVariant: "destructive",
          onConfirm: () => {
            updateLocalSurvey({ ...removeAllTranslations(localSurvey), languages: [] });
            setIsMultiLanguageActivated(false);
            setConfirmationModalInfo((prev) => ({ ...prev, open: false }));
          },
        });
      } else {
        setIsMultiLanguageActivated(false);
      }
    } else {
      setIsMultiLanguageActivated(true);
    }
  };

  const handleDefaultLanguageChange = (languageCode: string) => {
    const language = workspaceLanguages.find((lang) => lang.code === languageCode);
    if (!language) return;

    let languageExists = false;
    const newLanguages =
      localSurvey.languages.map((lang) => {
        if (lang.language.code === language.code) {
          languageExists = true;
          return { ...lang, default: true };
        }
        return { ...lang, default: false };
      }) ?? [];

    if (!languageExists) {
      newLanguages.push({ enabled: true, default: true, language });
    }

    // The default language is always keyed as "default" throughout the survey object. Strip any
    // stale/empty code key for the promoted language so it can never end up as the default while
    // its own code key sits empty next to a populated "default" — the state that makes the response
    // API reject valid choice answers (ENG-2001).
    const cleanedSurvey = removeLanguageKeysFromSurvey(localSurvey, language.code);

    setConfirmationModalInfo((prev) => ({ ...prev, open: false }));
    updateLocalSurvey({ ...cleanedSurvey, languages: newLanguages });
  };

  const handleToggleLanguage = (code: string) => {
    const surveyLang = localSurvey.languages.find((l) => l.language.code === code);

    if (surveyLang) {
      if (surveyLang.enabled) {
        // Disabling
        const progress = computeTranslationProgress(translatableStrings, code);
        if (progress.translated > 0) {
          // Has translations — just disable, keep translations in survey object
          const updatedLanguages = localSurvey.languages.map((l) =>
            l.language.code === code ? { ...l, enabled: false } : l
          );
          updateLocalSurvey({ ...localSurvey, languages: updatedLanguages });
        } else {
          // No translations — remove from survey object and clean up i18n keys
          const cleanedSurvey = removeLanguageKeysFromSurvey(localSurvey, code);
          const updatedLanguages = localSurvey.languages.filter((l) => l.language.code !== code);
          updateLocalSurvey({ ...cleanedSurvey, languages: updatedLanguages });
        }
      } else {
        // Re-enabling — ensure i18n keys exist for any new translatable strings
        const updatedLanguages = localSurvey.languages.map((l) =>
          l.language.code === code ? { ...l, enabled: true } : l
        );
        updateSurveyTranslations(localSurvey, updatedLanguages);
      }
    } else {
      // Language not in survey — add it with enabled: true
      const language = workspaceLanguages.find((l) => l.code === code);
      if (language) {
        const updatedLanguages: TSurveyLanguage[] = [
          ...localSurvey.languages,
          { enabled: true, default: false, language },
        ];
        updateSurveyTranslations(localSurvey, updatedLanguages);
      }
    }
  };

  const handleRemoveTranslations = (code: string) => {
    if (isRemovalLocked(code)) return;
    const label = getLanguageLabel(code, locale) ?? code;
    const progress = computeTranslationProgress(translatableStrings, code);
    const hasTranslations = progress.translated > 0;
    setConfirmationModalInfo({
      open: true,
      title: `${t("workspace.surveys.edit.remove_translations")}: ${label}`,
      body: hasTranslations
        ? t("workspace.surveys.edit.this_will_remove_the_language_and_all_its_translations")
        : t("workspace.surveys.edit.this_will_remove_the_language_from_this_survey"),
      buttonText: t("workspace.surveys.edit.remove_translations"),
      buttonVariant: "destructive",
      onConfirm: () => {
        // Fully strip the language's keys from the survey object (not just blank the strings) so a
        // removed language can never linger and later corrupt the default (ENG-2001).
        const cleanedSurvey = removeLanguageKeysFromSurvey(localSurvey, code);
        const updatedLanguages = localSurvey.languages.filter((l) => l.language.code !== code);
        updateLocalSurvey({ ...cleanedSurvey, languages: updatedLanguages });
        setConfirmationModalInfo((prev) => ({ ...prev, open: false }));
      },
    });
  };

  // Changing the default means removing every translation first, so both entry points share one
  // confirmation that says so. From the default row the survey drops back to no languages; from
  // "Make default" on a language, that language becomes the sole default in the same step.
  const openChangeDefaultConfirmation = (onConfirm: () => void) => {
    setConfirmationModalInfo({
      open: true,
      title: t("workspace.surveys.edit.change_default"),
      body: t("workspace.surveys.edit.to_change_the_default_you_need_to_remove_all_translations_first"),
      buttonText: t("workspace.surveys.edit.remove_and_change_default"),
      buttonVariant: "destructive",
      onConfirm: () => {
        onConfirm();
        setConfirmationModalInfo((prev) => ({ ...prev, open: false }));
      },
    });
  };

  const handleChangeDefault = () => {
    if (isRemovalLocked()) return;
    openChangeDefaultConfirmation(() => {
      // Actually strip every non-default language's keys from the survey object. Using
      // updateSurveyTranslations([]) here only re-seeds keys and leaves stale empty code keys
      // behind, which can later be promoted into a broken default (ENG-2001).
      updateLocalSurvey({ ...removeAllTranslations(localSurvey), languages: [] });
      setIsMultiLanguageActivated(false);
    });
  };

  const handleMakeDefault = (code: string) => {
    const language =
      workspaceLanguages.find((l) => l.code === code) ??
      localSurvey.languages.find((sl) => sl.language.code === code)?.language;
    if (!language || isRemovalLocked()) return;
    openChangeDefaultConfirmation(() => updateLocalSurvey(makeLanguageSoleDefault(localSurvey, language)));
  };

  const handleLanguageSwitchToggle = () => {
    setLocalSurvey({ ...localSurvey, showLanguageSwitch: !localSurvey.showLanguageSwitch });
  };

  const handleAutoSelectLanguageToggle = () => {
    setLocalSurvey({ ...localSurvey, autoSelectLanguage: !localSurvey.autoSelectLanguage });
  };

  const openTranslationModal = (code: string) => {
    setActiveLanguageCode(code);
    setTranslationModalOpen(true);
  };

  return (
    <div className="mt-12 space-y-3 p-5">
      {/* Activation toggle — only show when workspace has languages */}
      {workspaceLanguages.length > 0 && (
        <div className="flex items-center gap-4 rounded-lg border border-slate-300 bg-white p-4">
          <Switch
            checked={isMultiLanguageActivated}
            onCheckedChange={handleActivationSwitch}
            id="activate-translations-toggle"
          />
          <div>
            <Label htmlFor="activate-translations-toggle" className="text-base font-semibold text-slate-900">
              {t("workspace.surveys.edit.activate_translations")}
            </Label>
            <p className="text-sm text-slate-500">
              {t("workspace.surveys.edit.present_your_survey_in_multiple_languages")}
            </p>
          </div>
        </div>
      )}

      {isMultiLanguageActivated && (
        <div className="space-y-6 rounded-lg border border-slate-300 bg-white p-6">
          <div className="flex items-center justify-between">
            <h3 className="text-base font-semibold text-slate-900">{t("common.survey_languages")}</h3>
          </div>

          {/* Default language select — only show when no default is set yet */}
          {workspaceLanguages.length > 0 && !defaultLanguage && (
            <div className="space-y-2">
              <Label>{t("workspace.surveys.edit.default_language")}</Label>
              <div className="w-56">
                <Select
                  onValueChange={(code) => {
                    setConfirmationModalInfo({
                      open: true,
                      title:
                        t("workspace.surveys.edit.confirm_default_language") +
                        ": " +
                        getLanguageLabel(code, locale),
                      body: t(
                        "workspace.surveys.edit.once_set_the_default_language_for_this_survey_can_only_be_changed_by_disabling_the_multi_language_option_and_deleting_all_translations"
                      ),
                      buttonText: t("common.confirm"),
                      buttonVariant: "default",
                      onConfirm: () => handleDefaultLanguageChange(code),
                    });
                  }}>
                  <SelectTrigger className="w-full text-sm">
                    <SelectValue placeholder={t("common.select_language")} />
                  </SelectTrigger>
                  <SelectContent>
                    {workspaceLanguages.map((lang) => (
                      <SelectItem key={lang.id} value={lang.code}>
                        {getLanguageLabel(lang.code, locale)} ({lang.code})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}

          {/* Languages table — show all workspace languages */}
          {defaultLanguage && workspaceLanguages.length > 0 && (
            <div className="overflow-hidden rounded-lg border border-slate-300">
              <table className="w-full text-sm">
                <thead className="bg-slate-50">
                  <tr>
                    <th className="px-4 py-2.5 text-left font-medium text-slate-600">
                      {t("common.language")}
                    </th>
                    <th className="px-4 py-2.5 text-left font-medium text-slate-600">
                      {t("workspace.surveys.edit.code")}
                    </th>
                    <th className="px-4 py-2.5 text-left font-medium text-slate-600">
                      {t("workspace.surveys.edit.translated")}
                    </th>
                    <th className="px-4 py-2.5 text-left font-medium text-slate-600">
                      {t("workspace.surveys.edit.visible")}
                    </th>
                    <th className="w-12 px-4 py-2.5" />
                  </tr>
                </thead>
                <tbody>
                  {/* Default language row */}
                  <tr className="border-t border-slate-200">
                    <td className="px-4 py-3 font-medium text-slate-800">
                      {getLanguageLabel(defaultLanguage.code, locale)}
                    </td>
                    <td className="px-4 py-3 text-slate-600">{defaultLanguage.code}</td>
                    <td className="px-4 py-3">
                      <Badge type="gray" size="normal" text={t("common.default")} />
                    </td>
                    <td className="px-4 py-3">
                      <Switch checked disabled />
                    </td>
                    <td className="px-4 py-3">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <button type="button" className="rounded-sm p-1 hover:bg-slate-100">
                            <EllipsisVerticalIcon className="size-4 text-slate-500" />
                          </button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem onClick={handleChangeDefault}>
                            {t("workspace.surveys.edit.change_default")}
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </td>
                  </tr>

                  {/* Non-default rows — every workspace language plus any language already stored on
                      the survey (union), so a survey language is always visible and removable. */}
                  {nonDefaultLanguageCodes.map((code) => {
                    const surveyLang = localSurvey.languages.find((sl) => sl.language.code === code);
                    const inSurvey = !!surveyLang;
                    const enabled = surveyLang?.enabled ?? false;
                    const progress = inSurvey ? computeTranslationProgress(translatableStrings, code) : null;

                    return (
                      <tr
                        key={code}
                        className={cn(
                          "border-t border-slate-200",
                          inSurvey && "cursor-pointer hover:bg-slate-50"
                        )}
                        onClick={() => {
                          if (inSurvey) {
                            openTranslationModal(code);
                          }
                        }}>
                        <td className="px-4 py-3 font-medium text-slate-800">
                          {getLanguageLabel(code, locale)}
                        </td>
                        <td className="px-4 py-3 text-slate-600">{code}</td>
                        <td className="px-4 py-3">
                          {inSurvey && progress && (
                            <div className="flex items-center gap-2">
                              <div className="h-2 w-24 overflow-hidden rounded-full bg-slate-200">
                                <div
                                  className={cn(
                                    "h-full rounded-full transition-all",
                                    getProgressColor(progress.percentage)
                                  )}
                                  style={{ width: `${progress.percentage}%` }}
                                />
                              </div>
                              <span
                                className={cn(
                                  "text-xs font-medium",
                                  getProgressTextColor(progress.percentage)
                                )}>
                                {progress.translated}/{progress.total}
                              </span>
                            </div>
                          )}
                        </td>
                        <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                          <Switch checked={enabled} onCheckedChange={() => handleToggleLanguage(code)} />
                        </td>
                        <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <button type="button" className="rounded-sm p-1 hover:bg-slate-100">
                                <EllipsisVerticalIcon className="size-4 text-slate-500" />
                              </button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem onClick={() => handleMakeDefault(code)}>
                                {t("workspace.surveys.edit.make_default")}
                              </DropdownMenuItem>
                              {inSurvey && (
                                <>
                                  <DropdownMenuItem onClick={() => openTranslationModal(code)}>
                                    {t("workspace.surveys.edit.manage_translations")}
                                  </DropdownMenuItem>
                                  <DropdownMenuItem
                                    className="text-red-600 focus:text-red-600"
                                    onClick={() => handleRemoveTranslations(code)}>
                                    {t("workspace.surveys.edit.remove_translations")}
                                  </DropdownMenuItem>
                                </>
                              )}
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}

          {/* Manage workspace languages link */}
          <Button asChild size="sm" variant="secondary">
            <Link href={`/workspaces/${workspaceId}/settings/workspace/languages`} target="_blank">
              {t("workspace.surveys.edit.manage_languages")}
              <ArrowUpRight className="ml-1 size-4" />
            </Link>
          </Button>

          {/* Show language switcher toggle */}
          <AdvancedOptionToggle
            customContainerClass="px-0 pt-0"
            htmlId="languageSwitch"
            disabled={enabledLanguages.length <= 1}
            isChecked={!!localSurvey.showLanguageSwitch}
            onToggle={handleLanguageSwitchToggle}
            title={t("workspace.surveys.edit.show_language_switch")}
            description={t(
              "workspace.surveys.edit.enable_participants_to_switch_the_survey_language_at_any_point_during_the_survey"
            )}
            childBorder={true}
          />

          {/* Use browser language by default toggle */}
          <AdvancedOptionToggle
            customContainerClass="px-0 pt-0"
            htmlId="autoSelectLanguage"
            disabled={enabledLanguages.length <= 1}
            isChecked={!!localSurvey.autoSelectLanguage}
            onToggle={handleAutoSelectLanguageToggle}
            title={t("workspace.surveys.edit.auto_select_browser_language")}
            description={t("workspace.surveys.edit.auto_select_browser_language_description")}
            childBorder={true}
          />
        </div>
      )}

      {workspaceLanguages.length === 0 && (
        <div className="rounded-lg border border-slate-300 bg-white p-6 text-center">
          <p className="text-sm text-slate-500">
            {t("workspace.surveys.edit.no_languages_found_add_first_one_to_get_started")}
          </p>
          <Button asChild size="sm" variant="secondary" className="mt-3">
            <Link href={`/workspaces/${workspaceId}/settings/workspace/languages`} target="_blank">
              {t("workspace.surveys.edit.manage_languages")}
              <ArrowUpRight className="ml-1 size-4" />
            </Link>
          </Button>
        </div>
      )}

      {/* Confirmation modal */}
      <ConfirmationModal
        buttonText={confirmationModalInfo.buttonText}
        buttonVariant={confirmationModalInfo.buttonVariant}
        onConfirm={confirmationModalInfo.onConfirm}
        open={confirmationModalInfo.open}
        setOpen={(value) => {
          const open = typeof value === "function" ? value(confirmationModalInfo.open) : value;
          setConfirmationModalInfo((prev) => ({ ...prev, open }));
        }}
        body={confirmationModalInfo.body}
        title={confirmationModalInfo.title}
      />

      {/* Translations modal */}
      <ManageTranslationsModal
        open={translationModalOpen}
        setOpen={setTranslationModalOpen}
        localSurvey={localSurvey}
        setLocalSurvey={setLocalSurvey}
        languageCode={activeLanguageCode}
        languageName={getLanguageLabel(activeLanguageCode, locale) ?? activeLanguageCode}
        defaultLanguageName={
          defaultLanguage ? (getLanguageLabel(defaultLanguage.code, locale) ?? defaultLanguage.code) : ""
        }
        persistedSurvey={persistedSurvey}
        workspaceId={workspaceId}
        isAIAvailable={isAIAvailable}
        aiUnavailableReason={aiUnavailableReason}
      />
    </div>
  );
};
