"use client";

import type {
  TrialChoiceScreenDefinition,
  DefaultTexts,
  FunnelAnswers,
  FunnelDefinition,
  ArrowHintPosition,
} from "@/lib/funnel/types";
import { TemplateLayout } from "@/components/funnel/templates/layouts/TemplateLayout";
import { createTemplateLayoutProps } from "@/lib/funnel/templateHelpers";
import { TrialOptionsGrid } from "@/components/widgets/TrialOptionsGrid";
import { ProfileCreated } from "@/components/widgets/ProfileCreated";
import { useState, useMemo, useRef } from "react";
import { usePaymentPlacement } from "@/hooks/payment/usePaymentPlacement";
import { useTrialVariantSelection } from "@/entities/session/payment/TrialVariantSelectionContext";
import { Currency } from "@/shared/types";
import { getFormattedPrice } from "@/shared/utils/price";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";

/**
 * Компонент стрелки-указателя
 * Направление стрелки зависит от того, находится ли она сверху или снизу
 */
function ArrowIcon({ pointsUp }: { pointsUp: boolean }) {
  return (
    <svg
      width="15"
      height="22"
      viewBox="0 0 15 22"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className={cn(!pointsUp && "rotate-180")}
    >
      <g clipPath="url(#clip0_arrow)">
        <path
          d="M8.07009 0.292893C7.67956 -0.097631 7.0464 -0.097631 6.65587 0.292893L0.291916 6.65685C-0.0986075 7.04738 -0.0986075 7.68054 0.291916 8.07107C0.682441 8.46159 1.3156 8.46159 1.70613 8.07107L7.36298 2.41421L13.0198 8.07107C13.4104 8.46159 14.0435 8.46159 14.434 8.07107C14.8246 7.68054 14.8246 7.04738 14.434 6.65685L8.07009 0.292893ZM7.36298 22H8.36298V1H7.36298H6.36298V22H7.36298Z"
          fill="#224E90"
        />
      </g>
      <defs>
        <clipPath id="clip0_arrow">
          <rect width="15" height="22" fill="white" />
        </clipPath>
      </defs>
    </svg>
  );
}

/**
 * Получает CSS стили для позиционирования стрелки
 */
function getArrowPositionStyles(position: ArrowHintPosition): React.CSSProperties {
  const isLeft = position.includes("left");
  
  // Стрелка указывает на центр левой (25% слева) или правой (25% справа) колонки
  if (isLeft) {
    return {
      left: "25%",
      transform: "translateY(-50%) translateX(-50%)",
    };
  }
  return {
    right: "25%",
    transform: "translateY(-50%) translateX(50%)",
  };
}

/**
 * Заменяет переменные в тексте подсказки
 */
function substituteArrowHintVariables(
  text: string,
  maxTrialPrice: string
): string {
  return text.replace(/\{\{maxTrialPrice\}\}/g, maxTrialPrice);
}

interface TrialChoiceTemplateProps {
  funnel: FunnelDefinition;
  screen: TrialChoiceScreenDefinition;
  onContinue: () => void;
  canGoBack: boolean;
  onBack: () => void;
  screenProgress?: { current: number; total: number };
  defaultTexts?: DefaultTexts;
  answers: FunnelAnswers;
}

