/* eslint-disable react-hooks/set-state-in-effect */
/* eslint-disable react-hooks/preserve-manual-memoization */
/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import styles from "./pastor-view.module.scss";
import AdminLayout from "@/layouts/admin-layout";

import {
  useState,
  useRef,
  useEffect,
  useMemo,
} from "react";

import ReactDOM from "react-dom";

import { router } from "@inertiajs/react";

import {
  FiUser,
  FiMail,
  FiPhone,
  FiMapPin,
  FiBook,
  FiMoreVertical,
  FiTrash2,
  FiEdit,
  FiCalendar,
  FiHome,
  FiSlash,
  FiSend,
} from "react-icons/fi";

/* =========================================================
| TABS
========================================================= */

const tabs = [
  {
    key: "bio",
    title: "Bio Data",
    desc: "Personal information",
  },

  {
    key: "academic",
    title: "Academic Data",
    desc: "Education background",
  },

  {
    key: "ministry",
    title: "Ministry Data",
    desc: "Church journey",
  },

  {
    key: "banking",
    title: "Banking Data",
    desc: "Financial details",
  },

  {
    key: "history",
    title: "Transfer History",
    desc: "Movement log",
  },
];

/* =========================================================
| FORMAT DATE
========================================================= */

const formatReadableDate = (
  dateString: string
) => {
  if (!dateString) return "—";

  const date = new Date(dateString);

  if (isNaN(date.getTime())) {
    return "—";
  }

  const day = date.getDate();

  const getSuffix = (d: number) => {
    if (d > 3 && d < 21) {
      return "th";
    }

    switch (d % 10) {
      case 1:
        return "st";

      case 2:
        return "nd";

      case 3:
        return "rd";

      default:
        return "th";
    }
  };

  const suffix = getSuffix(day);

  const weekday =
    date.toLocaleDateString(
      "en-US",
      {
        weekday: "long",
      }
    );

  const month =
    date.toLocaleDateString(
      "en-US",
      {
        month: "long",
      }
    );

  const year = date.getFullYear();

  return `${weekday}, ${month} ${day}${suffix}, ${year}`;
};

/* =========================================================
| TRANSFER MODAL
========================================================= */

const TransferModal = ({
  pastor,
  close,
  branches,
}: any) => {
  const [form, setForm] = useState({
    branch_id: "",
    start_date: "",
    capacity: "",
    remark: "",
  });

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

    router.post(
      "/admin/pastors/transfer",
      {
        pastor_id: pastor.id,
        ...form,
      },
      {
        preserveScroll: true,

        onSuccess: () => {
          close();
        },
      }
    );
  };

  return ReactDOM.createPortal(
    <div
      className={styles.modalBackdrop}
      onClick={close}
    >
      <div
        className={styles.modalContent}
        onClick={(e) =>
          e.stopPropagation()
        }
      >
        <div className={styles.modalHeader}>
          <h2>Transfer Pastor</h2>

          <p>
            Fill in transfer details.
            Pastor will automatically
            be moved to the selected
            branch.
          </p>

          <button onClick={close}>
            ×
          </button>
        </div>

        <form
          onSubmit={handleSubmit}
          className={styles.modalForm}
        >
          <div className={styles.formGroup}>
            <label>
              Select Branch *
            </label>

            <select
              required
              value={form.branch_id}
              onChange={(e) =>
                setForm({
                  ...form,
                  branch_id:
                    e.target.value,
                })
              }
            >
              <option value="">
                Select Branch
              </option>

              {branches?.map(
                (b: any) => (
                  <option
                    key={b.id}
                    value={b.id}
                  >
                    {b.name}
                  </option>
                )
              )}
            </select>
          </div>

          <div className={styles.formGroup}>
            <label>
              Commencement Date *
            </label>

            <input
              required
              type="date"
              value={form.start_date}
              onChange={(e) =>
                setForm({
                  ...form,
                  start_date:
                    e.target.value,
                })
              }
            />
          </div>

          <div className={styles.formGroup}>
            <label>
              Capacity / Role *
            </label>

            <select
              required
              value={form.capacity}
              onChange={(e) =>
                setForm({
                  ...form,
                  capacity:
                    e.target.value,
                })
              }
            >
              <option value="">
                Select Role
              </option>

              <option value="HEAD_PASTOR">
                Head Pastor
              </option>

              <option value="PASTOR">
                Pastor
              </option>

              <option value="MINISTER">
                Minister
              </option>
            </select>
          </div>

          <div className={styles.formGroup}>
            <label>Remark</label>

            <textarea
              value={form.remark}
              onChange={(e) =>
                setForm({
                  ...form,
                  remark:
                    e.target.value,
                })
              }
            />
          </div>

          <button
            className={styles.submitBtn}
          >
            Transfer
          </button>
        </form>
      </div>
    </div>,
    document.body
  );
};

