import { useMemo } from "react";
import { TextInput } from "@/components/ui/TextInput/TextInput";
import { useBuilderDispatch, useBuilderState } from "@/lib/admin/builder/context";
import { Section } from "./Section";
import type { BuilderScreen } from "@/lib/admin/builder/types";

export function FunnelSettingsPanel() {
  const state = useBuilderState();
  const dispatch = useBuilderDispatch();

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

  const handleMetaChange = (field: keyof typeof state.meta, value: string) => {
    dispatch({ type: "set-meta", payload: { [field]: value } });
  };

  const handleFirstScreenChange = (value: string) => {
    dispatch({ type: "set-meta", payload: { firstScreenId: value } });
  };

  const handleDefaultTextsChange = (
    field: keyof NonNullable<typeof state.defaultTexts>,
    value: string
  ) => {
    dispatch({ type: "set-default-texts", payload: { [field]: value } });
  };

  return (
    <>
      <Section title="Настройки воронки">
        <div className="space-y-3">
          <TextInput
            label="ID воронки"
            value={state.meta.id}
            onChange={(e) => handleMetaChange("id", e.target.value)}
          />
          <TextInput
            label="Название"
            value={state.meta.title || ""}
            onChange={(e) => handleMetaChange("title", e.target.value)}
          />
          <TextInput
            label="Описание"
            value={state.meta.description || ""}
            onChange={(e) => handleMetaChange("description", e.target.value)}
          />
          <label className="flex flex-col gap-2 text-sm">
            <span className="text-muted-foreground">Первый экран</span>
            <select
              className="rounded-lg border border-border bg-background px-3 py-2"
              value={state.meta.firstScreenId || ""}
              onChange={(e) => handleFirstScreenChange(e.target.value)}
            >
              <option value="">—</option>
              {screenOptions.map((screen) => (
                <option key={screen.id} value={screen.id}>
                  {screen.title}
                </option>
              ))}
            </select>
          </label>
        </div>
      </Section>

      <Section title="Дефолтные тексты">
        <div className="space-y-3">
          <TextInput
            label='Кнопка "Next"'
            placeholder="Next"
            value={state.defaultTexts?.nextButton || ""}
            onChange={(e) => handleDefaultTextsChange("nextButton", e.target.value)}
          />
          <TextInput
            label='Кнопка "Continue"'
            placeholder="Continue"
            value={state.defaultTexts?.continueButton || ""}
            onChange={(e) => handleDefaultTextsChange("continueButton", e.target.value)}
          />
        </div>
      </Section>
    </>
  );
}
