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

import React, {
  useMemo,
  useState,
} from "react";

import ReactDOM from "react-dom";

import styles from "../modal-styles.module.scss";

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

import {
  FiSearch,
  FiSend,
} from "react-icons/fi";

interface Branch {
  id: number;
  name: string;
}

interface ModalProps {
  closeModal: () => void;
  branches: Branch[];
  pastors: any[];
}

const ROLES = [
  {
    label: "Head Pastor",
    value: "HEAD_PASTOR",
  },
  {
    label: "Pastor",
    value: "PASTOR",
  },
  {
    label: "Minister",
    value: "MINISTER",
  },
];

const TransferPastorModal: React.FC<ModalProps> = ({
  closeModal,
  branches,
  pastors,
}) => {
  const [search, setSearch] =
    useState("");

  const {
    data,
    setData,
    post,
    processing,
    errors,
  } = useForm({

    pastor_id: "",

    branch_id: "",

    start_date: "",

    role: "",

    remark: "",
  });

  /*
  |--------------------------------------------------------------------------
  | FILTER PASTORS
  |--------------------------------------------------------------------------
  */
  const filteredPastors =
    useMemo(() => {

      return pastors.filter(
        (pastor: any) => {

          if (!search)
            return true;

          const fullName = `
          ${pastor?.first_name || ""}
          ${pastor?.last_name || ""}
          ${pastor?.surname || ""}
        `
            .toLowerCase()
            .trim();

          return (
            fullName.includes(
              search.toLowerCase()
            ) ||

            pastor?.email
              ?.toLowerCase()
              .includes(
                search.toLowerCase()
              ) ||

            pastor?.branch?.name
              ?.toLowerCase()
              .includes(
                search.toLowerCase()
              )
          );
        }
      );

    }, [pastors, search]);

  /*
  |--------------------------------------------------------------------------
  | SUBMIT
  |--------------------------------------------------------------------------
  */
  const handleSubmit = (
    e: React.FormEvent
  ) => {

    e.preventDefault();

    console.log(
      "Transfer Payload:",
      data
    );

    post(
      route(
        "admin.pastors.transfer"
      ),
      {
        preserveScroll: true,

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

  return ReactDOM.createPortal(

    <div
      className={
        styles.modalBackdrop
      }
      onClick={closeModal}
    >

      <div
        className={
          styles.modalContent
        }
        onClick={(e) =>
          e.stopPropagation()
        }
      >

        {/* =======================================
        | HEADER
        ======================================= */}

        <div
          className={
            styles.modalHeader
          }
        >

          <div>

            <h2>
              Transfer Pastor
            </h2>

            <p>
              Transfer pastor to another
              branch and automatically
              update roles, access,
              places served and transfer
              history.
            </p>

          </div>

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

        </div>

        {/* =======================================
        | FORM
        ======================================= */}

        <form
          onSubmit={handleSubmit}
          className={
            styles.modalForm
          }
        >

          {/* =======================================
          | BRANCH
          ======================================= */}

          <div
            className={
              styles.formGroup
            }
          >

            <label>
              Transfer To Branch *
            </label>

            <select
              value={data.branch_id}
              onChange={(e) =>
                setData(
                  "branch_id",
                  e.target.value
                )
              }
            >

              <option value="">
                Select branch
              </option>

              {branches.map(
                (branch) => (

                  <option
                    key={branch.id}
                    value={branch.id}
                  >
                    {branch.name}
                  </option>
                )
              )}

            </select>

            {errors.branch_id && (

              <small
                className={
                  styles.error
                }
              >
                {
                  errors.branch_id
                }
              </small>
            )}

          </div>

          {/* =======================================
          | SEARCH
          ======================================= */}

          <div
            className={
              styles.searchBox
            }
          >

            <FiSearch />

            <input
              type="text"
              placeholder="Search pastor..."
              value={search}
              onChange={(e) =>
                setSearch(
                  e.target.value
                )
              }
            />

          </div>

          {/* =======================================
          | PASTOR
          ======================================= */}

          <div
            className={
              styles.formGroup
            }
          >

            <label>
              Select Pastor *
            </label>

            <select
              value={data.pastor_id}
              onChange={(e) =>
                setData(
                  "pastor_id",
                  e.target.value
                )
              }
            >

              <option value="">
                Select pastor
              </option>

              {filteredPastors.map(
                (pastor: any) => (

                  <option
                    key={pastor.id}
                    value={pastor.id}
                  >
                    {
                      pastor.first_name
                    }{" "}
                    {
                      pastor.last_name
                    }
                    {" — "}
                    {
                      pastor?.branch
                        ?.name
                    }
                  </option>
                )
              )}

            </select>

            {errors.pastor_id && (

              <small
                className={
                  styles.error
                }
              >
                {
                  errors.pastor_id
                }
              </small>
            )}

          </div>

          {/* =======================================
          | ROLE
          ======================================= */}

          <div
            className={
              styles.formGroup
            }
          >

            <label>
              New Role *
            </label>

            <select
              value={data.role}
              onChange={(e) =>
                setData(
                  "role",
                  e.target.value
                )
              }
            >

              <option value="">
                Select role
              </option>

              {ROLES.map((role) => (

                <option
                  key={role.value}
                  value={role.value}
                >
                  {role.label}
                </option>
              ))}

            </select>

            {errors.role && (

              <small
                className={
                  styles.error
                }
              >
                {errors.role}
              </small>
            )}

          </div>

          {/* =======================================
          | DATE
          ======================================= */}

          <div
            className={
              styles.formGroup
            }
          >

            <label>
              Transfer Date *
            </label>

            <input
              type="date"
              value={
                data.start_date
              }
              onChange={(e) =>
                setData(
                  "start_date",
                  e.target.value
                )
              }
            />

            {errors.start_date && (

              <small
                className={
                  styles.error
                }
              >
                {
                  errors.start_date
                }
              </small>
            )}

          </div>

          {/* =======================================
          | REMARK
          ======================================= */}

          <div
            className={
              styles.formGroup
            }
          >

            <label>
              Remark
            </label>

            <textarea
              rows={4}
              placeholder="Optional remark..."
              value={data.remark}
              onChange={(e) =>
                setData(
                  "remark",
                  e.target.value
                )
              }
            />

            {errors.remark && (

              <small
                className={
                  styles.error
                }
              >
                {errors.remark}
              </small>
            )}

          </div>

          {/* =======================================
          | EMPTY
          ======================================= */}

          {filteredPastors.length <
            1 && (

            <div
              className={
                styles.emptyState
              }
            >
              No pastors found
            </div>
          )}

          {/* =======================================
          | INFO
          ======================================= */}

          <div
            className={
              styles.infoBox
            }
          >

            <div
              className={
                styles.infoIcon
              }
            >
              <FiSend size={16} />
            </div>

            <div
              className={
                styles.infoContent
              }
            >

              <strong>
                Important
              </strong>

              <p>
                This action will
                automatically update
                the pastor's branch,
                permissions, role,
                transfer history,
                places served and
                dashboard access.
              </p>

            </div>

          </div>

          {/* =======================================
          | SUBMIT
          ======================================= */}

          <button
            type="submit"
            disabled={processing}
            className={
              styles.submitBtn
            }
          >

            {processing
              ? "Transferring..."
              : "Transfer Pastor"}

          </button>

        </form>

      </div>

    </div>,

    document.body
  );
};

export default TransferPastorModal;