"use client";

import Link from "next/link";
import type { PublicForm } from "@/lib/types";
import { formDataToObject, useFormSubmit } from "@/lib/forms";
import { SchemaField, type FieldExtras } from "./SchemaFields";

/**
 * Login-style card used by the Customer and Operations portal pages.
 * With a form (customer portal) it sends a request-status lookup to Aggie;
 * without one (operations) it links staff to the Aggie workspace where
 * submissions, leads and notices are actually managed.
 */
export default function PortalCard({
  brand,
  subtitle,
  form,
  extras,
  buttonLabel,
  buttonHref,
  noteHtml,
  successHtml,
  backLabel,
  backHref,
  source
}: {
  brand: string;
  subtitle: string;
  form: PublicForm | null;
  extras: FieldExtras;
  buttonLabel: string;
  buttonHref: string;
  noteHtml: string;
  successHtml: string;
  backLabel: string;
  backHref: string;
  source: string;
}) {
  const { state, error, send } = useFormSubmit(form?.formKey || "");

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    await send({ ...formDataToObject(e.currentTarget), source });
  };

  return (
    <div className="login-wrap">
      <div className="login-card">
        <div className="login-brand">
          <div className="icon" />
          <h1>{brand}</h1>
          <p>{subtitle}</p>
        </div>
        {form ? (
          state === "done" ? (
            <div className="proto-note" style={{ textAlign: "left" }} dangerouslySetInnerHTML={{ __html: successHtml || form.successMessage || "" }} />
          ) : (
            <form onSubmit={onSubmit}>
              {form.fields.map((f) => (
                <SchemaField key={f.fieldKey} field={f} extras={extras} />
              ))}
              <button type="submit" className="login-btn" disabled={state === "sending"}>
                {state === "sending" ? "Sending…" : buttonLabel}
              </button>
              {state === "error" && <p className="msc-form-error">{error}</p>}
            </form>
          )
        ) : (
          <a className="login-btn" href={buttonHref} style={{ display: "block", textAlign: "center", textDecoration: "none" }}>
            {buttonLabel}
          </a>
        )}
        {noteHtml && <div className="proto-note" dangerouslySetInnerHTML={{ __html: noteHtml }} />}
        <div className="back-link">
          <Link href={backHref}>{backLabel}</Link>
        </div>
      </div>
    </div>
  );
}
