"use client";

import { useState } from "react";
import { Plus, Trash2, ChevronDown, ChevronRight } from "lucide-react";
import { TextInput } from "@/components/ui/TextInput/TextInput";
import { VariableMappingConditionEditor } from "./VariableMappingConditionEditor";
import type { VariableDefinition, VariableMapping, NavigationConditionDefinition } from "@/lib/funnel/types";
import type { BuilderScreen } from "@/lib/admin/builder/types";

interface VariablesConfigProps {
  variables: VariableDefinition[] | undefined;
  onUpdate: (variables: VariableDefinition[] | undefined) => void;
  availableScreens: BuilderScreen[];
}

export function VariablesConfig({ variables = [], onUpdate, availableScreens }: VariablesConfigProps) {
  const [expandedVariables, setExpandedVariables] = useState<Set<number>>(new Set([0]));
  const [expandedMappings, setExpandedMappings] = useState<Set<string>>(new Set());

  const toggleVariable = (index: number) => {
    const newExpanded = new Set(expandedVariables);
    if (newExpanded.has(index)) {
      newExpanded.delete(index);
    } else {
      newExpanded.add(index);
    }
    setExpandedVariables(newExpanded);
  };

  const toggleMapping = (varIndex: number, mapIndex: number) => {
    const key = `${varIndex}-${mapIndex}`;
    const newExpanded = new Set(expandedMappings);
    if (newExpanded.has(key)) {
      newExpanded.delete(key);
    } else {
      newExpanded.add(key);
    }
    setExpandedMappings(newExpanded);
  };

  const isMappingExpanded = (varIndex: number, mapIndex: number) => {
    return expandedMappings.has(`${varIndex}-${mapIndex}`);
  };

  const addVariable = () => {
    const newVariable: VariableDefinition = {
      name: "",
      mappings: [],
      fallback: "",
    };
    const updatedVariables = [...(variables || []), newVariable];
    onUpdate(updatedVariables);
    setExpandedVariables(new Set([...expandedVariables, (variables || []).length]));
  };

  const removeVariable = (index: number) => {
    const newVariables = [...(variables || [])];
    newVariables.splice(index, 1);
    onUpdate(newVariables.length > 0 ? newVariables : undefined);
  };

  const updateVariable = (index: number, updates: Partial<VariableDefinition>) => {
    const newVariables = [...(variables || [])];
    newVariables[index] = { ...newVariables[index], ...updates };
    onUpdate(newVariables);
  };

  const addMapping = (variableIndex: number) => {
    const newMapping: VariableMapping = {
      conditions: [{
        screenId: availableScreens[0]?.id || "",
        conditionType: "values",
        operator: "includesAny",
        values: [],
      }],
      value: "",
    };
    const variable = variables![variableIndex];
    updateVariable(variableIndex, {
      mappings: [...variable.mappings, newMapping],
    });
  };

  const removeMapping = (variableIndex: number, mappingIndex: number) => {
    const variable = variables![variableIndex];
    const newMappings = [...variable.mappings];
    newMappings.splice(mappingIndex, 1);
    updateVariable(variableIndex, { mappings: newMappings });
  };

  const updateMapping = (
    variableIndex: number,
    mappingIndex: number,
    updates: Partial<VariableMapping>
  ) => {
    const variable = variables![variableIndex];
    const newMappings = [...variable.mappings];
    newMappings[mappingIndex] = { ...newMappings[mappingIndex], ...updates };
    updateVariable(variableIndex, { mappings: newMappings });
  };

  const updateCondition = (
    variableIndex: number,
    mappingIndex: number,
    conditionIndex: number,
    updates: Partial<NavigationConditionDefinition>
  ) => {
    const variable = variables![variableIndex];
    const mapping = variable.mappings[mappingIndex];
    const newConditions = [...mapping.conditions];
    newConditions[conditionIndex] = { ...newConditions[conditionIndex], ...updates };
    updateMapping(variableIndex, mappingIndex, { conditions: newConditions });
  };

  if (!variables || variables.length === 0) {
    return (
      <div className="space-y-4 rounded-2xl border border-border/70 bg-background/80 p-5 shadow-sm">
        <div className="space-y-2">
          <h4 className="text-sm font-semibold text-foreground">Переменные</h4>
          <p className="text-xs text-muted-foreground">
            Используйте переменные для динамической подстановки текста на основе ответов пользователя.
            <br />
            Синтаксис: <code className="bg-muted px-1 py-0.5 rounded">{"{{variableName}}"}</code>
          </p>
        </div>
        <button
          onClick={addVariable}
          className="flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 text-xs font-medium text-foreground hover:bg-accent"
        >
          <Plus className="h-4 w-4" />
          Добавить переменную
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-4 rounded-2xl border border-border/70 bg-background/80 p-5 shadow-sm">
      <div className="flex items-center justify-between">
        <h4 className="text-sm font-semibold text-foreground">Переменные</h4>
        <button
          onClick={addVariable}
          className="flex items-center gap-1 rounded-lg border border-border bg-background px-2 py-1 text-xs font-medium text-foreground hover:bg-accent"
        >
          <Plus className="h-3 w-3" />
          Добавить
        </button>
      </div>

      <div className="space-y-3">
        {variables.map((variable, varIndex) => (
          <div
            key={varIndex}
            className="rounded-lg border border-border/50 bg-background/50 p-3 space-y-3"
          >
            {/* Variable Header */}
            <div className="flex items-center gap-2">
              <button
                onClick={() => toggleVariable(varIndex)}
                className="flex items-center text-xs font-medium text-foreground hover:text-foreground/80"
              >
                {expandedVariables.has(varIndex) ? (
                  <ChevronDown className="h-4 w-4 mr-1" />
                ) : (
                  <ChevronRight className="h-4 w-4 mr-1" />
                )}
                {variable.name || `Переменная ${varIndex + 1}`}
              </button>
              <div className="flex-1" />
              <button
                onClick={() => removeVariable(varIndex)}
                className="text-destructive hover:text-destructive/80"
              >
                <Trash2 className="h-3 w-3" />
              </button>
            </div>

            {expandedVariables.has(varIndex) && (
              <div className="space-y-3 pl-3 border-l-2 border-border/30">
                {/* Variable Name */}
                <label className="flex flex-col gap-1">
                  <span className="text-xs font-medium text-muted-foreground">
                    Имя переменной <span className="text-destructive">*</span>
                  </span>
                  <TextInput
                    placeholder="gender"
                    value={variable.name}
                    onChange={(e) => updateVariable(varIndex, { name: e.target.value })}
                    className="text-xs"
                  />
                  <span className="text-[10px] text-muted-foreground">
                    Используйте: <code className="bg-muted px-1 py-0.5 rounded">{`{{${variable.name || "variableName"}}}`}</code>
                  </span>
                </label>

                {/* Mappings */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-medium text-muted-foreground">Правила подстановки</span>
                    <button
                      onClick={() => addMapping(varIndex)}
                      className="flex items-center gap-1 rounded-lg border border-border bg-background px-2 py-1 text-[10px] font-medium text-foreground hover:bg-accent"
                    >
                      <Plus className="h-3 w-3" />
                      Добавить правило
                    </button>
                  </div>

                  {variable.mappings.map((mapping, mapIndex) => {
                    const isExpanded = isMappingExpanded(varIndex, mapIndex);
                    const condition = mapping.conditions[0];
                    const conditionPreview = condition ? `${condition.screenId}: ${(condition.values || []).slice(0, 2).join(", ")}${(condition.values || []).length > 2 ? "..." : ""}` : "Нет условия";
                    
                    return (
                      <div
                        key={mapIndex}
                        className="rounded border border-border/30 bg-background/30 p-2 space-y-2"
                      >
                        {/* Mapping Header - всегда видимый */}
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => toggleMapping(varIndex, mapIndex)}
                            className="flex items-center flex-1 text-[10px] text-foreground hover:text-foreground/80 min-w-0"
                          >
                            {isExpanded ? (
                              <ChevronDown className="h-3 w-3 mr-1 flex-shrink-0" />
                            ) : (
                              <ChevronRight className="h-3 w-3 mr-1 flex-shrink-0" />
                            )}
                            <span className="truncate">
                              {conditionPreview} → <strong>{mapping.value || "(пусто)"}</strong>
                            </span>
                          </button>
                          <button
                            onClick={() => removeMapping(varIndex, mapIndex)}
                            className="text-destructive hover:text-destructive/80 flex-shrink-0"
                          >
                            <Trash2 className="h-3 w-3" />
                          </button>
                        </div>

                        {/* Mapping Content - сворачиваемое */}
                        {isExpanded && (
                          <div className="space-y-2 pl-4 border-l-2 border-border/20">
                            {/* Condition - используем интуитивный селектор */}
                            {mapping.conditions.map((condition, condIndex) => (
                              <div key={condIndex} className="border border-border/20 rounded-md p-2 bg-background/20">
                                <VariableMappingConditionEditor
                                  condition={condition}
                                  allScreens={availableScreens}
                                  onChange={(updated) =>
                                    updateCondition(varIndex, mapIndex, condIndex, updated)
                                  }
                                />
                              </div>
                            ))}

                            {/* Mapping Value */}
                            <label className="flex flex-col gap-1">
                              <span className="text-[10px] text-muted-foreground">Подставить значение</span>
                              <TextInput
                                placeholder="женщин"
                                value={mapping.value}
                                onChange={(e) => updateMapping(varIndex, mapIndex, { value: e.target.value })}
                                className="text-xs"
                              />
                            </label>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>

                {/* Fallback */}
                <label className="flex flex-col gap-1">
                  <span className="text-xs font-medium text-muted-foreground">
                    Значение по умолчанию (fallback)
                  </span>
                  <TextInput
                    placeholder="людей"
                    value={variable.fallback || ""}
                    onChange={(e) => updateVariable(varIndex, { fallback: e.target.value })}
                    className="text-xs"
                  />
                  <span className="text-[10px] text-muted-foreground">
                    Используется если ни одно условие не сработало
                  </span>
                </label>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
