"use client";

import { useId, useState } from "react";
import { ArrowDown, ArrowUp, ChevronDown, ChevronsDownUp, ChevronsUpDown, CircleAlert, Link2, Lock, MousePointerClick, Plus, Trash2, TriangleAlert } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { useT } from "@/shared/i18n/client";
import { ANNOUNCEMENT_LIMITS, FORMAT_FIELDS, STEP_PLACEMENTS } from "@/shared/constants/announcements";
import { newStep } from "@/shared/lib/announcements";
import { Button } from "@/presentation/components/ui/button";
import { ToggleGroup, ToggleGroupItem } from "@/presentation/components/ui/toggle-group";
import { ElementSelect } from "@/presentation/components/announcements/element-select";
import { FieldErrors, FieldLabel, Help, LocalizedInput, LocalizedRichText } from "@/presentation/components/announcements/form-controls";
import { CtaFields, IconPicker, MediaField } from "@/presentation/components/announcements/editor-sections/content-section";
import { EditorSection, type SectionProps } from "@/presentation/components/announcements/editor-sections/section";
import type { AnnouncementPlacement, AnnouncementStep } from "@/domain/entities/announcement";

/**
 * Steps of a step card or a guided tour. Each step folds to a one-line summary (title, the
 * element it is attached to, its position); adding a step folds the others and opens it. The
 * active step is the one the preview shows, and clicking an element in the preview attaches it.
 */
