"use client";

import { ChevronDown, ChevronRight, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { VariantConditionEditor } from "./VariantConditionEditor";
import { VariantOverridesEditor } from "./VariantOverridesEditor";
import type { VariantPanelProps } from "./types";
import { ensureCondition } from "./utils";

/**
 * Панель управления одним вариантом экрана
 * Включает условия показа и переопределения настроек
 */
export function VariantPanel({
  variant,
  index,
  isExpanded,
  baseScreen,
  allScreens,
  onToggle,
  onChange,
  onDelete,
}: VariantPanelProps) {
  const condition = ensureCondition(variant, allScreens[0]?.id ?? "");

  return (
    <div className="border border-border rounded-lg overflow-hidden">
      {/* Header */}
      <div
        className="flex items-center justify-between p-3 bg-muted/30 cursor-pointer hover:bg-muted/50"
        onClick={onToggle}
      >
        <div className="flex items-center gap-2">
          {isExpanded ? (
            <ChevronDown className="h-4 w-4" />
          ) : (
            <ChevronRight className="h-4 w-4" />
          )}
          <span className="text-sm font-medium">Вариант {index + 1}</span>
        </div>
        <Button
          variant="ghost"
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
          className="h-7 w-7 p-0"
        >
          <Trash2 className="h-4 w-4" />
        </Button>
      </div>

      {/* Body */}
      {isExpanded && (
        <div className="p-3 space-y-4">
          {/* Условие */}
          <div>
            <h4 className="text-sm font-semibold mb-2">Условие показа</h4>
            <VariantConditionEditor
              condition={condition}
              allScreens={allScreens}
              onChange={(newCondition) =>
                onChange({ ...variant, conditions: [newCondition] })
              }
            />
          </div>

          {/* Переопределения */}
          <div>
            <h4 className="text-sm font-semibold mb-2">
              Переопределения настроек
            </h4>
            <VariantOverridesEditor
              baseScreen={baseScreen}
              overrides={variant.overrides ?? {}}
              onChange={(newOverrides) =>
                onChange({ ...variant, overrides: newOverrides })
              }
            />
          </div>
        </div>
      )}
    </div>
  );
}