export function TrialChoiceTemplate(props: TrialChoiceTemplateProps) {
  const {
    funnel,
    screen,
    onContinue,
    canGoBack,
    onBack,
    screenProgress,
    defaultTexts,
    answers,
  } = props;
  // Load trial variants from placement API (same source as TrialPayment)
  const paymentId = "main"; // can be made configurable later
  const { placement, isLoading } = usePaymentPlacement({ funnel, paymentId });

  // Get/set selected variant from context (shared with Payment screen)
  const { selectedVariantId, setSelectedVariantId } = useTrialVariantSelection();

  // Local selection state
  const [selectedId, setSelectedId] = useState<string | null>(selectedVariantId);
  const [showError, setShowError] = useState<boolean>(false);

  // Ref для прокрутки к вариантам триала
  const trialOptionsRef = useRef<HTMLDivElement | null>(null);

  // Получаем email из answers воронки
  // Email хранится как массив строк под ключом с ID email экрана
  // Сначала ищем email экран по template, затем берем его ID
  const emailScreen = funnel.screens.find(s => s.template === 'email');
  const emailScreenId = emailScreen?.id || 'email'; // fallback на 'email' для обратной совместимости
  const email = answers[emailScreenId]?.[0] || 'user@example.com';

  // Получаем настройку подсветки варианта из конфига экрана
  const accentedOptionSetting = screen.accentedOption ?? "server";

  // Map variant -> TrialOption items with server-provided English titles and accent
  const items = useMemo(() => {
    const currency = placement?.currency || Currency.USD;
    const variants = placement?.variants ?? [];

    const TITLES = ["Basic", "Standard", "Popular", "Premium"] as const;
    const list = (variants.length ? variants : new Array(4).fill(null)).map(
      (v, index) => {
        const id = v?.id ?? `stub-${index}`;
        const trialPrice = v?.trialPrice ?? (index + 1) * 100; // cents stub
        const value = getFormattedPrice(trialPrice, currency);
        const title = v?.title ?? TITLES[index] ?? TITLES[TITLES.length - 1];

        return { id, value, title };
      }
    );

    const lastIndex = Math.max(0, list.length - 1);
    
    // Определяем какой индекс подсвечивать
    // Если задан конкретный номер и он существует - используем его
    // Иначе используем серверную логику
    const accentIndex = (() => {
      if (typeof accentedOptionSetting === "number") {
        const targetIndex = accentedOptionSetting - 1; // 1-indexed -> 0-indexed
        // Проверяем что индекс валиден для полученных вариантов
        if (targetIndex >= 0 && targetIndex < list.length) {
          return targetIndex;
        }
        // Fallback: если указанный вариант не существует, используем серверную логику
      }
      // Серверная логика: ищем accent: true или используем последний
      const serverAccentIndex = variants.findIndex(v => v?.accent === true);
      return serverAccentIndex >= 0 ? serverAccentIndex : lastIndex;
    })();

    return list.map((it, index) => {
      const state =
        selectedId === it.id
          ? "selected"
          : index === accentIndex
          ? "accent"
          : "default";
      // When user clicks disabled button, we flag all options with error until a selection is made
      const error = showError && selectedId == null;
      return { ...it, state, error } as const;
    });
  }, [placement, selectedId, showError, accentedOptionSetting]);

  // Вычисляем максимальную цену триала для переменной {{maxTrialPrice}}
  const maxTrialPrice = useMemo(() => {
    const currency = placement?.currency || Currency.USD;
    const variants = placement?.variants ?? [];
    
    if (variants.length === 0) {
      return getFormattedPrice(400, currency); // Fallback stub
    }
    
    const maxPrice = Math.max(...variants.map(v => v?.trialPrice ?? 0));
    return getFormattedPrice(maxPrice, currency);
  }, [placement]);

  // Получаем настройки стрелки-подсказки
  const arrowHintPosition = screen.arrowHint?.position ?? "bottom-right";
  const arrowHintText = screen.arrowHint?.text 
    ? substituteArrowHintVariables(screen.arrowHint.text, maxTrialPrice)
    : `It costs us ${maxTrialPrice} to compensate our team for the work involved in creating your personalized portrait and guide, but please choose the amount you are comfortable with.`;
  
  // Определяем, указывает ли стрелка вверх (top position) или вниз (bottom position)
  const isTopPosition = arrowHintPosition.includes("top");

  const isActionDisabled = selectedId == null;

  const layoutProps = createTemplateLayoutProps(
    screen,
    { canGoBack, onBack },
    screenProgress,
    {
      preset: "center",
      actionButton: {
        defaultText:
          screen.bottomActionButton?.text ||
          defaultTexts?.continueButton ||
          "Next",
        disabled: isActionDisabled,
        onClick: onContinue,
        onDisabledClick: () => {
          if (isActionDisabled) {
            setShowError(true);
            // Прокручиваем к вариантам триала
            if (trialOptionsRef.current) {
              trialOptionsRef.current.scrollIntoView({
                behavior: 'smooth',
                block: 'center',
              });
            }
          }
        },
      },
    }
  );

  // Show loader while loading placement (like in Payment)
  if (isLoading || !placement) {
    return (
      <div className="w-full min-h-dvh max-w-[560px] mx-auto flex items-center justify-center">
        <Spinner className="size-8" />
      </div>
    );
  }

  return (
    <TemplateLayout 
      {...layoutProps}
      contentProps={{ className: "p-0 pt-0" }}
      childrenWrapperProps={{ className: "mt-0" }}
    >
      <div className="flex flex-col w-full px-6 pb-[82px]">
        {/* Виджет созданного профиля - без верхнего отступа */}
        <ProfileCreated email={email} />

        {/* Первый текстовый блок */}
        <p className="text-[#2C2C2C] text-center font-inter text-[15px] font-medium leading-[125%] mt-[14px]">
          You&apos;re just one step away from discovering the face of your true soulmate — the person whose energy aligns perfectly with yours. This personalized experience, created by professionals through a precise analysis of your energy, compatibility, and subconscious love patterns, also includes the &quot;Finding the One Guide&quot; — a profound journey that reveals why your past relationships were the way they were and how to finally open yourself to real, lasting love. It has already helped millions find their true partner and harmony in love.
          <br />
          <br />
          Your portrait and guide — which could completely transform how you see love — are almost ready! Before we send them, we invite you to choose the amount you feel is fair to unlock access.
        </p>

        {/* Второй текстовый блок (список) */}
        <div className="text-[#2C2C2C] font-inter text-[15px] font-medium leading-[125%] mt-[14px]">
          <ul className="space-y-3 list-disc pl-6">
            <li>See the face of the person energetically connected to you — the one truly meant for you;</li>
            <li>Understand which emotional and energetic patterns have kept you from meeting &quot;the one&quot;;</li>
            <li>Recognize why the same relationship cycles keep repeating — and learn how to break them;</li>
            <li>Save hundreds of dollars on shallow compatibility tests and guesswork — this is a deep, personal exploration of your love energy;</li>
            <li>You will receive not only your personalized portrait but also powerful insights into your emotional energy — who truly nourishes it, who drains it, and how these invisible exchanges shape your relationships.</li>
          </ul>
        </div>

        {/* Третий текстовый блок */}
        <p className="text-[#2C2C2C] text-center font-sans text-[15px] font-medium leading-[125%] mt-[14px]">
          Creating your portrait and guide costs us $13.67, but you can choose the amount that feels right to you.
        </p>

        {/* При позиции сверху: сначала текст + стрелка, потом сетка */}
        {isTopPosition && (
          <div className="flex flex-col gap-[9px] items-end w-full mt-[14px]">
            {/* Текст над стрелочкой (при позиции сверху) */}
            <p className="text-[#0244A5] font-sans text-[15px] font-semibold leading-[125%] w-full">
              {arrowHintText}
            </p>

            {/* Контейнер стрелочки */}
            <div className="relative h-[22px] w-full">
              <div 
                className="absolute top-1/2"
                style={getArrowPositionStyles(arrowHintPosition)}
              >
                <ArrowIcon pointsUp={false} />
              </div>
            </div>
          </div>
        )}

        {/* TrialOptionsGrid с ref для прокрутки */}
        <div ref={trialOptionsRef} className="mt-[14px]">
          <TrialOptionsGrid
            className="w-full"
            items={items}
            onItemClick={(id) => {
              setSelectedId(id);
              setSelectedVariantId(id); // Save to context for Payment screen
              if (showError) setShowError(false);
            }}
          />
        </div>

        {/* При позиции снизу: сначала сетка, потом стрелка + текст */}
        {!isTopPosition && (
          <div className="flex flex-col gap-[9px] items-end w-full mt-[14px]">
            {/* Контейнер стрелочки */}
            <div className="relative h-[22px] w-full">
              <div 
                className="absolute top-1/2"
                style={getArrowPositionStyles(arrowHintPosition)}
              >
                <ArrowIcon pointsUp={true} />
              </div>
            </div>

            {/* Текст под стрелочкой */}
            <p className="text-[#0244A5] font-sans text-[15px] font-semibold leading-[125%] w-full">
              {arrowHintText}
            </p>
          </div>
        )}
      </div>
    </TemplateLayout>
  );
}
