/* eslint-disable @typescript-eslint/no-explicit-any */
import React from "react";
import ReactDOM from "react-dom";
import styles from "../create-attendance-modal/modal.module.scss";
import { useForm, router } from "@inertiajs/react";

interface ModalProps {
  closeModal: () => void;
  type: "add" | "update";
  project?: any;
  onSuccess?: (message: string) => void;
}

interface ProjectFormData {
  name: string;
  location: string;
  status: string;
  description: string;
}

const CreateProjectModal: React.FC<ModalProps> = ({
  closeModal,
  type,
  project,
}) => {
 const { data, setData, post, put, processing, errors, reset } = useForm<ProjectFormData>({
  name: project?.name || "",
  location: project?.location || "",
  status: project?.status || "",
  description: project?.description || "",
});

  const statusOptions = [
    { id: 1, name: "completed" },
    { id: 2, name: "on-going" },
    { id: 3, name: "pending" },
  ];

  // Handle input changes
  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    setData(name as keyof typeof data, value);
  };

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

   if (type === "add") {
       post(route("project_store"), {
         onSuccess: () => {
           reset();
           closeModal();
           // reload flash props globally
           router.reload({ only: ["flash"] });
         },
       });
     } else if (type === "update" && project?.id) {
       put(route("project_update", project.id), {
         onSuccess: () => {
           reset();
           closeModal();
           router.reload({ only: ["flash"] });
         },
       });
     }
   };

  return ReactDOM.createPortal(
    <div className={styles.modal}>
      <div className={styles["modal__content"]}>
        {/* Header */}
        <div className={styles["modal__content--header"]}>
          <h2>{type === "add" ? "Add New Project" : "Update Project"}</h2>
          <p>
            {type === "add"
              ? "You can add a new project seamlessly by filling out the form below."
              : "Update the selected project record seamlessly."}
          </p>
          <span onClick={closeModal} className={styles["modal__close"]}>
            Close
          </span>
        </div>

        {/* Form */}
        <form className={styles["modal__content--form"]} onSubmit={handleSubmit}>
          {/* Project Name */}
          <div className={styles["modal__content--form--group"]}>
            <label htmlFor="name">Project Name *</label>
            <input
              type="text"
              name="name"
              id="name"
              value={data.name}
              onChange={handleChange}
              placeholder="Please enter the name of the project"
              required
            />
            {errors.name && <span className={styles.error}>{errors.name}</span>}
          </div>

          {/* Location */}
          <div className={styles["modal__content--form--group"]}>
            <label htmlFor="location">Project Location *</label>
            <input
              type="text"
              name="location"
              id="location"
              value={data.location}
              onChange={handleChange}
              required
              placeholder="Please enter the location of the project"
            />
          </div>

          {/* Status */}
          <div className={styles["modal__content--form--group"]}>
            <label htmlFor="status">Project Status *</label>
            <select
              name="status"
              id="status"
              value={data.status}
              onChange={handleChange}
              required
            >
              <option value="" disabled>
                Please select applicable status
              </option>
              {statusOptions.map((sta) => (
                <option key={sta.id} value={sta.name}>
                  {sta.name.charAt(0).toUpperCase() + sta.name.slice(1)}
                </option>
              ))}
            </select>
          </div>

          {/* Description */}
          <div className={styles["modal__content--form--group"]}>
            <label htmlFor="description">Project Description</label>
            <textarea
              name="description"
              id="description"
              value={data.description}
              onChange={handleChange}
              placeholder="Enter the project description"
            />
          </div>

          <button type="submit" disabled={processing}>
            {processing
              ? type === "add"
                ? "Creating..."
                : "Updating..."
              : type === "add"
              ? "Create Project"
              : "Update Project"}
          </button>
        </form>
      </div>
    </div>,
    document.body
  );
};

export default CreateProjectModal;
