"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { TextInput } from "@/components/ui/TextInput/TextInput";
import { TextAreaInput } from "@/components/ui/TextAreaInput/TextAreaInput";
import { ArrowDown, ArrowUp, ChevronDown, ChevronRight, Plus, Trash2 } from "lucide-react";
import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { SpecialOfferScreenDefinition, TypographyVariant } from "@/lib/funnel/types";

interface SpecialOfferScreenConfigProps {
  screen: BuilderScreen & { template: "specialOffer" };
  onUpdate: (updates: Partial<SpecialOfferScreenDefinition>) => void;
}

function CollapsibleSection({
  title,
  children,
  storagePrefix = "special-offer",
  defaultExpanded = false,
}: {
  title: string;
  children: React.ReactNode;
  storagePrefix?: string;
  defaultExpanded?: boolean;
}) {
  const storageKey = `${storagePrefix}-section-${title.toLowerCase().replace(/\s+/g, "-")}`;
  const [isExpanded, setIsExpanded] = useState(() => {
    if (typeof window === "undefined") return defaultExpanded;
    const stored = sessionStorage.getItem(storageKey);
    return stored !== null ? JSON.parse(stored) : defaultExpanded;
  });

  const handleToggle = () => {
    const next = !isExpanded;
    setIsExpanded(next);
    if (typeof window !== "undefined") {
      sessionStorage.setItem(storageKey, JSON.stringify(next));
    }
  };

  return (
    <div className="space-y-3">
      <button
        type="button"
        onClick={handleToggle}
        className="flex w-full items-center gap-2 text-left text-sm font-medium text-foreground hover:text-primary transition-colors"
      >
        {isExpanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
        {title}
      </button>
      {isExpanded && <div className="ml-6 space-y-3">{children}</div>}
    </div>
  );
}

export function SpecialOfferScreenConfig({ screen, onUpdate }: SpecialOfferScreenConfigProps) {
  const specialScreen = screen as SpecialOfferScreenDefinition;

  const updateText = (field: keyof NonNullable<SpecialOfferScreenDefinition["text"]>, value: TypographyVariant | undefined) => {
    const base = specialScreen.text ?? {};
    const next = { ...base, [field]: value } as NonNullable<SpecialOfferScreenDefinition["text"]>;
    onUpdate({ text: next });
  };

  const handleTextChange = (
    field: keyof NonNullable<SpecialOfferScreenDefinition["text"]>,
    text: string
  ) => {
    const current = (specialScreen.text?.[field] ?? {}) as TypographyVariant;
    const trimmed = text; // allow empty, higher-level validation can handle required rules
    const nextValue: TypographyVariant | undefined =
      trimmed.length > 0 ? { ...current, text: trimmed } : { ...current, text: "" };
    updateText(field, nextValue);
  };

  // description is a composite object: { trialPrice, text, oldTrialPrice }
  const updateDescriptionPart = (
    part: "trialPrice" | "text" | "oldTrialPrice",
    value: TypographyVariant | undefined
  ) => {
    const baseText = specialScreen.text ?? {};
    const currentDescription = baseText.description ?? {};
    const nextDescription = {
      ...currentDescription,
      [part]: value,
    } as NonNullable<SpecialOfferScreenDefinition["text"]>["description"];

    onUpdate({ text: { ...baseText, description: nextDescription } });
  };

  const handleDescriptionTextChange = (
    part: "trialPrice" | "text" | "oldTrialPrice",
    text: string
  ) => {
    const current = (specialScreen.text?.description?.[part] ?? {}) as TypographyVariant;
    const nextValue: TypographyVariant | undefined = { ...current, text };
    updateDescriptionPart(part, nextValue);
  };

  const addAdvantageItem = () => {
    const items = specialScreen.advantages?.items ?? [];
    const next = [...items, { icon: { text: "" }, text: { text: "" } }];
    onUpdate({ advantages: { items: next } });
  };

  const removeAdvantageItem = (index: number) => {
    const items = specialScreen.advantages?.items ?? [];
    const next = items.filter((_, i) => i !== index);
    onUpdate({ advantages: { items: next } });
  };

  const moveAdvantageItem = (index: number, direction: -1 | 1) => {
    const items = [...(specialScreen.advantages?.items ?? [])];
    const target = index + direction;
    if (target < 0 || target >= items.length) return;
    const [cur] = items.splice(index, 1);
    items.splice(target, 0, cur);
    onUpdate({ advantages: { items } });
  };

  const updateAdvantageItem = (
    index: number,
    field: "icon" | "text",
    text: string
  ) => {
    const items = specialScreen.advantages?.items ?? [];
    const current = items[index] ?? { icon: { text: "" }, text: { text: "" } };
    const nextItem = {
      ...current,
      [field]: { ...(current[field] ?? {}), text },
    } as NonNullable<SpecialOfferScreenDefinition["advantages"]>["items"][number];
    const next = items.map((it, i) => (i === index ? nextItem : it));
    onUpdate({ advantages: { items: next } });
  };

  return (
    <div className="space-y-6">
      <CollapsibleSection title="Тексты">
        <div className="space-y-3">
          <TextAreaInput
            label="Заголовок"
            rows={2}
            className="resize-y"
            value={specialScreen.text?.title?.text ?? ""}
            onChange={(e) => handleTextChange("title", e.target.value)}
          />
          <TextAreaInput
            label="Подзаголовок"
            rows={2}
            className="resize-y"
            value={specialScreen.text?.subtitle?.text ?? ""}
            onChange={(e) => handleTextChange("subtitle", e.target.value)}
          />
          <TextInput
            label="Цена trial (подстановка {{trialPrice}})"
            value={specialScreen.text?.description?.trialPrice?.text ?? ""}
            onChange={(e) => handleDescriptionTextChange("trialPrice", e.target.value)}
          />
          <TextAreaInput
            label="Описание (текст между ценами)"
            rows={2}
            className="resize-y"
            value={specialScreen.text?.description?.text?.text ?? ""}
            onChange={(e) => handleDescriptionTextChange("text", e.target.value)}
          />
          <TextInput
            label="Старая цена trial (подстановка {{oldTrialPrice}})"
            value={specialScreen.text?.description?.oldTrialPrice?.text ?? ""}
            onChange={(e) => handleDescriptionTextChange("oldTrialPrice", e.target.value)}
          />
        </div>
      </CollapsibleSection>

      <CollapsibleSection title="Преимущества" defaultExpanded>
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <h4 className="text-sm font-semibold text-foreground">Список преимуществ</h4>
            <Button type="button" variant="outline" className="h-8 px-2 text-xs" onClick={addAdvantageItem}>
              <Plus className="h-4 w-4" />
            </Button>
          </div>

          <div className="space-y-3">
            {(specialScreen.advantages?.items ?? []).map((item, index) => (
              <div key={index} className="space-y-3 rounded-lg border border-border/60 bg-muted/10 p-3">
                <div className="flex items-center justify-between">
                  <div className="text-xs font-semibold uppercase text-muted-foreground">Элемент {index + 1}</div>
                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      className="rounded-md border border-border/70 p-1 text-muted-foreground transition hover:bg-muted"
                      onClick={() => moveAdvantageItem(index, -1)}
                      disabled={index === 0}
                      title="Переместить выше"
                    >
                      <ArrowUp className="h-4 w-4" />
                    </button>
                    <button
                      type="button"
                      className="rounded-md border border-border/70 p-1 text-muted-foreground transition hover:bg-muted"
                      onClick={() => moveAdvantageItem(index, 1)}
                      disabled={index === (specialScreen.advantages?.items?.length ?? 0) - 1}
                      title="Переместить ниже"
                    >
                      <ArrowDown className="h-4 w-4" />
                    </button>
                    <Button
                      type="button"
                      variant="ghost"
                      className="h-8 px-3 text-xs text-destructive"
                      onClick={() => removeAdvantageItem(index)}
                      aria-label="Удалить элемент"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>

                <div className="grid grid-cols-1 gap-2">
                  <TextInput
                    label="Иконка (emoji/текст)"
                    value={item.icon?.text ?? ""}
                    onChange={(e) => updateAdvantageItem(index, "icon", e.target.value)}
                  />
                  <TextAreaInput
                    label="Текст"
                    rows={2}
                    className="resize-y"
                    value={item.text?.text ?? ""}
                    onChange={(e) => updateAdvantageItem(index, "text", e.target.value)}
                  />
                </div>
              </div>
            ))}
          </div>

          {(specialScreen.advantages?.items ?? []).length === 0 && (
            <div className="rounded-lg border border-dashed border-border/60 p-4 text-sm text-muted-foreground">
              Пока нет элементов. Добавьте первый, нажав &quot;+&quot;.
            </div>
          )}
        </div>
      </CollapsibleSection>

      <div className="rounded-lg border border-border/60 bg-muted/10 p-3 text-xs text-muted-foreground">
        <p>
          Тексты и преимущества отображаются в шаблоне `SpecialOfferTemplate`. Основная нижняя кнопка
          настраивается выше в секции &quot;Нижняя кнопка&quot;.
        </p>
      </div>
    </div>
  );
}


