"use client";

import { useState, useRef, useEffect } from "react";

import { Coupon } from "@/components/widgets/Coupon/Coupon";
import Typography from "@/components/ui/Typography/Typography";

import { buildTypographyProps } from "@/lib/funnel/mappers";
import type { CouponScreenDefinition, DefaultTexts } from "@/lib/funnel/types";
import { TemplateLayout } from "../layouts/TemplateLayout";
import { createTemplateLayoutProps } from "@/lib/funnel/templateHelpers";
import { cn } from "@/lib/utils";

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

export function CouponTemplate({
  screen,
  onContinue,
  canGoBack,
  onBack,
  screenProgress,
  defaultTexts,
}: CouponTemplateProps) {
  const [copiedCode, setCopiedCode] = useState<string | null>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [animationKey, setAnimationKey] = useState(0);
  const fadeTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const removeTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // Cleanup timeouts on unmount
  useEffect(() => {
    return () => {
      if (fadeTimeoutRef.current) clearTimeout(fadeTimeoutRef.current);
      if (removeTimeoutRef.current) clearTimeout(removeTimeoutRef.current);
    };
  }, []);

  const handleCopyPromoCode = (code: string) => {
    // Clear existing timeouts
    if (fadeTimeoutRef.current) clearTimeout(fadeTimeoutRef.current);
    if (removeTimeoutRef.current) clearTimeout(removeTimeoutRef.current);

    navigator.clipboard.writeText(code);
    setCopiedCode(code);
    setIsVisible(true);
    setAnimationKey(prev => prev + 1); // Force animation restart
    
    // Start fade out animation before removing
    fadeTimeoutRef.current = setTimeout(() => {
      setIsVisible(false);
    }, 2500);
    
    // Remove from DOM after animation completes
    removeTimeoutRef.current = setTimeout(() => {
      setCopiedCode(null);
    }, 3000);
  };

  const couponProps = {
    title: buildTypographyProps(screen.coupon.title, {
      as: "h3" as const,
      defaults: {
        font: "manrope",
        weight: "bold",
        color: "primary",
      },
    }) ?? {
      as: "h3" as const,
      children: screen.coupon.title.text,
    },
    offer: {
      title: buildTypographyProps(screen.coupon.offer.title, {
        as: "h3" as const,
        defaults: {
          font: "manrope",
          weight: "black",
          color: "card",
          size: "4xl",
        },
      }) ?? {
        as: "h3" as const,
        children: screen.coupon.offer.title.text,
      },
      description: buildTypographyProps(screen.coupon.offer.description, {
        as: "p" as const,
        defaults: {
          font: "inter",
          weight: "semiBold",
          color: "card",
        },
      }) ?? {
        as: "p" as const,
        children: screen.coupon.offer.description.text,
      },
    },
    promoCode: buildTypographyProps(screen.coupon.promoCode, {
      as: "span" as const,
      defaults: {
        font: "inter",
        weight: "semiBold",
      },
    }) ?? {
      as: "span" as const,
      children: screen.coupon.promoCode.text,
    },
    footer: buildTypographyProps(screen.coupon.footer, {
      as: "p" as const,
      defaults: {
        font: "inter",
        weight: "medium",
        color: "muted",
        size: "sm",
      },
    }) ?? {
      as: "p" as const,
      children: screen.coupon.footer.text,
    },
    onCopyPromoCode: handleCopyPromoCode,
  };

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

  return (
    <TemplateLayout {...layoutProps}>
      <div className="w-full flex flex-col items-center justify-center mt-[22px]">
        <div className="relative mb-8">
          {/* Copied message positioned above coupon in available space */}
          {copiedCode && (
            <div 
              key={animationKey}
              className={cn(
                "absolute left-1/2 -translate-x-1/2",
                "-top-[56px]", // Position in the space above coupon
                "px-4 py-3 bg-green-50 border border-green-200 rounded-lg shadow-lg",
                "transition-all duration-500 z-10",
                "max-w-[280px]",
                "whitespace-nowrap",
                isVisible 
                  ? "animate-in fade-in slide-in-from-top-2 opacity-100" 
                  : "animate-out fade-out slide-out-to-top-2 opacity-0"
              )}
            >
              <Typography
                as="p"
                size="sm"
                color="success"
                weight="medium"
                align="center"
              >
                {screen.copiedMessage 
                  ? screen.copiedMessage.replace("{code}", copiedCode || "")
                  : `Промокод "${copiedCode}" скопирован!`
                }
              </Typography>
            </div>
          )}

          <Coupon {...couponProps} />
        </div>
      </div>
    </TemplateLayout>
  );
}
