"use client";

import { useState } from "react";

type ServiceOption = readonly [string, number];

const services: ServiceOption[] = [
  ["Trust Application Support", 149],
  ["IRA/401(k) Transfer Coordination", 199],
  ["Vault Transfer Coordination", 99],
  ["Annual Platform Service Fee", 129],
  ["Sell-Back Processing Fee", 29],
  ["Trust Account Linking", 79],
  ["Premium Concierge Service", 299]
];

export function ServiceFeesClient({ squareAvailable }: { squareAvailable: boolean }) {
  const [selected, setSelected] = useState<ServiceOption>(services[0]);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [submitting, setSubmitting] = useState(false);

  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (submitting) return;
    const form = new FormData(event.currentTarget);
    setSubmitting(true);
    setMessage(null);
    try {
      const res = await fetch("/api/service-payments", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          customerName: form.get("customerName"),
          customerEmail: form.get("customerEmail"),
          customerPhone: form.get("customerPhone"),
          serviceType: selected[0],
          amount: selected[1],
          paymentMethod: form.get("paymentMethod"),
          companyUrl: form.get("companyUrl"),
          simulateFailure: false,
          agreementAccepted: form.get("agreementAccepted") === "on"
        })
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setMessage({ type: "error", text: "Service fee request could not be submitted. Please review the form and try again." });
        return;
      }
      setMessage({ type: "success", text: "Service fee request submitted. Redirecting to confirmation..." });
      window.location.href = data.redirect;
    } catch {
      setMessage({ type: "error", text: "Service fee request could not be submitted. Please try again." });
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <section className="container-grid py-12">
      <p className="text-sm font-bold uppercase text-gold">Fixed service fees</p>
      <h1 className="mt-2 font-heading text-4xl font-black">Service Fee Payment</h1>
      <div className="mt-6 grid gap-6 lg:grid-cols-[1fr_420px]">
        <div className="grid gap-3">
          {services.map((service) => (
            <button key={service[0]} type="button" onClick={() => setSelected(service)} className={`panel flex justify-between p-4 text-left ${selected[0] === service[0] ? "border-gold/60" : ""}`}>
              <span className="font-bold">{service[0]}</span><span className="text-gold">${service[1]}</span>
            </button>
          ))}
        </div>
        <form onSubmit={submit} className="panel grid h-fit gap-4 p-5">
          <input type="text" name="companyUrl" tabIndex={-1} autoComplete="off" aria-hidden="true" className="hidden" />
          <h2 className="font-heading text-xl font-black">{selected[0]} - ${selected[1]}</h2>
          <label>Customer name<input name="customerName" required /></label>
          <label>Email<input name="customerEmail" type="email" required /></label>
          <label>Phone<input name="customerPhone" required /></label>
          <label>
            Payment / request method
            <select name="paymentMethod" defaultValue="STRIPE">
              <option value="STRIPE">Card payment request</option>
              <option value="PAYPAL" disabled>PayPal - coming soon</option>
              <option value="SQUARE" disabled>Square - coming soon</option>
            </select>
          </label>
          <p className="text-sm leading-6 text-[#666]">
            Service fee requests are recorded for team review. PayPal and Square service-fee processing will be enabled after provider setup is confirmed.
          </p>
          {squareAvailable ? <p className="text-xs text-[#666]">Square card checkout is available for product orders. This service fee form will use a separate service-payment flow when enabled.</p> : null}
          <label className="flex-row items-center gap-2"><input className="h-4 min-h-0 w-4" type="checkbox" name="agreementAccepted" required /> I accept the Service Agreement, Refund Policy, and request review terms.</label>
          {message ? (
            <p
              aria-live="polite"
              className={message.type === "success" ? "rounded border border-[#0F766E]/25 bg-emerald-50 p-3 text-sm font-bold text-[#0F766E]" : "rounded border border-[#B91C1C]/25 bg-red-50 p-3 text-sm font-bold text-[#B91C1C]"}
            >
              {message.text}
            </p>
          ) : null}
          <button className="btn btn-primary w-full disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto" disabled={submitting}>
            {submitting ? "Submitting..." : "Submit Service Fee Request"}
          </button>
        </form>
      </div>
    </section>
  );
}
