"use client";

import Image from "next/image";

import type { PayChannel } from "@/data/dto/payment";

import styles from "./subscription-payment-method.module.css";

const PAYMENT_METHODS: Array<{
  channel: PayChannel;
  title: string;
  logoSrc?: string;
}> = [
  {
    channel: "stripe",
    title: "Stripe",
  },
  {
    channel: "ezpay",
    title: "GCash",
    logoSrc: "/images/subscription/gcash-logo.svg",
  },
];

export interface SubscriptionPaymentMethodProps {
  value: PayChannel;
  defaultChannel?: PayChannel;
  disabled?: boolean;
  caption?: string;
  onChange: (channel: PayChannel) => void;
}

export function SubscriptionPaymentMethod({
  value,
  defaultChannel = "stripe",
  disabled = false,
  caption = "Stripe by default",
  onChange,
}: SubscriptionPaymentMethodProps) {
  const paymentMethods =
    defaultChannel === "ezpay"
      ? [...PAYMENT_METHODS].sort((a, b) =>
          a.channel === "ezpay" ? -1 : b.channel === "ezpay" ? 1 : 0,
        )
      : PAYMENT_METHODS;

  return (
    <section className={styles.root} aria-labelledby="payment-method-title">
      <div className={styles.header}>
        <h2 id="payment-method-title" className={styles.title}>
          Payment Method
        </h2>
        <span className={styles.caption}>{caption}</span>
      </div>
      <div className={styles.options}>
        {paymentMethods.map((method) => {
          const selected = method.channel === value;
          const classes = [
            styles.option,
            selected ? styles.selected : "",
          ]
            .filter(Boolean)
            .join(" ");

          return (
            <button
              key={method.channel}
              type="button"
              className={classes}
              disabled={disabled}
              aria-pressed={selected}
              aria-label={method.title}
              onClick={() => onChange(method.channel)}
            >
              {method.logoSrc ? (
                <Image
                  src={method.logoSrc}
                  alt=""
                  aria-hidden="true"
                  width={122}
                  height={29}
                  className={styles.optionLogo}
                />
              ) : (
                <span className={styles.optionTitle}>{method.title}</span>
              )}
            </button>
          );
        })}
      </div>
    </section>
  );
}
