"use client";

import * as Collapsible from "@radix-ui/react-collapsible";
import { CheckIcon, LinkIcon, MonitorIcon } from "lucide-react";
import { useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { TSegment } from "@formbricks/types/segment";
import type { TShowConditions } from "@formbricks/types/show-conditions";
import { TSurvey, TSurveyType } from "@formbricks/types/surveys/types";
import { getDefaultEndingCard } from "@/app/lib/survey-builder";
import { cn } from "@/lib/cn";
import { Alert, AlertButton, AlertDescription, AlertTitle } from "@/modules/ui/components/alert";
import { Badge } from "@/modules/ui/components/badge";
import { Label } from "@/modules/ui/components/label";
import { RadioGroup, RadioGroupItem } from "@/modules/ui/components/radio-group";

interface HowToSendCardProps {
  readonly localSurvey: TSurvey;
  readonly setLocalSurvey: (survey: TSurvey | ((TSurvey: TSurvey) => TSurvey)) => void;
  readonly appSetupCompleted: boolean;
}

export const HowToSendCard = ({ localSurvey, setLocalSurvey, appSetupCompleted }: HowToSendCardProps) => {
  const workspaceBasePath = `/workspaces/${localSurvey.workspaceId}`;
  const [open, setOpen] = useState(false);
  const { t } = useTranslation();
  // The conditions a switch to link set aside, so switching back to app in the same session brings
  // them back instead of losing them to a mis-click.
  const setAsideShowConditions = useRef<TShowConditions>(null);

  const setSurveyType = (type: TSurveyType) => {
    const endingsTemp = localSurvey.endings;
    if (type === "link" && localSurvey.endings.length === 0) {
      endingsTemp.push(getDefaultEndingCard(localSurvey.languages, t));
    }
    if (type !== "app" && localSurvey.showConditions) {
      setAsideShowConditions.current = localSurvey.showConditions;
    }
    const restoredShowConditions = setAsideShowConditions.current;
    if (type === "app") setAsideShowConditions.current = null;
    setLocalSurvey((prevSurvey) => ({
      ...prevSurvey,
      type,
      endings: endingsTemp,
      // Show conditions belong to app surveys. Left on a link survey, an unfinished one would block
      // publishing and point at a Survey Trigger card the link survey does not have.
      showConditions: type === "app" ? (prevSurvey.showConditions ?? restoredShowConditions) : null,
    }));

    // if the type is "app" and the local survey does not already have a segment, we create a new temporary segment
    if (type === "app" && !localSurvey.segment) {
      const tempSegment: TSegment = {
        id: "temp",
        isPrivate: true,
        title: localSurvey.id,
        workspaceId: localSurvey.workspaceId,
        surveys: [localSurvey.id],
        filters: [],
        createdAt: new Date(),
        updatedAt: new Date(),
        description: "",
      };

      setLocalSurvey((prevSurvey) => ({
        ...prevSurvey,
        segment: tempSegment,
      }));
    }

    // if the type is anything other than "app" and the local survey has a temporary segment, we remove it
    if (type !== "app" && localSurvey.segment?.id === "temp") {
      setLocalSurvey((prevSurvey) => ({
        ...prevSurvey,
        segment: null,
      }));
    }
  };

  const options = [
    {
      id: "link",
      name: t("common.link_survey"),
      icon: LinkIcon,
      description: t("workspace.surveys.edit.link_survey_description"),
      comingSoon: false,
      alert: false,
      hide: false,
    },
    {
      id: "app",
      name: t("common.website_app_survey"),
      icon: MonitorIcon,
      description: t("workspace.surveys.edit.app_survey_description"),
      comingSoon: false,
      alert: !appSetupCompleted,
    },
  ];

  return (
    <Collapsible.Root
      open={open}
      onOpenChange={setOpen}
      className={cn(
        open ? "" : "hover:bg-slate-50",
        "w-full space-y-2 rounded-lg border border-slate-300 bg-white"
      )}>
      <Collapsible.CollapsibleTrigger
        asChild
        className="h-full w-full cursor-pointer"
        id="howToSendCardTrigger">
        <button type="button" className="inline-flex px-4 py-4 text-left">
          <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="font-semibold text-slate-800">{t("common.survey_type")}</p>
            <p className="mt-1 text-sm text-slate-500">
              {t("workspace.surveys.edit.choose_where_to_run_the_survey")}
            </p>
          </div>
        </button>
      </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="space-y-3 p-3">
          {localSurvey.status === "inProgress" && (
            <Alert variant="warning" className="mb-3" alertRole="status">
              <AlertTitle>{t("workspace.surveys.edit.change_survey_type")}</AlertTitle>
              <AlertDescription>
                {t("workspace.surveys.edit.changing_survey_type_will_remove_existing_distribution_channels")}
              </AlertDescription>
            </Alert>
          )}
          <RadioGroup
            defaultValue="app"
            value={localSurvey.type}
            onValueChange={setSurveyType}
            className="flex flex-col gap-y-3">
            {options
              .filter((option) => !option.hide)
              .map((option) => (
                <Label
                  key={option.id}
                  htmlFor={option.id}
                  className={cn(
                    "flex w-full items-center rounded-lg border bg-slate-50 p-4",
                    option.comingSoon && "border-slate-200 bg-slate-50/50",
                    !option.comingSoon &&
                      (option.id === localSurvey.type
                        ? "cursor-pointer border-brand-dark bg-slate-50"
                        : "cursor-pointer bg-slate-50")
                  )}
                  id={`howToSendCardOption-${option.id}`}>
                  <RadioGroupItem
                    value={option.id}
                    id={option.id}
                    className="mx-5 disabled:border-slate-400 aria-checked:border-2 aria-checked:border-brand-dark"
                    disabled={option.comingSoon}
                  />
                  <div className="inline-flex items-center">
                    <option.icon className="mr-4 size-8 text-slate-500" />
                    <div>
                      <div className="inline-flex items-center">
                        <p
                          className={cn(
                            "font-semibold",
                            option.comingSoon ? "text-slate-500" : "text-slate-800"
                          )}>
                          {option.name}
                        </p>
                        {option.comingSoon && (
                          <Badge
                            size="normal"
                            type="success"
                            className="ml-2"
                            text={t("workspace.settings.enterprise.coming_soon")}
                          />
                        )}
                      </div>
                      <p className="mt-2 text-xs font-normal text-slate-600">{option.description}</p>
                      {localSurvey.type === option.id && option.alert && (
                        <Alert variant="warning" className="mt-2">
                          <AlertTitle>
                            {t("workspace.surveys.edit.formbricks_sdk_is_not_connected")}
                          </AlertTitle>
                          <AlertDescription>
                            {t("workspace.surveys.edit.connect_formbricks_and_launch_surveys")}
                          </AlertDescription>
                          <AlertButton
                            onClick={() =>
                              window.open(
                                `${workspaceBasePath}/settings/workspace/app-connection`,
                                "_blank",
                                "noopener,noreferrer"
                              )
                            }>
                            {t("common.set_up_formbricks_sdk")}
                          </AlertButton>
                        </Alert>
                      )}
                    </div>
                  </div>
                </Label>
              ))}
          </RadioGroup>
        </div>
      </Collapsible.CollapsibleContent>
    </Collapsible.Root>
  );
};
