import Link from "next/link";
import { redirect } from "next/navigation";
import { ArrowLeftIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { getSeededOperator } from "@/lib/operator";
import { WhenFormClient } from "./when-form-client";
import { specFromRrule } from "@/lib/recurrence";
import { defaultFirstFireIso } from "@/lib/date-picker";
import { decodeMessages, legacyMessageToParts } from "@/lib/reminder-messages";

interface StepWhenParams {
  step?: string;
  accountId?: string;
  groupIds?: string;
  /** User-supplied reminder name (passes through unchanged). */
  name?: string;
  /** New shape — encoded MessagePart[]. */
  messages?: string;
  /** Legacy single-message fields, accepted for back-compat. */
  text?: string;
  mediaId?: string;
  caption?: string;
  scheduledAt?: string;
  rrule?: string;
  editReminderId?: string;
}

interface StepWhenProps {
  params: StepWhenParams;
}

export async function StepWhen({ params }: StepWhenProps) {
  const { accountId, groupIds, scheduledAt, rrule, editReminderId } = params;

  // Resolve the messages param once: prefer the new shape, fall back to
  // the legacy fields. Either way the wizard needs at least one part to
  // continue past Compose.
  const messagesParam =
    params.messages && decodeMessages(params.messages)
      ? params.messages
      : (() => {
          const legacy = legacyMessageToParts(params.text, params.mediaId, params.caption);
          if (!legacy) return undefined;
          // Re-encode the legacy fallback so subsequent steps see one
          // canonical wire-format and don't have to know about both.
          return new URLSearchParams({
            messages: encodeURIComponent(JSON.stringify(legacy)),
          }).get("messages") ?? undefined;
        })();

  if (!accountId || !messagesParam) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    redirect("/reminders/new" as any);
  }

  const op = await getSeededOperator();
  const timezone = op.defaultTimezone ?? "UTC";

  const backParams = new URLSearchParams({ step: "2", accountId });
  if (groupIds) backParams.set("groupIds", groupIds);
  if (params.name) backParams.set("name", params.name);
  if (messagesParam) backParams.set("messages", messagesParam);
  if (rrule) backParams.set("rrule", rrule);
  if (editReminderId) backParams.set("editReminderId", editReminderId);
  const backHref = `/reminders/new?${backParams.toString()}`;

  return (
    <div className="space-y-4">
      <div>
        <Button asChild variant="ghost" size="sm" className="-ml-2">
          {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
          <Link href={backHref as any}>
            <ArrowLeftIcon />
            Back
          </Link>
        </Button>
      </div>

      <p className="text-sm text-muted-foreground">
        Choose when to send this reminder. Times are in{" "}
        <span className="font-medium text-foreground">{timezone}</span>.
      </p>

      <WhenFormClient
        accountId={accountId}
        groupIds={groupIds ?? ""}
        timezone={timezone}
        initialDefaultIso={scheduledAt ?? defaultFirstFireIso(timezone)}
        initialSpec={specFromRrule(rrule)}
        passThroughParams={{ name: params.name, messages: messagesParam, editReminderId }}
      />
    </div>
  );
}
