"use client";

import { useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { ScreenDefinition, ScreenVariantDefinition } from "@/lib/funnel/types";
import { VariantPanel, type VariantDefinition } from "./variants";

interface ScreenVariantsConfigProps {
  screen: BuilderScreen;
  allScreens: BuilderScreen[];
  onChange: (variants: ScreenVariantDefinition<ScreenDefinition>[]) => void;
}

/**
 * Компонент для настройки вариантов экрана
 * Разбит на модули для лучшей поддерживаемости
 */
export function ScreenVariantsConfig({
  screen,
  allScreens,
  onChange,
}: ScreenVariantsConfigProps) {
  const variants = useMemo(
    () => (screen.variants ?? []) as VariantDefinition[],
    [screen.variants]
  );

  const [expandedVariant, setExpandedVariant] = useState<number | null>(() =>
    variants.length > 0 ? 0 : null
  );

  useEffect(() => {
    if (variants.length === 0) {
      setExpandedVariant(null);
    } else if (expandedVariant !== null && expandedVariant >= variants.length) {
      setExpandedVariant(variants.length - 1);
    }
  }, [variants.length, expandedVariant]);

  const handleAddVariant = () => {
    const firstScreenId = allScreens[0]?.id ?? "";
    const newVariant: VariantDefinition = {
      conditions: [
        {
          screenId: firstScreenId,
          operator: "includesAny",
          optionIds: [],
        },
      ],
      overrides: {},
    };

    const updatedVariants = [...variants, newVariant];
    onChange(updatedVariants);
    setExpandedVariant(updatedVariants.length - 1);
  };

  const handleVariantChange = (index: number, updatedVariant: VariantDefinition) => {
    const updatedVariants = [...variants];
    updatedVariants[index] = updatedVariant;
    onChange(updatedVariants);
  };

  const handleVariantDelete = (index: number) => {
    const updatedVariants = variants.filter((_, i) => i !== index);
    onChange(updatedVariants);

    if (expandedVariant === index) {
      setExpandedVariant(null);
    } else if (expandedVariant !== null && expandedVariant > index) {
      setExpandedVariant(expandedVariant - 1);
    }
  };

  const handleToggleVariant = (index: number) => {
    setExpandedVariant(expandedVariant === index ? null : index);
  };

  if (allScreens.length === 0) {
    return (
      <div className="text-sm text-muted-foreground">
        Недостаточно экранов для создания вариантов
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold">Варианты экрана</h3>
        <Button
          variant="outline"
          onClick={handleAddVariant}
          className="h-8 px-3 text-sm"
        >
          Добавить вариант
        </Button>
      </div>

      {variants.length === 0 ? (
        <div className="text-sm text-muted-foreground text-center py-6 border border-dashed border-border rounded-lg">
          Нет вариантов. Добавьте вариант для показа разного контента на основе
          ответов пользователя.
        </div>
      ) : (
        <div className="space-y-2">
          {variants.map((variant, index) => (
            <VariantPanel
              key={index}
              variant={variant}
              index={index}
              isExpanded={expandedVariant === index}
              baseScreen={screen}
              allScreens={allScreens}
              onToggle={() => handleToggleVariant(index)}
              onChange={(updatedVariant) =>
                handleVariantChange(index, updatedVariant)
              }
              onDelete={() => handleVariantDelete(index)}
            />
          ))}
        </div>
      )}
    </div>
  );
}
