"use client";

import { useId, useState } from "react";
import { Info } from "lucide-react";
import { useT } from "@/shared/i18n/client";
import { FORMAT_FIELDS, WIDGET_CORNERS } from "@/shared/constants/announcements";
import { SearchableSelect } from "@/presentation/components/ui/searchable-select";
import { ToggleGroup, ToggleGroupItem } from "@/presentation/components/ui/toggle-group";
import { ElementSelect } from "@/presentation/components/announcements/element-select";
import { FieldErrors, FieldLabel, Help } from "@/presentation/components/announcements/form-controls";
import { EditorSection, type SectionProps } from "@/presentation/components/announcements/editor-sections/section";
import type { AnnouncementExampleVehicle, AnnouncementPlacement, AnnouncementWidgetCorner } from "@/domain/entities/announcement";

const ALL_PAGES = "__all";

/** Page → element → position, in that order; only what the format uses (spec §4). */
export function PlacementSection({
  input,
  update,
  errors,
  catalogs,
  disabled,
  exampleVehicles,
  exampleVehicleId,
  onExampleVehicle,
}: SectionProps & {
  exampleVehicles: AnnouncementExampleVehicle[];
  exampleVehicleId: number | null;
  onExampleVehicle: (id: number | null) => void;
}) {
  const t = useT();
  const e = t.announcements.editor;
  const spec = FORMAT_FIELDS[input.format];
  const pageId = useId();
  const elementId = useId();
  const [cleared, setCleared] = useState(false);
  const page = catalogs.pages.find((p) => p.key === input.page_key);

  const setPage = (value: string) => {
    const pageKey = value === ALL_PAGES || value === "" ? null : value;
    const anchor = catalogs.anchors.find((a) => a.key === input.anchor_key);
    // An element of another page cannot stay; menu entries are on every page.
    const keep = !anchor || anchor.page_key === null || anchor.page_key === pageKey;
    setCleared(!keep);
    update({ page_key: pageKey, ...(keep ? {} : { anchor_key: null, target_sidebar_path: null }) });
  };

  const setAnchor = (anchorKey: string | null) => {
    const sidebar = catalogs.sidebar_paths.find((s) => s.anchor_key === anchorKey);
    setCleared(false);
    update({ anchor_key: anchorKey, target_sidebar_path: sidebar?.path ?? null });
  };

  const pageOptions = [
    ...(spec.allPages ? [{ value: ALL_PAGES, label: e.allPages }] : []),
    ...(spec.page === "optional" && !spec.allPages ? [{ value: ALL_PAGES, label: "—" }] : []),
    // Fleet's French menu label, the English one as a hint.
    ...catalogs.pages.map((p) => ({ value: p.key, label: p.label, hint: p.hint })),
  ];

  const fixedNote = input.format === "banner" || input.format === "modal" ? e.positionFixed[input.format] : null;

  return (
    <EditorSection id="section-placement" index={3} title={e.sections.placement.title} help={e.sections.placement.help}>
      <div className="grid gap-4 md:grid-cols-2">
        {spec.page !== "none" && (
          <div className="space-y-1.5">
            <FieldLabel htmlFor={pageId} required={spec.page === "required"}>{e.page}</FieldLabel>
            <SearchableSelect
              triggerClassName="w-full"
              value={input.page_key ?? (spec.page === "required" ? "" : ALL_PAGES)}
              onValueChange={setPage}
              placeholder={e.pagePlaceholder}
              options={pageOptions}
              disabled={disabled}
            />
            <FieldErrors errors={errors} path="page_key" />
          </div>
        )}

        {spec.element !== "none" && (
          <div className="space-y-1.5">
            <FieldLabel htmlFor={elementId} required>{spec.element === "menu" ? e.menuEntry : e.element}</FieldLabel>
            <ElementSelect
              id={elementId}
              catalogs={catalogs}
              pageKey={input.page_key}
              value={input.anchor_key}
              onChange={setAnchor}
              menuOnly={spec.element === "menu"}
              invalid={!!errors.anchor_key}
              disabled={disabled}
            />
            <FieldErrors errors={errors} path="anchor_key" />
            {cleared && <p className="text-xs text-amber-700">{e.elementCleared}</p>}
          </div>
        )}
      </div>

      {spec.element !== "none" && (
        <p className="flex items-start gap-1.5 text-xs text-muted-foreground">
          <Info className="mt-0.5 h-3.5 w-3.5 shrink-0" />
          {e.elementNote}
        </p>
      )}

      {spec.placements.length > 0 && (
        <div className="space-y-1.5">
          <FieldLabel>{e.position}</FieldLabel>
          <ToggleGroup
            type="single"
            variant="outline"
            value={input.placement}
            onValueChange={(v) => v && update({ placement: v as AnnouncementPlacement })}
            disabled={disabled}
          >
            {spec.placements.map((p) => (
              <ToggleGroupItem key={p} value={p} className="px-3 text-xs">{e.placements[p]}</ToggleGroupItem>
            ))}
          </ToggleGroup>
        </div>
      )}

      {spec.corner && (
        <div className="space-y-1.5">
          <FieldLabel>{e.corner}</FieldLabel>
          <ToggleGroup
            type="single"
            variant="outline"
            value={input.widget_corner}
            onValueChange={(v) => v && update({ widget_corner: v as AnnouncementWidgetCorner })}
            disabled={disabled}
          >
            {WIDGET_CORNERS.map((c) => (
              <ToggleGroupItem key={c} value={c} className="px-3 text-xs">{e.corners[c]}</ToggleGroupItem>
            ))}
          </ToggleGroup>
        </div>
      )}

      {fixedNote && <Help>{fixedNote}</Help>}

      {page?.needs_vehicle && (
        <div className="space-y-1.5 rounded-lg border border-blue-200 bg-blue-50/50 p-3">
          <FieldLabel>{e.exampleVehicle}</FieldLabel>
          <SearchableSelect
            triggerClassName="w-full bg-background"
            value={exampleVehicleId ? String(exampleVehicleId) : ""}
            onValueChange={(v) => onExampleVehicle(v ? Number(v) : null)}
            placeholder={e.exampleVehiclePlaceholder}
            options={exampleVehicles.map((v) => ({ value: String(v.id), label: `${v.numberplate} · ${v.make_model}` }))}
          />
          <Help>{e.exampleVehicleHelp}</Help>
        </div>
      )}

      {page?.example && !page.needs_vehicle && <Help>{e.exampleRecordHelp}</Help>}
    </EditorSection>
  );
}
