"use client";

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

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

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 },
          text: typedItem.processingSubtitle ? { children: typedItem.processingSubtitle } : undefined,
        } : undefined,
        completed: typedItem.completedTitle ? {
          title: { children: typedItem.completedTitle },
          text: typedItem.completedSubtitle ? { children: typedItem.completedSubtitle } : undefined,  
        } : undefined,
      };
    }) || [],
    transitionDurationItem: screen.progressbars?.transitionDuration || 3000, // Как в оригинале
    onAnimationEnd,
  };

  const layoutProps = createTemplateLayoutProps(
    screen,
    { canGoBack, onBack },
    screenProgress,
    {
      preset: "center",
      actionButton: {
        defaultText: defaultTexts?.nextButton || "Continue",
        disabled: !isVisibleButton,
        onClick: onContinue,
      },
    }
  );

  return (
    <TemplateLayout {...layoutProps}>
      <div className="w-full flex flex-col items-center gap-[22px] mt-[22px]">
        <CircularProgressbarsList
          {...progressbarsListProps}
          showDividers={false}
        />
      </div>
    </TemplateLayout>
  );
}
