/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */

import styles from "./checkout.module.scss";
import { useState } from "react";
import { MdWallet } from "react-icons/md";
import { router } from "@inertiajs/react";
import { useForm, usePage } from "@inertiajs/react";
import currencyData from "../../../../data/countries-currencies.json";
import { formatMoneyComplete } from "@/lib/utils/format-money";

const PlanCheckout = ({ plan }: any) => {
  const {
    name,
    min_amount,
    max_amount,
    roi,
    platformFees,
    duration,
    leverage,
    base_currency,
  } = plan;

  const { appSettings } =
    usePage().props as unknown as any;

  const currency = currencyData.find(
    (item) =>
      item.currency_code ===
      appSettings?.base_currency
  );

  const [method, setMethod] =
    useState("wallet");

  const [displayAmount, setDisplayAmount] =
    useState("");

  const [amountError, setAmountError] =
    useState("");

  const handleAmountChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const raw = e.target.value.replace(
      /,/g,
      ""
    );

    if (!/^\d*$/.test(raw)) return;

    setAmountError("");

    setData("amount", raw);

    setDisplayAmount(
      raw
        ? Number(raw).toLocaleString("en-US")
        : ""
    );
  };

  const {
    data,
    setData,
    post,
    reset,
  } = useForm({
    plan_id: plan?.id,
    amount: "",
  });

  const toggleMethod = (
    selectedMethod: string
  ) => {
    setMethod(selectedMethod);
  };

  const numericAmount = Number(
    data.amount
  );

  const projectedReturn =
    (numericAmount * roi) / 100;

  const calculatedPlatformFees =
    (platformFees / 100) *
    numericAmount;

  const totalAmount =
    numericAmount +
    calculatedPlatformFees;

  const { auth }: any =
    usePage().props;

  const walletBalance =
    auth?.user?.balance ?? 0;

  const handleSubmit = (
    e: React.FormEvent
  ) => {
    e.preventDefault();

    if (!numericAmount) {
      setAmountError(
        "Please enter an investment amount."
      );
      return;
    }

    if (
      numericAmount < min_amount
    ) {
      setAmountError(
        `Minimum investment amount is ${currency?.currency_symbol}${formatMoneyComplete(
          min_amount
        )}`
      );
      return;
    }

    if (
      numericAmount > max_amount
    ) {
      setAmountError(
        `Maximum investment amount is ${currency?.currency_symbol}${formatMoneyComplete(
          max_amount
        )}`
      );
      return;
    }

    setAmountError("");

    post(
      route("investment.purchase"),
      {
        onSuccess: () => {
          reset();

          setDisplayAmount("");

          router.reload({
            only: ["flash"],
          });
        },
      }
    );
  };

  return (
    <div className={styles.checkout}>
      {/* Hero */}

      <div className={styles.checkoutHero}>
        <span
          className={styles.checkoutBadge}
        >
          Investment Checkout
        </span>

        <h3>{name}</h3>

        <p>
          Review your investment
          details and fund this
          portfolio directly from your
          wallet balance.
        </p>
      </div>

      <div
        className={styles["checkout--body"]}
      >
        {/* Amount */}

        <div
          className={
            styles[
              "checkout--body--amount"
            ]
          }
        >
          <label>
            Investment Amount
          </label>

          <input
            type="text"
            value={displayAmount}
            onChange={
              handleAmountChange
            }
            placeholder="Enter amount"
          />

          <div
            className={
              styles[
                "checkout--body--amount--helper"
              ]
            }
          >
            <p>
              Min:{" "}
              {
                currency?.currency_symbol
              }
              {formatMoneyComplete(
                min_amount
              )}
            </p>

            <p>
              Max:{" "}
              {
                currency?.currency_symbol
              }
              {formatMoneyComplete(
                max_amount
              )}
            </p>
          </div>

          {amountError && (
            <div
              className={
                styles[
                  "checkout--body--amount--error"
                ]
              }
            >
              {amountError}
            </div>
          )}
        </div>

        {/* Summary */}

        <div
          className={
            styles[
              "checkout--body--fees"
            ]
          }
        >
          <h5>
            Investment Summary
          </h5>

          <div
            className={
              styles[
                "checkout--body--fees--content"
              ]
            }
          >
            <div
              className={
                styles[
                  "checkout--body--fees--content--item"
                ]
              }
            >
              <p>ROI</p>
              <p>{roi}%</p>
            </div>

            <div
              className={
                styles[
                  "checkout--body--fees--content--item"
                ]
              }
            >
              <p>Duration</p>
              <p>{duration}</p>
            </div>

            <div
              className={
                styles[
                  "checkout--body--fees--content--item"
                ]
              }
            >
              <p>Leverage</p>
              <p>{leverage}</p>
            </div>

            <div
              className={
                styles[
                  "checkout--body--fees--content--item"
                ]
              }
            >
              <p>Base Currency</p>
              <p>
                {
                  currency?.currency_code
                }
              </p>
            </div>

            <div
              className={
                styles[
                  "checkout--body--fees--content--item"
                ]
              }
            >
              <p>
                Projected Return
              </p>

              <p>
                {
                  currency?.currency_symbol
                }
                {formatMoneyComplete(
                  projectedReturn
                )}
              </p>
            </div>
          </div>
        </div>

        {/* Wallet */}

        <div
          className={
            styles[
              "checkout--body--method"
            ]
          }
        >
          <h5>
            Payment Method
          </h5>

          <div
            onClick={() =>
              toggleMethod(
                "wallet"
              )
            }
            className={
              method === "wallet"
                ? styles[
                    "checkout--body--method--item--active"
                  ]
                : styles[
                    "checkout--body--method--item"
                  ]
            }
          >
            <MdWallet
              color="#F79318"
              size="1.4rem"
            />

            <p>
              Wallet Balance:
              {" "}
              {
                currency?.currency_symbol
              }
              {formatMoneyComplete(
                walletBalance
              )}
            </p>
          </div>
        </div>

        {/* Notice */}

        <div
          className={
            styles[
              "checkout--body--notice"
            ]
          }
        >
          <h5>
            Investment Activation
          </h5>

          <small>
            Your investment begins
            immediately after payment
            confirmation and becomes
            visible in your active
            portfolio.
          </small>
        </div>

        {/* CTA */}

        <button
          onClick={handleSubmit}
        >
          Buy Investment Package
        </button>
      </div>
    </div>
  );
};

export default PlanCheckout;