"use client";

import { useCallback, useMemo } from "react";
import { TemplateConfig } from "@/components/admin/builder/templates";
import { Button } from "@/components/ui/button";
import {
  extractVariantOverrides,
  mergeScreenWithOverrides,
} from "@/lib/admin/builder/variants";
import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { ScreenDefinition } from "@/lib/funnel/types";
import type { VariantOverridesEditorProps } from "./types";

/**
 * Редактор переопределений для варианта экрана
 * Позволяет изменить любые настройки базового экрана для конкретного варианта
 */
export function VariantOverridesEditor({
  baseScreen,
  overrides,
  onChange,
}: VariantOverridesEditorProps) {
  const baseWithoutVariants = useMemo(() => {
    const clone = mergeScreenWithOverrides(baseScreen, {});
    const sanitized = { ...clone } as BuilderScreen;
    if ("variants" in sanitized) {
      delete (sanitized as Partial<BuilderScreen>).variants;
    }
    return sanitized;
  }, [baseScreen]);

  const mergedScreen = useMemo(
    () =>
      mergeScreenWithOverrides<BuilderScreen>(
        baseWithoutVariants,
        overrides
      ) as BuilderScreen,
    [baseWithoutVariants, overrides]
  );

  const handleUpdate = useCallback(
    (updates: Partial<ScreenDefinition>) => {
      const nextScreen = mergeScreenWithOverrides<BuilderScreen>(
        mergedScreen,
        updates as Partial<BuilderScreen>
      );
      const nextOverrides = extractVariantOverrides(
        baseWithoutVariants,
        nextScreen
      );
      onChange(nextOverrides);
    },
    [baseWithoutVariants, mergedScreen, onChange]
  );

  return (
    <div className="space-y-3">
      <TemplateConfig screen={mergedScreen} onUpdate={handleUpdate} />
      <Button
        variant="outline"
        className="h-8 px-3 text-xs"
        onClick={() => onChange({})}
      >
        Сбросить переопределения
      </Button>
    </div>
  );
}