/* =========================================================
| CONFIRM MODAL
========================================================= */

const ConfirmModal = ({
  title,
  onConfirm,
  close,
  pastor,
  type,
}: any) => {
  return ReactDOM.createPortal(
    <div
      className={styles.modalBackdrop}
      onClick={close}
    >
      <div
        className={styles.modalContent}
        onClick={(e) =>
          e.stopPropagation()
        }
      >
        <div className={styles.modalHeader}>
          <h2>{title}</h2>

          {type === "permission" ? (
            <p>
              {!pastor?.is_suspended
                ? `You are about to suspend Pastor ${pastor?.first_name} ${pastor?.last_name} and he/she will lose access to the platform`
                : `You are about to reinstate Pastor ${pastor?.first_name} ${pastor?.last_name} and he/she will gain access back to the platform`}
            </p>
          ) : (
            <p>
              You are about to delete
              this Pastor. This will
              delete all the associated
              data too. Be sure before
              you proceed.
            </p>
          )}
        </div>

        <div
          className={styles.confirmActions}
        >
          <button
            onClick={close}
            className={
              styles.cancelBtn
            }
          >
            Cancel
          </button>

          <button
            onClick={onConfirm}
            className={
              styles.dangerBtn
            }
          >
            Confirm
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
};

/* =========================================================
| MAIN PAGE
========================================================= */

const PastorView = ({
  pastor,
  branches,
}: any) => {
  const [active, setActive] =
    useState("bio");

  const [menu, setMenu] =
    useState(false);

  const [showTransfer, setShowTransfer] =
    useState(false);

  const [confirm, setConfirm] =
    useState<any>(null);

  /* =========================================================
  | SAFE VALUES
  ========================================================= */

  const age = pastor?.date_of_birth
    ? new Date().getFullYear() -
      new Date(
        pastor.date_of_birth
      ).getFullYear()
    : "—";

  const years = pastor?.date_joined
    ? new Date().getFullYear() -
      new Date(
        pastor.date_joined
      ).getFullYear()
    : "—";

  const initials = `${
    pastor?.first_name?.[0] || ""
  }${
    pastor?.last_name?.[0] || ""
  }`;

  /* =========================================================
  | REUSABLE ROW
  ========================================================= */

  const row = (
    icon: any,
    label: string,
    value: any
  ) => (
    <div className={styles.row}>
      <span className={styles.icon}>
        {icon}
      </span>

      <div>
        <p className={styles.label}>
          {label}
        </p>

        <h4 className={styles.value}>
          {value || "—"}
        </h4>
      </div>
    </div>
  );

  /* =========================================================
  | HISTORY
  ========================================================= */

  const history = useMemo(() => {
    return [
      ...(pastor?.transfers || []),
    ].sort(
      (a: any, b: any) =>
        new Date(
          a.start_date
        ).getTime() -
        new Date(
          b.start_date
        ).getTime()
    );
  }, [pastor?.transfers]);

  /* =========================================================
  | INTERSECTION OBSERVER
  ========================================================= */

  const itemRefs = useRef<
    (HTMLDivElement | null)[]
  >([]);

  const [
    visibleItems,
    setVisibleItems,
  ] = useState<number[]>([]);

  useEffect(() => {
    setVisibleItems([]);

    const observer =
      new IntersectionObserver(
        (entries) => {
          entries.forEach(
            (entry) => {
              const index =
                Number(
                  entry.target.getAttribute(
                    "data-index"
                  )
                );

              if (
                entry.isIntersecting
              ) {
                setVisibleItems(
                  (prev) => {
                    if (
                      prev.includes(
                        index
                      )
                    ) {
                      return prev;
                    }

                    return [
                      ...prev,
                      index,
                    ];
                  }
                );
              }
            }
          );
        },
        {
          threshold: 0.15,
        }
      );

    itemRefs.current.forEach(
      (item) => {
        if (item) {
          observer.observe(item);
        }
      }
    );

    return () => {
      observer.disconnect();
    };
  }, [history, active]);

  return (
    <div className={styles.page}>
      {/* =========================================================
      | HEADER
      ========================================================= */}

      <div className={styles.header}>
        <div
          className={
            styles.dataHeadText
          }
        >
          {pastor.first_name}'s
          Information
        </div>

        <div className={styles.avatar}>
          {initials}
        </div>
      </div>

      {/* =========================================================
      | PROFILE SECTION
      ========================================================= */}

      <div className={styles.profile}>
        <div className={styles.nameRow}>
          <h1>
            {pastor.first_name}{" "}
            {pastor.last_name}
          </h1>

          <span
            className={`${
              styles.badge
            } ${
              pastor.is_suspended
                ? styles.danger
                : styles.success
            }`}
          >
            {pastor.is_suspended
              ? "Suspended"
              : "Active"}
          </span>
        </div>

        <div className={styles.meta}>
          🇳🇬{" "}
          {pastor.branch?.name ||
            "Unassigned"}

          <span className={styles.dot} />

          {age} Years old

          <span className={styles.dot} />

          {years} Years in
          service
        </div>

        {/* =========================================================
        | ACTIONS
        ========================================================= */}

        <div className={styles.actions}>
          <button
            className={
              pastor.is_suspended
                ? styles.activateBtn
                : styles.suspendBtn
            }
            onClick={() =>
              setConfirm({
                type: "permission",

                title:
                  pastor.is_suspended
                    ? "Reinstate Pastor?"
                    : "Suspend Pastor?",

                action: () => {
                  router.post(
                    `/admin/pastors/${pastor.id}/suspend`,
                    {},
                    {
                      onSuccess:
                        () => {
                          setConfirm(
                            null
                          );
                        },
                    }
                  );
                },
              })
            }
          >
            <FiSlash />

            {pastor.is_suspended
              ? "Reinstate"
              : "Suspend"}
          </button>

          <button
            className={
              styles.transferBtn
            }
            onClick={() =>
              setShowTransfer(true)
            }
          >
            <FiSend /> Transfer
          </button>

          {/* MENU */}

          <div className={styles.menu}>
            <button
              onClick={() =>
                setMenu(!menu)
              }
            >
              <FiMoreVertical />
            </button>

            {menu && (
              <div
                className={
                  styles.dropdown
                }
              >
                <div
                  onClick={() =>
                    router.visit(
                      `/admin/pastors/${pastor.id}/edit`
                    )
                  }
                >
                  <FiEdit /> Update
                </div>

                <div
                  className={
                    styles.delete
                  }
                  onClick={() =>
                    setConfirm({
                      title:
                        "Delete Pastor?",

                      action: () => {
                        router.delete(
                          `/admin/pastors/${pastor.id}`,
                          {
                            onSuccess:
                              () => {
                                setConfirm(
                                  null
                                );

                                router.visit(
                                  "/admin/pastors"
                                );
                              },
                          }
                        );
                      },
                    })
                  }
                >
                  <FiTrash2 /> Delete
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* =========================================================
      | BODY
      ========================================================= */}

      <div className={styles.wrapper}>
        {/* SIDEBAR */}

        <div className={styles.sidebar}>
          {tabs.map((t) => (
            <div
              key={t.key}
              className={`${
                styles.tabItem
              } ${
                active === t.key
                  ? styles.activeTab
                  : ""
              }`}
              onClick={() =>
                setActive(t.key)
              }
            >
              <h4>{t.title}</h4>

              <p>{t.desc}</p>
            </div>
          ))}
        </div>

        {/* CONTENT */}

        <div className={styles.content}>
          <div
            className={
              styles.contentHeader
            }
          >
            <h2>
              {
                tabs.find(
                  (t) =>
                    t.key === active
                )?.title
              }
            </h2>

            <p>
              {
                tabs.find(
                  (t) =>
                    t.key === active
                )?.desc
              }
            </p>

            <br />
          </div>

          {/* =========================================================
          | BIO
          ========================================================= */}

          {active === "bio" && (
            <div className={styles.grid}>
              {row(
                <FiUser />,
                "Surname",
                pastor.surname
              )}

              {row(
                <FiUser />,
                "First Name",
                pastor.first_name
              )}

              {row(
                <FiUser />,
                "Last Name",
                pastor.last_name
              )}

              {row(
                <FiMail />,
                "Email",
                pastor.email
              )}

              {row(
                <FiPhone />,
                "Phone",
                pastor.phone
              )}

              {row(
                <FiHome />,
                "State of Origin",
                pastor.state
              )}

              {row(
                <FiUser />,
                "Gender",
                pastor.gender
              )}

              {row(
                <FiCalendar />,
                "Date of Birth",
                formatReadableDate(
                  pastor.date_of_birth
                )
              )}

              {row(
                <FiMapPin />,
                "Marital Status",
                pastor.marital_status
              )}

              {row(
                <FiMapPin />,
                "Address",
                pastor.address
              )}
            </div>
          )}

          {/* =========================================================
          | ACADEMIC
          ========================================================= */}

          {active === "academic" && (
            <div className={styles.grid}>
              {pastor.qualification ===
              "Other" ? (
                row(
                  <FiBook />,
                  "Educational / Vocational Background",
                  pastor.qualification_details ||
                    "-"
                )
              ) : (
                <>
                  {row(
                    <FiBook />,
                    "Highest Qualification",
                    pastor.qualification
                  )}

                  {row(
                    <FiBook />,
                    "Course of Study",
                    pastor.course ||
                      "-"
                  )}

                  {row(
                    <FiCalendar />,
                    "Graduation Year",
                    pastor.graduation_year ||
                      "-"
                  )}
                </>
              )}
            </div>
          )}

          {/* =========================================================
          | MINISTRY
          ========================================================= */}

          {active === "ministry" && (
            <div className={styles.grid}>
              {row(
                <FiHome />,
                "Branch",
                pastor.branch?.name
              )}

              {row(
                <FiCalendar />,
                "Date Joined",
                formatReadableDate(
                  pastor.date_joined
                )
              )}

              {row(
                <FiCalendar />,
                "Ordination Date",
                formatReadableDate(
                  pastor.ordination_date
                )
              )}

              {row(
                <FiCalendar />,
                "Date Left",
                pastor.date_left
                  ? formatReadableDate(
                      pastor.date_left
                    )
                  : "Currently Serving"
              )}

              {row(
                <FiUser />,
                "Status",
                pastor.is_suspended
                  ? "Suspended"
                  : "Active"
              )}

              {row(
                <FiMapPin />,
                "State of Service",
                pastor.branch?.state
              )}

              {row(
                <FiBook />,
                "Remarks",
                pastor.remarks
              )}
            </div>
          )}

          {/* =========================================================
          | BANKING
          ========================================================= */}

          {active === "banking" && (
            <div className={styles.grid}>
              {row(
                <FiHome />,
                "Bank Name",
                pastor
                  ?.primary_bank_account
                  ?.bank_name
              )}

              {row(
                <FiUser />,
                "Account Name",
                pastor
                  ?.primary_bank_account
                  ?.account_name
              )}

              {row(
                <FiBook />,
                "Account Number",
                pastor
                  ?.primary_bank_account
                  ?.masked_account_number
              )}
            </div>
          )}

          {/* =========================================================
          | HISTORY
          ========================================================= */}

          {active === "history" && (
            <div className={styles.timeline}>
              {history.length < 1 ? (

                <div
                  className={
                    styles.emptyHistory
                  }
                >
                  No transfer history
                  available
                </div>

              ) : (

                history.map(
                  (
                    transfer: any,
                    i: number
                  ) => {

                    const isLast =
                      i ===
                      history.length - 1;

                    const isVisible =
                      visibleItems.includes(
                        i
                      );

                    return (

                      <div
                        key={
                          transfer.id || i
                        }
                        ref={(el) => {
                          itemRefs.current[i] =
                            el;
                        }}
                        data-index={i}
                        className={`${
                          styles.timelineItem
                        } ${
                          isVisible
                            ? styles.show
                            : ""
                        }`}
                      >

                        {!isLast && (
                          <div
                            className={
                              styles.line
                            }
                          />
                        )}

                        <div
                          className={`${
                            styles.circle
                          } ${
                            isVisible
                              ? styles.activeNode
                              : ""
                          }`}
                        >
                          <span>
                            {i + 1}
                          </span>
                        </div>

                        <div
                          className={
                            styles.timelineCard
                          }
                        >
                          <div
                            className={
                              styles.timelineHeader
                            }
                          >
                            <h3>
                              {
                                transfer
                                  ?.branch
                                  ?.name
                              }
                            </h3>

                            <span
                              className={`${
                                styles.status
                              } ${
                                isLast
                                  ? styles.current
                                  : styles.completed
                              }`}
                            >
                              {isLast
                                ? "Current"
                                : "Completed"}
                            </span>
                          </div>

                          <div
                            className={
                              styles.timelineBody
                            }
                          >
                            <p>
                              {transfer.capacity
                                ? transfer.capacity.replaceAll(
                                    "_",
                                    " "
                                  )
                                : "Pastoral Assignment"}
                            </p>
                          </div>

                          <span
                            className={
                              styles.date
                            }
                          >
                            {transfer.start_date
                              ? formatReadableDate(
                                  transfer.start_date
                                )
                              : "Unknown Date"}

                            {" → "}

                            {transfer.end_date
                              ? formatReadableDate(
                                  transfer.end_date
                                )
                              : "Present"}
                          </span>

                          {transfer.remark && (
                            <details
                              className={
                                styles.expand
                              }
                            >
                              <summary>
                                View Details
                              </summary>

                              <p>
                                {
                                  transfer.remark
                                }
                              </p>
                            </details>
                          )}
                        </div>
                      </div>
                    );
                  }
                )
              )}
            </div>
          )}
        </div>
      </div>

      {/* =========================================================
      | MODALS
      ========================================================= */}

      {showTransfer && (
        <TransferModal
          pastor={pastor}
          branches={branches}
          close={() =>
            setShowTransfer(false)
          }
        />
      )}

      {confirm && (
        <ConfirmModal
          type={confirm.type}
          pastor={pastor}
          title={confirm.title}
          onConfirm={confirm.action}
          close={() =>
            setConfirm(null)
          }
        />
      )}
    </div>
  );
};

PastorView.layout = (
  page: any
) => (
  <AdminLayout title="Pastor Details">
    {page}
  </AdminLayout>
);

export default PastorView;