"use client";

import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import type { TSurveyType } from "@formbricks/types/surveys/types";
import { type TTemplate, type TTemplateFilter, ZTemplateRole } from "@formbricks/types/templates";
import type { TUserLocale } from "@formbricks/types/user";
import { ZWorkspaceConfigChannel, ZWorkspaceConfigIndustry } from "@formbricks/types/workspace";
import { CUSTOM_SURVEY_TEMPLATE_ID, templates } from "@/app/lib/templates";
import type { TAIUnavailableReason } from "@/lib/ai/service";
import { IS_DEVELOPMENT_BUILD } from "@/lib/env-client";
import { getV3ApiErrorMessage } from "@/modules/api/lib/v3-client";
import { type TWorkspaceWithoutCustomCss } from "@/modules/custom-css/lib/types";
import { ImportSurveyCard } from "@/modules/survey/import/components/import-survey-card";
import { CreateWithAITemplate } from "./components/create-with-ai-template";
import { StartFromScratchTemplate } from "./components/start-from-scratch-template";
import { Template } from "./components/template";
import { TemplateFilters } from "./components/template-filters";
import { useCreateSurveyFromTemplate } from "./hooks/use-create-survey-from-template";

interface TemplateListProps {
  workspaceId: string;
  workspace: TWorkspaceWithoutCustomCss;
  /** The language the created survey is authored in — see `resolveDefaultSurveyLanguage`. */
  defaultLanguage: string;
  templateSearch?: string;
  showFilters?: boolean;
  onTemplateClick?: (template: TTemplate) => void;
  noPreview?: boolean; // single click to create survey
  showAICreateCard?: boolean;
  /** The "Import survey" card (ENG-3655). The templates page and the empty survey list show it. */
  showImportCard?: boolean;
  /** The creator's dashboard locale. AI generation is capped to the languages the dashboard has. */
  language: TUserLocale;
  isAIAvailable?: boolean;
  aiUnavailableReason?: TAIUnavailableReason;
}

export const TemplateList = ({
  workspace,
  workspaceId,
  defaultLanguage,
  showFilters = true,
  templateSearch,
  onTemplateClick = () => {},
  noPreview,
  showAICreateCard = false,
  showImportCard = false,
  language,
  isAIAvailable = false,
  aiUnavailableReason,
}: Readonly<TemplateListProps>) => {
  const workspaceBasePath = `/workspaces/${workspace.id}`;
  const { t } = useTranslation();
  const router = useRouter();
  const [activeTemplate, setActiveTemplate] = useState<TTemplate | null>(null);
  const [selectedFilter, setSelectedFilter] = useState<TTemplateFilter[]>([null, null, null]);
  const createSurveyMutation = useCreateSurveyFromTemplate();
  const surveyType: TSurveyType = useMemo(() => {
    if (workspace.config.channel) {
      if (workspace.config.channel === "website") {
        return "app";
      }

      return workspace.config.channel;
    }

    return "link";
  }, [workspace.config.channel]);

  const createSurvey = async (activeTemplate: TTemplate) => {
    try {
      const survey = await createSurveyMutation.mutateAsync({
        workspaceId,
        templateId: activeTemplate.id,
        source: activeTemplate.id === CUSTOM_SURVEY_TEMPLATE_ID ? "custom" : "catalog",
        surveyType,
        defaultLanguage,
      });

      router.push(`${workspaceBasePath}/surveys/${survey.id}/edit`);
    } catch (error) {
      toast.error(getV3ApiErrorMessage(error, t("common.something_went_wrong_please_try_again")));
    }
  };

  const filteredTemplates = () => {
    return templates(t).filter((template) => {
      if (templateSearch) {
        return template.name.toLowerCase().includes(templateSearch.toLowerCase());
      }

      // Parse and validate the filters
      const channelParseResult = ZWorkspaceConfigChannel.nullable().safeParse(selectedFilter[0]);
      const industryParseResult = ZWorkspaceConfigIndustry.nullable().safeParse(selectedFilter[1]);
      const roleParseResult = ZTemplateRole.nullable().safeParse(selectedFilter[2]);

      // Ensure all validations are successful
      if (!channelParseResult.success || !industryParseResult.success || !roleParseResult.success) {
        // If any validation fails, skip this template
        return true;
      }

      // Access the validated data from the parse results
      const validatedChannel = channelParseResult.data;
      const validatedIndustry = industryParseResult.data;
      const validatedRole = roleParseResult.data;

      // Perform the filtering
      const channelMatch = validatedChannel === null || template.channels?.includes(validatedChannel);
      const industryMatch = validatedIndustry === null || template.industries?.includes(validatedIndustry);
      const roleMatch = validatedRole === null || template.role === validatedRole;

      return channelMatch && industryMatch && roleMatch;
    });
  };

  return (
    <main className="relative z-0 flex-1 overflow-y-auto px-6 pt-2 pb-6 focus:outline-hidden">
      {showFilters && !templateSearch && (
        <TemplateFilters
          selectedFilter={selectedFilter}
          setSelectedFilter={setSelectedFilter}
          templateSearch={templateSearch}
        />
      )}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <StartFromScratchTemplate
          activeTemplate={activeTemplate}
          setActiveTemplate={setActiveTemplate}
          onTemplateClick={onTemplateClick}
          workspace={workspace}
          createSurvey={createSurvey}
          loading={createSurveyMutation.isPending}
          noPreview={noPreview}
        />
        {showAICreateCard && (
          <CreateWithAITemplate
            workspaceId={workspaceId}
            language={language}
            isAIAvailable={isAIAvailable}
            aiUnavailableReason={aiUnavailableReason}
          />
        )}
        {showImportCard && <ImportSurveyCard workspaceId={workspaceId} isAIAvailable={isAIAvailable} />}
        {(IS_DEVELOPMENT_BUILD ? [...filteredTemplates()] : filteredTemplates()).map(
          (template: TTemplate) => {
            return (
              <Template
                key={template.id}
                template={template}
                activeTemplate={activeTemplate}
                setActiveTemplate={setActiveTemplate}
                onTemplateClick={onTemplateClick}
                workspace={workspace}
                createSurvey={createSurvey}
                loading={createSurveyMutation.isPending}
                selectedFilter={selectedFilter}
                noPreview={noPreview}
              />
            );
          }
        )}
      </div>
    </main>
  );
};
