import { useMemo } from "react";
import { Button } from "@/components/ui/button";
import {
  useBuilderDispatch,
  useBuilderState,
} from "@/lib/admin/builder/context";
import { Section } from "./Section";
import { NavigationRuleEditor } from "./NavigationRuleEditor";
import { NavigationRulesHelper } from "./NavigationRulesHelper";
import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { NavigationRuleDefinition } from "@/lib/funnel/types";

interface NavigationPanelProps {
  screen: BuilderScreen;
}

export function NavigationPanel({ screen }: NavigationPanelProps) {
  const state = useBuilderState();
  const dispatch = useBuilderDispatch();

  const screenOptions = useMemo(
    () => state.screens.map((s) => ({ id: s.id, title: s.title?.text })),
    [state.screens]
  );

  const getScreenById = (screenId: string): BuilderScreen | undefined =>
    state.screens.find((item) => item.id === screenId);

  const updateNavigation = (
    targetScreen: BuilderScreen,
    navigationUpdates: Partial<BuilderScreen["navigation"]> = {}
  ) => {
    dispatch({
      type: "update-navigation",
      payload: {
        screenId: targetScreen.id,
        navigation: {
          defaultNextScreenId:
            navigationUpdates.defaultNextScreenId ??
            targetScreen.navigation?.defaultNextScreenId,
          rules:
            navigationUpdates.rules ?? targetScreen.navigation?.rules ?? [],
          isEndScreen:
            navigationUpdates.isEndScreen ??
            targetScreen.navigation?.isEndScreen,
          onBackScreenId:
            navigationUpdates.onBackScreenId ??
            targetScreen.navigation?.onBackScreenId,
        },
      },
    });
  };

  const handleDefaultNextChange = (
    screenId: string,
    nextScreenId: string | ""
  ) => {
    const targetScreen = getScreenById(screenId);
    if (!targetScreen) return;

    updateNavigation(targetScreen, {
      defaultNextScreenId: nextScreenId || undefined,
    });
  };

  const updateRules = (screenId: string, rules: NavigationRuleDefinition[]) => {
    const targetScreen = getScreenById(screenId);
    if (!targetScreen) return;

    updateNavigation(targetScreen, { rules });
  };

  const handleAddRule = (targetScreen: BuilderScreen) => {
    const rules = targetScreen.navigation?.rules ?? [];
    const firstScreenOption = screenOptions.find(
      (s) => s.id !== targetScreen.id
    );
    
    // Создаем базовое условие в зависимости от типа экрана
    const isListType = targetScreen.template === "list";
    const baseCondition = isListType
      ? {
          screenId: targetScreen.id,
          conditionType: "options" as const,
          operator: "includesAny" as const,
          optionIds: [],
        }
      : {
          screenId: targetScreen.id,
          conditionType: "unleash" as const,
          operator: "includesAny" as const,
          unleashFlag: "",
          unleashVariants: [],
        };
    
    updateRules(targetScreen.id, [
      ...rules,
      {
        conditions: [baseCondition],
        nextScreenId: firstScreenOption?.id || "",
      },
    ]);
  };

  const handleRemoveRule = (screenId: string, ruleIndex: number) => {
    const targetScreen = getScreenById(screenId);
    if (!targetScreen) return;

    const rules = targetScreen.navigation?.rules ?? [];
    updateRules(
      screenId,
      rules.filter((_, index) => index !== ruleIndex)
    );
  };

  return (
    <>
      <Section title="Навигация">
        {/* Чекбокс для финального экрана */}
        <label className="flex items-center gap-2 cursor-pointer">
          <input
            type="checkbox"
            checked={screen.navigation?.isEndScreen ?? false}
            onChange={(e) => {
              updateNavigation(screen, { isEndScreen: e.target.checked });
            }}
            className="rounded border-border"
          />
          <div className="flex flex-col">
            <span className="text-sm font-medium text-foreground">
              Финальный экран
            </span>
            <span className="text-xs text-muted-foreground">
              Этот экран завершает воронку (переход не требуется)
            </span>
          </div>
        </label>

        {/* Обычная навигация - показываем только если НЕ финальный экран */}
        {!screen.navigation?.isEndScreen && (
          <label className="flex flex-col gap-2">
            <span className="text-sm font-medium text-muted-foreground">
              Экран по умолчанию
            </span>
            <select
              className="rounded-lg border border-border bg-background px-3 py-2 text-sm"
              value={screen.navigation?.defaultNextScreenId ?? ""}
              onChange={(e) =>
                handleDefaultNextChange(screen.id, e.target.value)
              }
            >
              <option value="">—</option>
              {screenOptions
                .filter((s) => s.id !== screen.id)
                .map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.title}
                  </option>
                ))}
            </select>
          </label>
        )}

        {/* Экран при попытке перехода назад */}
        {/* {!screen.navigation?.isEndScreen && ( */}
        <label className="flex flex-col gap-2 mt-3">
          <span className="text-sm font-medium text-muted-foreground">
            Экран при попытке перехода назад
          </span>
          <select
            className="rounded-lg border border-border bg-background px-3 py-2 text-sm"
            value={screen.navigation?.onBackScreenId ?? ""}
            onChange={(e) =>
              updateNavigation(screen, {
                ...(screen.navigation ?? {}),
                onBackScreenId: e.target.value || undefined,
              })
            }
          >
            <option value="">—</option>
            {screenOptions
              .filter((s) => s.id !== screen.id)
              .map((s) => (
                <option key={s.id} value={s.id}>
                  {s.title}
                </option>
              ))}
          </select>
        </label>
        {/* )} */}
      </Section>

      {!screen.navigation?.isEndScreen && (
        <Section title="Правила переходов" description="Условная навигация">
          <div className="flex flex-col gap-3">
            {/* Подсказка о возможностях */}
            <NavigationRulesHelper />

            <div className="flex items-center justify-between">
              <p className="text-xs text-muted-foreground">
                Направляйте пользователей на разные экраны в зависимости от условий.
              </p>
              <Button
                className="h-8 w-8 p-0 flex items-center justify-center"
                onClick={() => handleAddRule(screen)}
              >
                <span className="text-lg leading-none">+</span>
              </Button>
            </div>

            {(screen.navigation?.rules ?? []).length === 0 && (
              <div className="rounded-lg border border-border/60 bg-muted/30 p-3 text-center text-xs text-muted-foreground">
                Правил пока нет
              </div>
            )}

            {(screen.navigation?.rules ?? []).map((rule, ruleIndex) => (
              <NavigationRuleEditor
                key={ruleIndex}
                rule={rule}
                ruleIndex={ruleIndex}
                screen={screen}
                allScreens={state.screens}
                screenOptions={screenOptions}
                onRuleChange={(updatedRule) => {
                  const rules = screen.navigation?.rules ?? [];
                  const updatedRules = [...rules];
                  updatedRules[ruleIndex] = updatedRule;
                  updateRules(screen.id, updatedRules);
                }}
                onRuleDelete={() => handleRemoveRule(screen.id, ruleIndex)}
              />
            ))}
          </div>
        </Section>
      )}
    </>
  );
}