export function StepsSection({
  input,
  update,
  errors,
  catalogs,
  locked,
  disabled,
  activeStep,
  onActiveStep,
}: SectionProps & { activeStep: number; onActiveStep: (index: number) => void }) {
  const t = useT();
  const s = t.announcements.steps;
  const spec = FORMAT_FIELDS[input.format].steps;
  const [anchorChanged, setAnchorChanged] = useState(false);
  // Open steps by id; the first one starts open.
  const [open, setOpen] = useState<Set<string>>(() => new Set(input.steps[0] ? [input.steps[0].id] : []));
  if (!spec) return null;

  const steps = input.steps;
  const setSteps = (next: AnnouncementStep[]) => update({ steps: next });
  const patch = (i: number, p: Partial<AnnouncementStep>) => setSteps(steps.map((step, j) => (j === i ? { ...step, ...p } : step)));
  const move = (i: number, dir: -1 | 1) => {
    const next = [...steps];
    [next[i], next[i + dir]] = [next[i + dir], next[i]];
    setSteps(next);
    if (activeStep === i) onActiveStep(i + dir);
  };
  const toggle = (id: string, index: number) => {
    setOpen((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
    onActiveStep(index);
  };
  const add = () => {
    const step = newStep();
    setSteps([...steps, step]);
    setOpen(new Set([step.id]));
    onActiveStep(steps.length);
  };
  const remove = (i: number) => {
    setSteps(steps.filter((_, j) => j !== i));
    if (activeStep >= i && activeStep > 0) onActiveStep(activeStep - 1);
  };
  const allOpen = steps.every((step) => open.has(step.id));
  const hasErrors = (i: number) => Object.keys(errors).some((field) => field.startsWith(`steps.${i}.`));

  return (
    <EditorSection
      id="section-steps"
      index={4}
      title={t.announcements.editor.sections.steps.title}
      help={s.count(spec.min, spec.max)}
      aside={
        <div className="flex items-center gap-2">
          {steps.length > 1 && (
            <Button type="button" size="sm" variant="ghost" onClick={() => setOpen(allOpen ? new Set() : new Set(steps.map((x) => x.id)))}>
              {allOpen ? <ChevronsDownUp className="mr-1 h-3.5 w-3.5" /> : <ChevronsUpDown className="mr-1 h-3.5 w-3.5" />}
              {allOpen ? s.collapseAll : s.expandAll}
            </Button>
          )}
          {!locked && (
            <Button type="button" size="sm" variant="outline" disabled={disabled || steps.length >= spec.max} onClick={add}>
              <Plus className="mr-1 h-3.5 w-3.5" />
              {s.add}
            </Button>
          )}
        </div>
      }
    >
      {locked && (
        <p className="flex items-center gap-1.5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
          <Lock className="h-3.5 w-3.5" />
          {s.countLocked}
        </p>
      )}
      {anchorChanged && (
        <p className="flex items-center gap-1.5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
          <TriangleAlert className="h-3.5 w-3.5" />
          {s.changeWarning}
        </p>
      )}
      {spec.anchor !== "none" && (
        <p className="flex items-start gap-1.5 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-xs text-blue-900">
          <MousePointerClick className="mt-0.5 h-3.5 w-3.5 shrink-0" />
          {s.attachHow}
        </p>
      )}
      <FieldErrors errors={errors} path="steps" />
      <ol className="space-y-3">
        {steps.map((step, i) => (
          <StepCard
            key={step.id}
            index={i}
            step={step}
            count={steps.length}
            open={open.has(step.id)}
            active={activeStep === i}
            invalid={hasErrors(i)}
            anchorRule={spec.anchor}
            pageKey={input.page_key}
            catalogs={catalogs}
            errors={errors}
            locked={locked}
            disabled={disabled}
            canRemove={steps.length > spec.min}
            onToggle={() => toggle(step.id, i)}
            onPatch={(p) => {
              if (locked && "anchor_key" in p) setAnchorChanged(true);
              patch(i, p);
            }}
            onMove={(dir) => move(i, dir)}
            onRemove={() => remove(i)}
          />
        ))}
      </ol>
    </EditorSection>
  );
}

function StepCard({
  index,
  step,
  count,
  open,
  active,
  invalid,
  anchorRule,
  pageKey,
  catalogs,
  errors,
  locked,
  disabled,
  canRemove,
  onToggle,
  onPatch,
  onMove,
  onRemove,
}: {
  index: number;
  step: AnnouncementStep;
  count: number;
  open: boolean;
  active: boolean;
  invalid: boolean;
  anchorRule: "none" | "optional" | "required";
  pageKey: string | null;
  catalogs: SectionProps["catalogs"];
  errors: SectionProps["errors"];
  locked: boolean;
  disabled: boolean;
  canRemove: boolean;
  onToggle: () => void;
  onPatch: (p: Partial<AnnouncementStep>) => void;
  onMove: (dir: -1 | 1) => void;
  onRemove: () => void;
}) {
  const t = useT();
  const s = t.announcements.steps;
  const e = t.announcements.editor;
  const f = `steps.${index}`;
  const elementId = useId();
  const bodyId = useId();
  const anchor = catalogs.anchors.find((a) => a.key === step.anchor_key);

  return (
    <li
      className={cn(
        "rounded-lg border bg-muted/20 transition-colors",
        active && "border-blue-400 ring-1 ring-blue-400",
        invalid && !open && "border-destructive",
      )}
    >
      <div className="flex items-center gap-2 px-3 py-2.5">
        <button
          type="button"
          onClick={onToggle}
          aria-expanded={open}
          aria-controls={bodyId}
          className="flex min-w-0 flex-1 items-center gap-2.5 text-left"
        >
          <ChevronDown className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform", !open && "-rotate-90")} />
          <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-blue-600 text-[11px] font-bold text-white">{index + 1}</span>
          <span className="min-w-0 flex-1">
            <span className={cn("block truncate text-sm font-semibold", !step.title.fr && "font-normal italic text-muted-foreground")}>
              {step.title.fr || s.noTitle}
            </span>
            {anchorRule !== "none" && (
              <span className="flex items-center gap-1 truncate text-xs text-muted-foreground">
                <Link2 className="h-3 w-3 shrink-0" />
                {anchor ? `${anchor.label} · ${e.placements[step.placement]}` : s.notAttached}
              </span>
            )}
          </span>
          {invalid && (
            <span className="flex shrink-0 items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-[11px] font-medium text-destructive">
              <CircleAlert className="h-3 w-3" />
              {s.toFix}
            </span>
          )}
        </button>
        {!locked && (
          <div className="flex shrink-0 items-center gap-0.5">
            <Button type="button" size="icon-sm" variant="ghost" disabled={disabled || index === 0} onClick={() => onMove(-1)} aria-label={s.moveUp} title={s.moveUp}>
              <ArrowUp className="h-4 w-4" />
            </Button>
            <Button type="button" size="icon-sm" variant="ghost" disabled={disabled || index === count - 1} onClick={() => onMove(1)} aria-label={s.moveDown} title={s.moveDown}>
              <ArrowDown className="h-4 w-4" />
            </Button>
            <Button type="button" size="icon-sm" variant="ghost" disabled={disabled || !canRemove} onClick={onRemove} aria-label={s.remove} title={s.remove} className="hover:text-destructive">
              <Trash2 className="h-4 w-4" />
            </Button>
          </div>
        )}
      </div>

      {open && (
        <div id={bodyId} className="space-y-4 border-t px-4 pb-4 pt-4">
          {anchorRule !== "none" && (
            <div className="space-y-4 rounded-lg border border-blue-200 bg-white p-3">
              <div className="space-y-1.5">
                <FieldLabel htmlFor={elementId} required={anchorRule === "required"} hint={anchorRule === "optional" ? s.elementOptional : undefined}>
                  {s.attachedTo}
                </FieldLabel>
                <ElementSelect
                  id={elementId}
                  catalogs={catalogs}
                  pageKey={pageKey}
                  value={step.anchor_key}
                  onChange={(anchor_key) => onPatch({ anchor_key, placement: anchor_key ? step.placement : "auto" })}
                  allowNone={anchorRule === "optional"}
                  noneLabel={anchorRule === "optional" ? s.noElement : s.chooseElement}
                  invalid={!!errors[`${f}.anchor_key`]}
                  disabled={disabled}
                />
                <FieldErrors errors={errors} path={`${f}.anchor_key`} />
                <Help>{s.attachHelp}</Help>
              </div>
              {step.anchor_key && (
                <div className="space-y-1.5">
                  <FieldLabel>{s.bubblePosition}</FieldLabel>
                  <ToggleGroup
                    type="single"
                    variant="outline"
                    value={step.placement}
                    onValueChange={(v) => v && onPatch({ placement: v as AnnouncementPlacement })}
                    disabled={disabled}
                    className="flex-wrap"
                  >
                    {STEP_PLACEMENTS.map((p) => (
                      <ToggleGroupItem key={p} value={p} className="px-2.5 text-xs">{e.placements[p]}</ToggleGroupItem>
                    ))}
                  </ToggleGroup>
                </div>
              )}
            </div>
          )}

          <LocalizedInput label={s.title} path={`${f}.title`} value={step.title} onChange={(title) => onPatch({ title })} errors={errors} max={ANNOUNCEMENT_LIMITS.stepTitle} required disabled={disabled} />
          <LocalizedInput label={s.subtitle} path={`${f}.subtitle`} value={step.subtitle} onChange={(subtitle) => onPatch({ subtitle })} errors={errors} max={ANNOUNCEMENT_LIMITS.stepSubtitle} disabled={disabled} />
          <LocalizedRichText label={s.body} path={`${f}.body`} value={step.body} onChange={(body) => onPatch({ body })} errors={errors} max={ANNOUNCEMENT_LIMITS.stepBody} required disabled={disabled} />
          <IconPicker value={step.icon} onChange={(icon) => onPatch({ icon })} disabled={disabled} />
          <MediaField path={`${f}.media`} url={step.media_url} alt={step.media_alt} onChange={(media_url, media_alt) => onPatch({ media_url, media_alt })} errors={errors} disabled={disabled} />
          <CtaFields path={`${f}.cta`} label={step.cta_label} ctaPath={step.cta_path} onChange={(cta_label, cta_path) => onPatch({ cta_label, cta_path })} errors={errors} disabled={disabled} />
        </div>
      )}
    </li>
  );
}
