import React from "react"
import styles from "./faq-modal.module.scss"
import { useForm, router } from "@inertiajs/react"

interface FaqForm {
  question: string
  answer: string
}

interface FaqModalProps {
  closeModal: () => void
  type: "add" | "update"
  faq?: Partial<FaqForm> & { id?: number }
}

const FaqModal: React.FC<FaqModalProps> = ({ closeModal, type, faq }) => {
  const { data, setData, post, put, processing, reset } = useForm<FaqForm>({
    question: faq?.question ?? "",
    answer: faq?.answer ?? "",
  })

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

    const onSuccess = () => {
      reset("question", "answer")
      closeModal()
      router.reload({ only: ["flash"] })
    }

    if (type === "add") {
      post(route("faqs.store"), { onSuccess })
      return
    }

    if (type === "update" && faq?.id) {
      put(
        route("faqs.update", { id: faq.id }),
        { onSuccess }
      )
    }
  }

  return (
    <div className={styles["faq"]}>
      <div className={styles["faq__content"]}>
        <div
          onClick={closeModal}
          className={styles["faq__content--close"]}
        >
          Close
        </div>

        <div className={styles["faq__content--details"]}>
          <div className={styles["faq__content--details--header"]}>
            <div
              className={
                styles["faq__content--details--header--helper"]
              }
            >
              {type === "add" ? "Create" : "Update"}
            </div>

            <h2>
              {type === "add" ? "Create FAQ" : "Update FAQ"}
            </h2>

            <p>
              {type === "add"
                ? "Create a new frequently asked question for your website."
                : "Update only the fields you wish to change below."}
            </p>
          </div>

          <form onSubmit={handleSubmit}>
            <div>
              <label>Question *</label>
              <input
                type="text"
                value={data.question}
                onChange={(e) =>
                  setData("question", e.target.value)
                }
                required
              />
            </div>

            <div>
              <label>Answer *</label>
              <textarea
                value={data.answer}
                onChange={(e) =>
                  setData("answer", e.target.value)
                }
                required
              />
            </div>

            <button type="submit" disabled={processing}>
              {processing
                ? type === "add"
                  ? "Adding..."
                  : "Updating..."
                : type === "add"
                ? "Add FAQ"
                : "Update FAQ"}
            </button>
          </form>
        </div>
      </div>
    </div>
  )
}

export default FaqModal
