"use client";

import type {
  TrialChoiceScreenDefinition,
  DefaultTexts,
  FunnelAnswers,
  FunnelDefinition,
} 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";

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';

  // Map variant -> TrialOption items with server-provided English titles and accent (last as fallback)
  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);
    return list.map((it, index) => {
      const variant = variants[index];
      const accentFromApi = variant?.accent === true;
      const state =
        selectedId === it.id
          ? "selected"
          : accentFromApi || index === lastIndex
          ? "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]);

  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>

        {/* 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>

        {/* Блок со стрелочкой и текстом под вариантами */}
        <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={{ 
                right: '25%', // Правая колонка = 50% ширины, ее центр = 25% от правого края
                transform: 'translateY(-50%) translateX(50%)' // Центрируем саму стрелочку
              }}
            >
              <svg 
                width="15" 
                height="22" 
                viewBox="0 0 15 22" 
                fill="none" 
                xmlns="http://www.w3.org/2000/svg"
              >
                <g clipPath="url(#clip0_570_2828)">
                  <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_570_2828">
                    <rect width="15" height="22" fill="white"/>
                  </clipPath>
                </defs>
              </svg>
            </div>
          </div>

          {/* Текст под стрелочкой */}
          <p className="text-[#0244A5] font-sans text-[15px] font-semibold leading-[125%] w-full">
            It costs us $13.67 to compensate our team for the work involved in creating your personalized portrait and guide, but please choose the amount you are comfortable with.
          </p>
        </div>
      </div>
    </TemplateLayout>
  );
}
