"use client";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { TTemplate } from "@formbricks/types/templates";
import type { TUserLocale } from "@formbricks/types/user";
import { customSurveyTemplate } from "@/app/lib/templates";
import type { TAIUnavailableReason } from "@/lib/ai/service";
import { type TWorkspaceWithoutCustomCss } from "@/modules/custom-css/lib/types";
import { TemplateList } from "@/modules/survey/components/template-list";
import { TemplateCreateQueryClientProvider } from "@/modules/survey/components/template-list/query-client-provider";
import { MenuBar } from "@/modules/survey/templates/components/menu-bar";
import { PreviewSurvey } from "@/modules/ui/components/preview-survey";
import { SearchBar } from "@/modules/ui/components/search-bar";
import { getTemplatePreviewSurvey } from "../lib/minimal-survey";

type TemplateContainerWithPreviewProps = {
  workspace: TWorkspaceWithoutCustomCss;
  isTemplatePage?: boolean;
  publicDomain: string;
  /** The language surveys created here are authored in — see `resolveDefaultSurveyLanguage`. */
  defaultLanguage: string;
  /** The creator's dashboard locale, for the AI create card. */
  language: TUserLocale;
  isAIAvailable?: boolean;
  aiUnavailableReason?: TAIUnavailableReason;
};

export const TemplateContainerWithPreview = ({
  workspace,
  isTemplatePage = true,
  publicDomain,
  defaultLanguage,
  language,
  isAIAvailable = false,
  aiUnavailableReason,
}: Readonly<TemplateContainerWithPreviewProps>) => {
  const { t } = useTranslation();
  const initialTemplate = customSurveyTemplate(t);
  const [activeTemplate, setActiveTemplate] = useState<TTemplate>(initialTemplate);
  const [activeElementId, setActiveElementId] = useState<string>(
    initialTemplate.preset.blocks[0]?.elements[0]?.id || ""
  );
  const [templateSearch, setTemplateSearch] = useState<string | null>(null);

  return (
    <div className="flex h-full flex-col">
      {isTemplatePage && <MenuBar />}
      <div className="relative z-0 flex flex-1 overflow-hidden">
        <div className="flex-1 flex-col overflow-auto bg-slate-50">
          <div className="mt-6 mb-3 ml-6 flex flex-col items-center justify-between md:flex-row md:items-end">
            <h1 className="text-2xl font-bold text-slate-800">
              {isTemplatePage
                ? t("workspace.surveys.templates.create_a_new_survey")
                : t("workspace.surveys.all_set_time_to_create_first_survey")}
            </h1>
            <div className="px-6">
              <SearchBar
                value={templateSearch ?? ""}
                onChange={setTemplateSearch}
                placeholder={t("common.search")}
                className="border-slate-700"
              />
            </div>
          </div>
          <TemplateCreateQueryClientProvider>
            <TemplateList
              workspaceId={workspace.id}
              workspace={workspace}
              defaultLanguage={defaultLanguage}
              templateSearch={templateSearch ?? ""}
              showAICreateCard={!isTemplatePage}
              showImportCard
              language={language}
              isAIAvailable={isAIAvailable}
              aiUnavailableReason={aiUnavailableReason}
              onTemplateClick={(template) => {
                setActiveElementId(template.preset.blocks[0]?.elements[0]?.id || "");
                setActiveTemplate(template);
              }}
            />
          </TemplateCreateQueryClientProvider>
        </div>
        <aside className="group hidden flex-1 shrink-0 items-center justify-center overflow-hidden border-l border-slate-100 bg-slate-50 md:flex md:flex-col">
          {activeTemplate && (
            <PreviewSurvey
              survey={getTemplatePreviewSurvey(t, activeTemplate.preset)}
              elementId={activeElementId}
              workspace={workspace}
              languageCode={"default"}
              isSpamProtectionAllowed={false} // setting it to false as this is a template
              publicDomain={publicDomain}
            />
          )}
        </aside>
      </div>
    </div>
  );
};
