"use client";

import { Button } from "@/components/ui/button";
import { Trash2 } from "lucide-react";
import { VariantConditionEditor } from "../forms/variants/VariantConditionEditor";
import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { NavigationRuleDefinition } from "@/lib/funnel/types";

interface NavigationRuleEditorProps {
  rule: NavigationRuleDefinition;
  ruleIndex: number;
  screen: BuilderScreen;
  allScreens: BuilderScreen[];
  screenOptions: Array<{ id: string; title?: string }>;
  onRuleChange: (updatedRule: NavigationRuleDefinition) => void;
  onRuleDelete: () => void;
}

/**
 * Редактор одного правила навигации
 */
export function NavigationRuleEditor({
  rule,
  ruleIndex,
  screen,
  allScreens,
  screenOptions,
  onRuleChange,
  onRuleDelete,
}: NavigationRuleEditorProps) {
  return (
    <div className="flex flex-col gap-3 rounded-xl border border-border/80 bg-background/60 p-3">
      {/* Заголовок правила */}
      <div className="flex items-center justify-between">
        <span className="text-xs font-semibold uppercase text-muted-foreground">
          Правило {ruleIndex + 1}
        </span>
        <Button
          variant="ghost"
          className="h-8 px-2 text-destructive hover:bg-destructive/10"
          onClick={onRuleDelete}
        >
          <Trash2 className="h-3 w-3 mr-1" />
          <span className="text-xs">Удалить</span>
        </Button>
      </div>

      {/* Условия */}
      <div className="space-y-2">
        <label className="text-xs font-semibold text-foreground">
          Условия (все должны выполняться)
        </label>
        
        {rule.conditions.map((condition, conditionIndex) => (
          <div key={conditionIndex} className="relative">
            <VariantConditionEditor
              condition={condition}
              allScreens={allScreens}
              onChange={(updatedCondition) => {
                const updatedConditions = [...rule.conditions];
                updatedConditions[conditionIndex] = updatedCondition;
                onRuleChange({
                  ...rule,
                  conditions: updatedConditions,
                });
              }}
            />
            
            {rule.conditions.length > 1 && (
              <Button
                variant="ghost"
                className="absolute top-0 right-0 h-6 px-2 text-destructive"
                onClick={() => {
                  const updatedConditions = rule.conditions.filter(
                    (_, i) => i !== conditionIndex
                  );
                  onRuleChange({
                    ...rule,
                    conditions: updatedConditions,
                  });
                }}
              >
                <Trash2 className="h-3 w-3" />
              </Button>
            )}
          </div>
        ))}

        {/* Кнопка добавления условия */}
        <Button
          variant="outline"
          className="w-full h-8 text-xs"
          onClick={() => {
            const isListType = screen.template === "list";
            const newCondition = isListType
              ? {
                  screenId: screen.id,
                  conditionType: "options" as const,
                  operator: "includesAny" as const,
                  optionIds: [],
                }
              : {
                  screenId: screen.id,
                  conditionType: "unleash" as const,
                  operator: "includesAny" as const,
                  unleashFlag: "",
                  unleashVariants: [],
                };

            onRuleChange({
              ...rule,
              conditions: [...rule.conditions, newCondition],
            });
          }}
        >
          + Добавить условие
        </Button>
      </div>

      {/* Целевой экран */}
      <div className="space-y-1">
        <label className="text-xs font-semibold text-foreground">
          Переход на экран
        </label>
        <select
          value={rule.nextScreenId}
          onChange={(e) =>
            onRuleChange({
              ...rule,
              nextScreenId: e.target.value,
            })
          }
          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
        >
          <option value="">Выберите экран</option>
          {screenOptions
            .filter((s) => s.id !== screen.id)
            .map((s) => (
              <option key={s.id} value={s.id}>
                {s.title || s.id}
              </option>
            ))}
        </select>
      </div>
    </div>
  );
}
