"use client";

import { useState, type FormEvent } from "react";
import { Field } from "@/components/shared/field";
import { Panel } from "@/components/shared/page";
import { Button } from "@/components/ui/button";
import type { CurrentUserProfile } from "@/features/profile/api-contract";
import {
  processSubscriptionPayment,
  subscriptionPaymentUrl,
  type SubscriptionPaymentBody,
} from "./subscription-api";

type PaymentDraft = Omit<SubscriptionPaymentBody, "contract_id" | "invoice_id">;

const uuidPattern =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

function initialPaymentDraft(profile: CurrentUserProfile | null): PaymentDraft {
  return {
    cvn: "",
    card_number: "",
    expiry_year: "",
    expiry_month: "",
    cardholder_first_name: profile?.firstName ?? "",
    cardholder_last_name: profile?.lastName ?? "",
    cardholder_email: profile?.email ?? "",
    cardholder_phone_number: profile?.phone ?? "",
  };
}

function errorMessage(error: unknown) {
  return error instanceof Error
    ? error.message
    : "Could not process the subscription payment.";
}

export function SubscriptionPaymentForm({
  editable,
  profile,
  contractId,
  invoiceId,
  onPaymentProcessed,
}: {
  editable: boolean;
  profile: CurrentUserProfile | null;
  contractId: string;
  invoiceId: string;
  onPaymentProcessed: () => void;
}) {
  const [draft, setDraft] = useState(() => initialPaymentDraft(profile));
  const [busy, setBusy] = useState(false);
  const [requestSubmitted, setRequestSubmitted] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [paymentUrl, setPaymentUrl] = useState("");
  const fieldsDisabled = !editable || busy || requestSubmitted;

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError("");
    setNotice("");
    setPaymentUrl("");
    if (!editable) return;
    if (!uuidPattern.test(contractId) || !uuidPattern.test(invoiceId)) {
      setError("Enter valid contract and invoice IDs for the pending payment.");
      return;
    }

    setBusy(true);
    try {
      const result = await processSubscriptionPayment({
        ...draft,
        contract_id: contractId,
        invoice_id: invoiceId,
        card_number: draft.card_number.replaceAll(" ", ""),
      });
      const url = subscriptionPaymentUrl(result);
      setPaymentUrl(url ?? "");
      setRequestSubmitted(true);
      onPaymentProcessed();
      setNotice(
        url
          ? "Payment request created. Continue through the secure payment page; this does not confirm payment yet."
          : "Payment request accepted. Confirm the payment status with Monet before treating it as paid.",
      );
      setDraft(initialPaymentDraft(profile));
    } catch (paymentError: unknown) {
      setError(errorMessage(paymentError));
    } finally {
      setBusy(false);
    }
  }

  return (
    <Panel
      title="Process subscription payment"
      description="Pay the issued setup invoice. The contract and invoice IDs are linked automatically."
    >
      <form className="space-y-5 p-5" onSubmit={submit}>
        <div className="grid gap-4 sm:grid-cols-2">
          <Field
            label="Card number"
            value={draft.card_number}
            onChange={(event) =>
              setDraft((current) => ({
                ...current,
                card_number: event.target.value.replace(/[^\d ]/g, "").slice(0, 23),
              }))
            }
            autoComplete="cc-number"
            inputMode="numeric"
            required
            maxLength={23}
            disabled={fieldsDisabled}
          />
          <div className="grid grid-cols-2 gap-3">
            <Field
              label="Expiry month"
              value={draft.expiry_month}
              onChange={(event) =>
                setDraft((current) => ({
                  ...current,
                  expiry_month: event.target.value.replace(/\D/g, "").slice(0, 2),
                }))
              }
              autoComplete="cc-exp-month"
              inputMode="numeric"
              placeholder="MM"
              required
              maxLength={2}
              disabled={fieldsDisabled}
            />
            <Field
              label="Expiry year"
              value={draft.expiry_year}
              onChange={(event) =>
                setDraft((current) => ({
                  ...current,
                  expiry_year: event.target.value.replace(/\D/g, "").slice(0, 4),
                }))
              }
              autoComplete="cc-exp-year"
              inputMode="numeric"
              placeholder="YYYY"
              required
              maxLength={4}
              disabled={fieldsDisabled}
            />
          </div>
          <Field
            label="CVN"
            type="password"
            value={draft.cvn}
            onChange={(event) =>
              setDraft((current) => ({
                ...current,
                cvn: event.target.value.replace(/\D/g, "").slice(0, 4),
              }))
            }
            autoComplete="cc-csc"
            inputMode="numeric"
            required
            maxLength={4}
            disabled={fieldsDisabled}
          />
          <Field
            label="Cardholder first name"
            value={draft.cardholder_first_name}
            onChange={(event) =>
              setDraft((current) => ({
                ...current,
                cardholder_first_name: event.target.value,
              }))
            }
            autoComplete="cc-given-name"
            required
            maxLength={100}
            disabled={fieldsDisabled}
          />
          <Field
            label="Cardholder last name"
            value={draft.cardholder_last_name}
            onChange={(event) =>
              setDraft((current) => ({
                ...current,
                cardholder_last_name: event.target.value,
              }))
            }
            autoComplete="cc-family-name"
            maxLength={100}
            disabled={fieldsDisabled}
          />
          <Field
            label="Cardholder email"
            type="email"
            value={draft.cardholder_email}
            onChange={(event) =>
              setDraft((current) => ({
                ...current,
                cardholder_email: event.target.value,
              }))
            }
            autoComplete="email"
            required
            maxLength={320}
            disabled={fieldsDisabled}
          />
          <Field
            label="Cardholder phone"
            type="tel"
            value={draft.cardholder_phone_number}
            onChange={(event) =>
              setDraft((current) => ({
                ...current,
                cardholder_phone_number: event.target.value,
              }))
            }
            autoComplete="tel"
            required
            maxLength={80}
            disabled={fieldsDisabled}
          />
        </div>
        <p className="text-xs text-muted-foreground">
          Card details are sent to the configured Monet service for this request
          and are not saved in the browser.
        </p>
        {error && (
          <p role="alert" className="text-sm text-destructive">
            {error}
          </p>
        )}
        {notice && (
          <div className="space-y-3" role="status">
            <p className="text-sm text-success">{notice}</p>
            {paymentUrl && (
              <Button asChild>
                <a href={paymentUrl} target="_blank" rel="noreferrer">
                  Continue to secure payment
                </a>
              </Button>
            )}
          </div>
        )}
        <Button
          type="submit"
          disabled={!editable || busy || requestSubmitted}
        >
          {busy
            ? "Submitting payment…"
            : requestSubmitted
              ? "Payment request submitted"
              : "Process payment"}
        </Button>
      </form>
    </Panel>
  );
}
