"use client";

import { Loader2, UsersIcon } from "lucide-react";
import { useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { TSegment, ZSegmentFilters } from "@formbricks/types/segment";
import { TSurvey } from "@formbricks/types/surveys/types";
import { type TUserLocale } from "@formbricks/types/user";
import { cn } from "@/lib/cn";
import { formatDate, timeSinceDate } from "@/lib/time";
import { Dialog, DialogBody, DialogContent, DialogHeader, DialogTitle } from "@/modules/ui/components/dialog";

interface SegmentDetailProps {
  readonly segment: TSegment;
  readonly setSegment: (segment: TSegment) => void;
  readonly setOpen: (open: boolean) => void;
  readonly setIsSegmentEditorOpen: (isOpen: boolean) => void;
  readonly onSegmentLoad: (surveyId: string, segmentId: string) => Promise<TSurvey>;
  readonly surveyId: string;
  readonly currentSegment: TSegment;
  readonly locale: TUserLocale;
}

const SegmentDetail = ({
  segment,
  setIsSegmentEditorOpen,
  setOpen,
  setSegment,
  onSegmentLoad,
  surveyId,
  currentSegment,
  locale,
}: SegmentDetailProps) => {
  const [isLoading, setIsLoading] = useState(false);
  const handleLoadNewSegment = async (segmentId: string) => {
    try {
      if (currentSegment.id === segmentId) {
        return;
      }

      setIsLoading(true);
      const updatedSurvey = await onSegmentLoad(surveyId, segmentId);

      if (!updatedSurvey?.id || !updatedSurvey?.segment) {
        toast.error("Error loading survey");
        setIsLoading(false);
        setIsSegmentEditorOpen(false);
        setOpen(false);
        return;
      }

      const parsedFilters = ZSegmentFilters.safeParse(updatedSurvey?.segment?.filters);

      if (!parsedFilters.success) {
        toast.error("Error loading survey");
        setIsLoading(false);
        setIsSegmentEditorOpen(false);
        setOpen(false);
        return;
      }

      setSegment({
        ...updatedSurvey.segment,
        description: updatedSurvey.segment.description || "",
        filters: parsedFilters.data,
        surveys: updatedSurvey.segment.surveys,
      });

      setIsLoading(false);
    } catch (err) {
      setIsLoading(false);
      toast.error(err instanceof Error ? err.message : String(err));
      setOpen(false);
    }
  };

  return (
    <button
      type="button"
      key={segment.id}
      className={cn(
        "relative mt-1 grid h-16 w-full cursor-pointer grid-cols-5 content-center rounded-lg hover:bg-slate-100",
        currentSegment.id === segment.id && "pointer-events-none bg-slate-100 opacity-60"
      )}
      onClick={async () => {
        setIsLoading(true);
        try {
          await handleLoadNewSegment(segment.id);
          setIsLoading(false);
        } catch {
          setIsLoading(false);
        }
      }}>
      {isLoading && (
        <div className="absolute inset-0 flex items-center justify-center bg-slate-50 opacity-80">
          <Loader2 className="size-6 animate-spin" />
        </div>
      )}
      <div className="col-span-3 flex items-center pl-6 text-sm">
        <div className="flex items-center gap-4">
          <div className="ph-no-capture size-8 shrink-0 text-slate-700">
            <UsersIcon className="size-5" />
          </div>
          <div className="flex flex-col">
            <div className="ph-no-capture font-medium text-slate-900">{segment.title}</div>
            <div className="ph-no-capture text-xs font-medium text-slate-500">{segment.description}</div>
          </div>
        </div>
      </div>

      <div className="whitespace-wrap col-span-1 my-auto hidden text-center text-sm text-slate-500 sm:block">
        <div className="ph-no-capture text-slate-900">{timeSinceDate(segment.updatedAt, locale)}</div>
      </div>

      <div className="whitespace-wrap col-span-1 my-auto hidden text-center text-sm text-slate-500 sm:block">
        <div className="ph-no-capture text-slate-900">{formatDate(segment.createdAt, locale)}</div>
      </div>
    </button>
  );
};

type LoadSegmentModalProps = {
  readonly open: boolean;
  readonly setOpen: (open: boolean) => void;
  readonly surveyId: string;
  readonly currentSegment: TSegment;
  readonly segments: TSegment[];
  readonly setSegment: (segment: TSegment) => void;
  readonly setIsSegmentEditorOpen: (isOpen: boolean) => void;
  readonly onSegmentLoad: (surveyId: string, segmentId: string) => Promise<TSurvey>;
};

export const LoadSegmentModal = ({
  open,
  surveyId,
  setOpen,
  currentSegment,
  segments,
  setSegment,
  setIsSegmentEditorOpen,
  onSegmentLoad,
}: LoadSegmentModalProps) => {
  const handleResetState = () => {
    setOpen(false);
  };
  const { t, i18n } = useTranslation();
  const locale = (i18n.resolvedLanguage ?? i18n.language ?? "en-US") as TUserLocale;
  const segmentsArray = segments?.filter((segment) => !segment.isPrivate);

  return (
    <Dialog
      open={open}
      onOpenChange={(open) => {
        if (!open) {
          handleResetState();
        }
      }}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t("workspace.surveys.edit.load_segment")}</DialogTitle>
        </DialogHeader>

        <DialogBody>
          {!segmentsArray?.length ? (
            <div className="group">
              <div className="flex h-16 w-full flex-col items-center justify-center rounded-md text-slate-700">
                {t("workspace.surveys.edit.you_have_not_created_a_segment_yet")}
              </div>
            </div>
          ) : (
            <div className="flex flex-col">
              <div>
                <div className="grid h-12 grid-cols-5 content-center rounded-lg bg-slate-100 text-left text-sm font-semibold text-slate-900">
                  <div className="col-span-3 pl-6">{t("common.segment")}</div>
                  <div className="col-span-1 hidden text-center sm:block">{t("common.updated_at")}</div>
                  <div className="col-span-1 hidden text-center sm:block">{t("common.created_at")}</div>
                </div>

                {segmentsArray.map((segment) => (
                  <SegmentDetail
                    key={segment.id}
                    segment={segment}
                    setIsSegmentEditorOpen={setIsSegmentEditorOpen}
                    setOpen={setOpen}
                    setSegment={setSegment}
                    onSegmentLoad={onSegmentLoad}
                    surveyId={surveyId}
                    currentSegment={currentSegment}
                    locale={locale}
                  />
                ))}
              </div>
            </div>
          )}
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};
