"use client";

import { useState, type FormEvent } from "react";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import {
  buildSupportReport,
  submitSupportReport,
  type SubmitSupportResult,
} from "@enode/core/support/report";
import { useTranslation } from "@enode/core/translations/hooks";
import { BottomSheetCard } from "../bottom-sheet-card";
import { Button } from "../button";
import { toast } from "../feedback/toast-store";
import { isValidEmail } from "./change-email-machine";

const INPUT_CLASS =
  "body-normal w-full rounded-xl border border-surface-stroke bg-background px-4 py-3 text-foreground-default outline-none placeholder:text-foreground-muted focus:border-foreground-default disabled:opacity-60";

/**
 * The message support receives for an owner's sign-in email change: a fixed
 * first line (the report has no subject field) and the addresses. English on
 * purpose — it is read by enode support, never shown in the app.
 */
export function ownerEmailChangeMessage(
  newEmail: string,
  currentEmail?: string | null,
): string {
  const lines = [
    "Owner sign-in email change",
    `New sign-in email: ${newEmail.trim()}`,
  ];
  const current = currentEmail?.trim();
  if (current) lines.push(`Current sign-in email: ${current}`);
  return lines.join("\n");
}

/**
 * Sends the change request through the same support-report transport (and
 * offline queue) as "Report a problem". Replies go to the current address.
 * Never throws; see `submitSupportReport`.
 */
export function sendOwnerEmailChange(
  newEmail: string,
  currentEmail?: string | null,
): Promise<SubmitSupportResult> {
  return submitSupportReport(
    buildSupportReport("user", {
      userMessage: ownerEmailChangeMessage(newEmail, currentEmail),
      userEmail: currentEmail?.trim() || undefined,
    }),
  );
}

/** Props of {@link OwnerEmailChangeForm}. */
export type OwnerEmailChangeFormProps = {
  /** The owner's current sign-in email; goes into the request and is the reply address. */
  currentEmail?: string | null;
  /** Called after the request was sent or queued. */
  onDone: () => void;
  onCancel: () => void;
  /** Delivery; defaults to {@link sendOwnerEmailChange}. Stories / tests pass their own. */
  send?: (newEmail: string, currentEmail?: string | null) => Promise<SubmitSupportResult>;
};

/**
 * "Change your sign-in email" for an owner: one address field with the same
 * inline check as the member change (flagged on Send, cleared on edit), then
 * "Send to support". Sent / queued end with a toast; a failure keeps the form.
 */
export function OwnerEmailChangeForm({
  currentEmail,
  onDone,
  onCancel,
  send = sendOwnerEmailChange,
}: OwnerEmailChangeFormProps) {
  const { t } = useTranslation();
  const [email, setEmail] = useState("");
  const [invalid, setInvalid] = useState(false);
  const [sending, setSending] = useState(false);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    const next = email.trim();
    if (!isValidEmail(next)) {
      setInvalid(true);
      return;
    }
    setSending(true);
    const result = await send(next, currentEmail);
    setSending(false);
    if (result.kind === "failed") {
      toast.error(t("Couldn't send right now — please try again later."));
      return;
    }
    toast.success(
      result.kind === "sent"
        ? t("Sent to enode support")
        : t("Saved — we'll send it when you're back online"),
    );
    setEmail("");
    onDone();
  }

  return (
    <form onSubmit={handleSubmit} noValidate className="px-6 pb-2 pt-6">
      <h2 className="heading-large">{t("Change your sign-in email")}</h2>
      <p className="body-normal mt-1 text-foreground-muted">
        {t("enode support changes the owner's sign-in email for you.")}
      </p>
      <label className="mt-4 block">
        <span className="body-prominent mb-1.5 block text-foreground-default">
          {t("New sign-in email")}
        </span>
        <input
          type="email"
          autoComplete="email"
          value={email}
          onChange={(e) => {
            setEmail(e.target.value);
            setInvalid(false);
          }}
          disabled={sending}
          placeholder={t("you@email.com")}
          aria-invalid={invalid || undefined}
          className={INPUT_CLASS}
        />
        {invalid && (
          <span className="body-small mt-1.5 block text-feedback-error" aria-live="polite">
            {t("Enter a valid email address.")}
          </span>
        )}
      </label>
      <div className="mt-5 flex flex-col gap-3">
        <Button type="submit" variant="primary" size="large" busy={sending}>
          {sending ? t("Sending…") : t("Send to support")}
        </Button>
        <Button variant="neutral" size="large" onClick={onCancel} disabled={sending}>
          {t("Cancel")}
        </Button>
      </div>
    </form>
  );
}

/**
 * The focused sheet behind the owner's "Contact support" link. Owners can
 * never change their sign-in email in the app; this files the request with
 * support (no new backend).
 */
export function OwnerEmailChangeSheet({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  const { t } = useTranslation();
  const user = useCurrentUser();
  return (
    <BottomSheetCard
      open={open}
      onClose={onClose}
      ariaLabel={t("Change your sign-in email")}
      zIndex={260}
      innerClassName="max-w-md"
    >
      <OwnerEmailChangeForm
        currentEmail={user?.email ?? null}
        onDone={onClose}
        onCancel={onClose}
      />
    </BottomSheetCard>
  );
}
