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

import React from "react";
import ReactDOM from "react-dom";
import styles from "./branch.module.scss";
import { useForm, router } from "@inertiajs/react";

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

const nigeriaStates = [
  "Abia","Adamawa","Akwa Ibom","Anambra","Bauchi","Bayelsa","Benue",
  "Borno","Cross River","Delta","Ebonyi","Edo","Ekiti","Enugu",
  "FCT - Abuja","Gombe","Imo","Jigawa","Kaduna","Kano","Katsina",
  "Kebbi","Kogi","Kwara","Lagos","Nasarawa","Niger","Ogun","Ondo",
  "Osun","Oyo","Plateau","Rivers","Sokoto","Taraba","Yobe","Zamfara"
];

const CreateBranchModal: React.FC<ModalProps> = ({
  closeModal,
  type,
  branch,
}) => {
  const { data, setData, post, put, processing, errors, reset } = useForm({
    name: type === "update" ? branch?.name || "" : "",
    address: type === "update" ? branch?.address || "" : "",
    state: type === "update" ? branch?.state || "" : "",
    pastor_in_charge:
      type === "update" ? branch?.pastor_in_charge || "" : "",
    is_active:
      type === "update" ? branch?.is_active ?? true : true, // ✅ NEW
  });

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

    if (type === "add") {
      post(route("branches_store"), {
        onSuccess: () => {
          reset();
          closeModal();
          router.reload({ only: ["flash"] });
        },
      });
    } else if (type === "update" && branch?.id) {
      put(route("branches_update", branch.id), {
        onSuccess: () => {
          reset();
          closeModal();
          router.reload({ only: ["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" ? "Create New Branch" : "Update Branch"}</h2>
          <p>Fill in the details to continue</p>
          <button className={styles.closeBtn} onClick={closeModal}>
            ×
          </button>
        </div>

        {/* FORM */}
        <form onSubmit={handleSubmit} className={styles.modalForm}>
          {/* NAME */}
          <div className={styles.formGroup}>
            <label>Branch Name *</label>
            <input
              type="text"
              value={data.name}
              onChange={(e) => setData("name", e.target.value)}
              placeholder="Censers Church Enugu"
            />
            {errors.name && (
              <small className={styles.error}>{errors.name}</small>
            )}
          </div>

          {/* ADDRESS */}
          <div className={styles.formGroup}>
            <label>Address *</label>
            <input
              type="text"
              value={data.address}
              onChange={(e) => setData("address", e.target.value)}
              placeholder="Full church address"
            />
            {errors.address && (
              <small className={styles.error}>{errors.address}</small>
            )}
          </div>

          {/* STATE */}
          <div className={styles.formGroup}>
            <label>State *</label>
            <select
              value={data.state}
              onChange={(e) => setData("state", e.target.value)}
            >
              <option value="">Select State</option>
              {nigeriaStates.map((state) => (
                <option key={state} value={state}>
                  {state}
                </option>
              ))}
            </select>
            {errors.state && (
              <small className={styles.error}>{errors.state}</small>
            )}
          </div>

          {/* PASTOR */}
          {/* <div className={styles.formGroup}>
            <label>Pastor in Charge *</label>
            <input
              type="text"
              value={data.pastor_in_charge}
              onChange={(e) =>
                setData("pastor_in_charge", e.target.value)
              }
              placeholder="Pastor Name"
            />
            {errors.pastor_in_charge && (
              <small className={styles.error}>
                {errors.pastor_in_charge}
              </small>
            )}
          </div> */}

          {/* 🔥 STATUS (NEW) */}
          <div className={styles.formGroup}>
            <label>Status *</label>
            <select
              value={data.is_active ? "true" : "false"}
              onChange={(e) =>
                setData("is_active", e.target.value === "true")
              }
            >
              <option value="true">Active</option>
              <option value="false">Inactive</option>
            </select>
            {errors.is_active && (
              <small className={styles.error}>{errors.is_active}</small>
            )}
          </div>

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

export default CreateBranchModal;