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

import { useState } from "react";
import { router, usePage } from "@inertiajs/react";
import { FiX, FiCheckCircle, FiAlertTriangle } from "react-icons/fi";
import styles from "../modal-styles.module.scss";
import PageIntro from "@/components/dashboard/page-intro";

const AppointmentBookingModal = ({
  onClose,
  hasActiveAppointment = false,
  is_accepting_appointments,
}: any) => {
  const { props }: any = usePage();
  const flash = props.flash || {};

  const todayBookings = flash.today_bookings;
  const dailyLimit = flash.daily_limit;

  const [form, setForm] = useState({
    appointment_type: "",
    note: "",
  });

  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<any>({});
  const [success, setSuccess] = useState(false);

  // 🔥 NEW
  const [agreed, setAgreed] = useState(false);

  const isDisabled = hasActiveAppointment || !is_accepting_appointments;
  const isBookingClosed = !is_accepting_appointments;

  const handleChange = (e: any) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value,
    });
  };

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

    if (isDisabled || !agreed) return;

    setLoading(true);

    router.post(route("member.appointments.store"), form, {
      onError: (err) => {
        setErrors(err);
        setLoading(false);
      },
      onSuccess: () => {
        setLoading(false);
        setSuccess(true);
      },
    });
  };

  const percentage =
    todayBookings && dailyLimit
      ? Math.min((todayBookings / dailyLimit) * 100, 100)
      : 0;

  return (
    <div className={styles.modalBackdrop}>
      <div className={styles.modalContent}>

        {/* ================= HEADER ================= */}
        <div className={styles.modalHeader}>
          <PageIntro
            title={success ? "Booking Confirmed" : "Request Appointment"}
            description={
              success
                ? "Your appointment will be reviewed and assigned a date accordingly"
                : "Request Appointment by filling the form completely"
            }
          />

          <button className={styles.closeBtn} onClick={onClose}>
            <FiX />
          </button>
        </div>

        {/* ================= SUCCESS ================= */}
        {success && (
          <div className={styles.successBox}>
            <div className={styles.successIconWrapper}>
              <FiCheckCircle className={styles.successIcon} />
            </div>

            <h3>You're booked!</h3>

            <p>
              You are number <strong>{todayBookings}</strong> out of{" "}
              <strong>{dailyLimit}</strong> today.
            </p>

            <div className={styles.progressBar}>
              <div
                className={styles.progressFill}
                style={{ width: `${percentage}%` }}
              />
            </div>

            <p className={styles.smallNote}>
              Your appointment will be reviewed in the shortest possible time.
            </p>

            <button className={styles.successBtn} onClick={onClose}>
              Close
            </button>
          </div>
        )}

        {/* ================= MAIN ================= */}
        {!success && (
          <>
            {/* ================= STATUS ================= */}
            <div className={styles.statusWrapper}>
              {!hasActiveAppointment && !isBookingClosed && (
                <div
                  className={`${styles.availability} ${
                    is_accepting_appointments
                      ? styles.available
                      : styles.unavailable
                  }`}
                >
                  <span className={styles.indicator} />
                  Pastor is accepting appointments
                </div>
              )}

              {hasActiveAppointment && (
                <div className={styles.blockedBanner}>
                  <FiAlertTriangle size={"2rem"} />

                  <div>
                    <strong>Booking not allowed</strong>
                    <p>
                      You have already booked an appointment this month.
                      You can only request once per month.
                    </p>
                  </div>
                </div>
              )}
            </div>

            {/* ================= FORM ================= */}
            <form onSubmit={handleSubmit} className={styles.modalForm}>
              <fieldset
                disabled={isDisabled}
                className={isDisabled ? styles.disabledFieldset : ""}
              >
                <div className={styles.formGroup}>
                  <label>Appointment Type</label>

                  <select
                    name="appointment_type"
                    value={form.appointment_type}
                    onChange={handleChange}
                  >
                    <option value="">Select type</option>
                    <option value="prayer">Prayer</option>
                    <option value="deliverance">Deliverance</option>
                    <option value="counselling">Counselling</option>
                    <option value="mentorship">Mentorship</option>
                    <option value="healing">Healing</option>
                    <option value="others">Others</option>
                  </select>

                  {errors.appointment_type && (
                    <span className={styles.error}>
                      {errors.appointment_type}
                    </span>
                  )}
                </div>

                <br />

                <div className={styles.formGroup}>
                  <label>Reason for Appointment</label>

                  <textarea
                    name="note"
                    placeholder="Briefly describe your request..."
                    value={form.note}
                    onChange={handleChange}
                  />

                  {errors.note && (
                    <span className={styles.error}>{errors.note}</span>
                  )}
                </div>
              </fieldset>

              {/* ================= CONFIRMATION ================= */}
              <div
                className={`${styles.confirmBox} ${
                  agreed ? styles.confirmActive : ""
                }`}
                onClick={() => setAgreed(!agreed)}
              >
                <div className={styles.checkWrapper}>
                  <input
                    type="checkbox"
                    checked={agreed}
                    onChange={() => setAgreed(!agreed)}
                  />
                  <span className={styles.customCheck} />
                </div>

                <div className={styles.confirmText}>
                  <p>
                    I consent to booking this appointment
                  </p>
                </div>
              </div>

              {/* ================= SUBMIT ================= */}
              <button
                type="submit"
                disabled={loading || isDisabled || !agreed}
                className={styles.submitBtn}
              >
                {isBookingClosed
                  ? "Booking Closed"
                  : hasActiveAppointment
                  ? "Already Booked This Month"
                  : loading
                  ? "Submitting..."
                  : "Submit Request"}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
};

export default AppointmentBookingModal;