"use client";

import { useState } from "react";
import { TemplateLayout } from "./TemplateLayout";
import CircularProgressbarsList from "@/components/widgets/CircularProgressbarsList/CircularProgressbarsList";
import type { LoadersScreenDefinition } from "@/lib/funnel/types";

interface LoadersTemplateProps {
  screen: LoadersScreenDefinition;
  onContinue: () => void;
  canGoBack: boolean;
  onBack: () => void;
  screenProgress?: { current: number; total: number };
  defaultTexts?: { nextButton?: string; continueButton?: string };
}

export function LoadersTemplate({
  screen,
  onContinue,
  canGoBack,
  onBack,
  screenProgress,
  defaultTexts,
}: LoadersTemplateProps) {
  const [isVisibleButton, setIsVisibleButton] = useState(false);

  const onAnimationEnd = () => {
    setIsVisibleButton(true);
  };

  const progressbarsListProps = {
    progressbarItems: screen.progressbars?.items?.map((item: unknown, index: number) => {
      const typedItem = item as {
        title?: string;
        processingTitle?: string;
        processingSubtitle?: string;
        completedTitle?: string;
        completedSubtitle?: string;
      };

      return {
        circularProgressbarProps: {
          text: { children: typedItem.title || `Step ${index + 1}` },
        },
        processing: typedItem.processingTitle ? {
          title: { children: typedItem.processingTitle },
          subtitle: typedItem.processingSubtitle ? { children: typedItem.processingSubtitle } : undefined,
        } : undefined,
        completed: typedItem.completedTitle ? {
          title: { children: typedItem.completedTitle },
          subtitle: typedItem.completedSubtitle ? { children: typedItem.completedSubtitle } : undefined,  
        } : undefined,
      };
    }) || [],
    transitionDurationItem: screen.progressbars?.transitionDuration || 3000, // Как в оригинале
    onAnimationEnd,
  };

  return (
    <TemplateLayout
      screen={screen}
      onContinue={onContinue}
      canGoBack={canGoBack}
      onBack={onBack}
      screenProgress={screenProgress}
      defaultTexts={defaultTexts}
      titleDefaults={{ font: "manrope", weight: "bold", align: "center", size: "2xl", color: "default" }}
      subtitleDefaults={{ font: "manrope", weight: "medium", color: "default", align: "center", size: "lg" }}
      actionButtonOptions={{
        defaultText: defaultTexts?.nextButton || "Continue",
        disabled: !isVisibleButton,
        onClick: onContinue,
      }}
    >
      <div className="w-full flex flex-col items-center gap-[22px] mt-[22px]">
        <CircularProgressbarsList
          {...progressbarsListProps}
          showDividers={false}
        />
      </div>
    </TemplateLayout>
  );
}
