/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useState } from "react";
import ReactDOM from "react-dom";
import styles from "./giving-modal.module.scss";
import { useForm, router } from "@inertiajs/react";
import { FiInfo } from "react-icons/fi";

interface ModalProps {
  closeModal: () => void;
  type: "add" | "update";
  giving?: any;
}

const formatNumber = (value: string) => {
  if (!value) return "";
  const num = value.replace(/,/g, "");
  return Number(num).toLocaleString();
};

const parseNumber = (value: string) => {
  return value.replace(/,/g, "");
};

const GivingModal: React.FC<ModalProps> = ({
  closeModal,
  type,
  giving,
}) => {
  /* ================= LOCAL DISPLAY STATE ================= */
  const [displayAmount, setDisplayAmount] = useState(
    type === "update"
      ? Number(giving?.amount || 0).toLocaleString()
      : ""
  );

  const { data, setData, post, processing, errors, reset } = useForm({
    amount: type === "update" ? giving?.amount || "" : "",
    description: type === "update" ? giving?.description || "" : "",
    date: type === "update" ? giving?.date || "" : "",
  });

  /* ================= HANDLE AMOUNT ================= */
  const handleAmountChange = (value: string) => {
    // Remove invalid characters
    const clean = value.replace(/[^\d]/g, "");

    // Format with commas
    const formatted = formatNumber(clean);

    setDisplayAmount(formatted);

    // Save raw number (no commas)
    setData("amount", parseNumber(formatted));
  };

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

    if (type === "add") {
      post("/member/givings", {
        onSuccess: () => {
          reset();
          setDisplayAmount("");
          closeModal();
          router.reload({ only: ["givings", "totalGivings", "flash"] });
        },
      });
    }

    if (type === "update" && giving?.id) {
      post(`/member/givings/${giving.id}/update`, {
        onSuccess: () => {
          reset();
          setDisplayAmount("");
          closeModal();
          router.reload({ only: ["givings", "totalGivings", "flash"] });
        },
      });
    }
  };

  return ReactDOM.createPortal(
    <div className={styles.modalBackdrop} onClick={closeModal}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
      >
        {/* ================= HEADER ================= */}
        <div className={styles.modalHeader}>
          <h2>
            {type === "add"
              ? "Record Giving"
              : "Update Giving Record"}
          </h2>
          <p>
            {type === "add"
              ? "Enter your giving details below"
              : "Modify your giving information"}
          </p>

          <button className={styles.closeBtn} onClick={closeModal}>
            ×
          </button>
        </div>

        {/* ================= FORM ================= */}
        <form onSubmit={handleSubmit} className={styles.modalForm}>
          {/* AMOUNT */}
          <div className={styles.formGroup}>
            <label>Amount (₦) *</label>

            <div className={styles.inputWrapper}>
              {/* <span className={styles.currency}>₦</span> */}

              <input
                type="text"
                value={displayAmount}
                onChange={(e) =>
                  handleAmountChange(e.target.value)
                }
                placeholder="Enter amount"
              />
            </div>

            {errors.amount && (
              <small className={styles.error}>{errors.amount}</small>
            )}
          </div>

          {/* DATE */}
          <div className={styles.formGroup}>
            <label>Date *</label>
            <input
              type="date"
              value={data.date}
              onChange={(e) => setData("date", e.target.value)}
            />
            {errors.date && (
              <small className={styles.error}>{errors.date}</small>
            )}
          </div>

          {/* DESCRIPTION */}
          <div className={styles.formGroup}>
            <label>Description</label>
            <textarea
              rows={3}
              value={data.description}
              onChange={(e) =>
                setData("description", e.target.value)
              }
              placeholder="e.g Tithe, Offering, Seed..."
            />
            {errors.description && (
              <small className={styles.error}>
                {errors.description}
              </small>
            )}
          </div>

          {/* ================= INFO BOX ================= */}
          <div className={styles.infoBox}>
            <div className={styles.infoIcon}>
              <FiInfo />
            </div>

            <div className={styles.infoContent}>
              <strong>Be Accountable</strong>
              <p>
                Give as you are led and monitor your givings over time
              </p>
            </div>
          </div>

          {/* ================= BUTTON ================= */}
          <button
            type="submit"
            disabled={processing}
            className={styles.submitBtn}
          >
            {processing
              ? "Saving..."
              : type === "add"
              ? "Record Giving"
              : "Update Giving"}
          </button>
        </form>
      </div>
    </div>,
    document.body
  );
};

export default GivingModal;