import { TextInput } from "@/components/ui/TextInput/TextInput";
import { Button } from "@/components/ui/button";
import { Trash2 } from "lucide-react";
import { TemplateConfig } from "@/components/admin/builder/templates";
import { ScreenVariantsConfig } from "../forms/ScreenVariantsConfig";
import {
  useBuilderDispatch,
  useBuilderState,
} from "@/lib/admin/builder/context";
import { Section } from "./Section";
import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { ScreenDefinition } from "@/lib/funnel/types";

interface ScreenSettingsPanelProps {
  screen: BuilderScreen;
}

export function ScreenSettingsPanel({ screen }: ScreenSettingsPanelProps) {
  const state = useBuilderState();
  const dispatch = useBuilderDispatch();

  const handleScreenIdChange = (currentId: string, newId: string) => {
    if (newId === currentId) return;

    // Разрешаем пустые ID для полного переименования
    if (newId.trim() === "") {
      dispatch({
        type: "update-screen",
        payload: {
          screenId: currentId,
          screen: { id: newId },
        },
      });
      return;
    }

    // Обновляем ID экрана
    dispatch({
      type: "update-screen",
      payload: {
        screenId: currentId,
        screen: { id: newId },
      },
    });

    // Если это был первый экран в мета данных, обновляем и там
    if (state.meta.firstScreenId === currentId) {
      dispatch({ type: "set-meta", payload: { firstScreenId: newId } });
    }
  };

  const handleTemplateUpdate = (
    screenId: string,
    updates: Partial<ScreenDefinition>
  ) => {
    dispatch({
      type: "update-screen",
      payload: { screenId, screen: updates },
    });
  };

  const handleVariantsChange = (
    screenId: string,
    variants: BuilderScreen["variants"]
  ) => {
    dispatch({
      type: "update-screen",
      payload: { screenId, screen: { variants } },
    });
  };

  const handleDeleteScreen = (screenId: string) => {
    if (!confirm("Вы уверены, что хотите удалить этот экран?")) return;
    dispatch({ type: "remove-screen", payload: { screenId } });
  };

  return (
    <>
      <div className="flex items-center justify-between px-4 py-3 border-b border-border/60 bg-muted/30">
        <div className="flex-1">
          <div className="text-sm font-semibold text-foreground truncate">
            {screen.title?.text || "Без названия"}
          </div>
          <span className="text-xs text-muted-foreground">
            {screen.template}
          </span>
        </div>
        <Button
          variant="ghost"
          className="h-8 px-2 text-destructive hover:text-destructive"
          onClick={() => handleDeleteScreen(screen.id)}
        >
          <Trash2 className="h-4 w-4" />
        </Button>
      </div>

      <Section title="Общие данные">
        <TextInput
          label="ID экрана"
          value={screen.id}
          onChange={(e) => handleScreenIdChange(screen.id, e.target.value)}
        />
      </Section>

      <Section title="Контент и оформление">
        <TemplateConfig
          screen={screen}
          onUpdate={(updates) => handleTemplateUpdate(screen.id, updates)}
        />
      </Section>

      <Section title="Вариативность">
        <ScreenVariantsConfig
          screen={screen}
          allScreens={state.screens}
          onChange={(variants) => handleVariantsChange(screen.id, variants)}
        />
      </Section>
    </>
  );
}
