/* eslint-disable react-hooks/set-state-in-effect */
/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import { useState, useEffect } from "react";
import AdminLayout from "@/layouts/admin-layout";
import DashboardHeader from "@/components/shared/DashPageHeader";
import styles from "./create-pastor.module.scss";
import { router } from "@inertiajs/react";
import ConfirmModal from "@/components/modals/confirmation-modal";

import {
  FiX,
  FiUser,
  FiMail,
  FiPhone,
  FiMapPin,
  FiBook,
  FiArrowLeft,
  FiArrowRight,
  FiArrowUp, 
  FiArrowDown,
} from "react-icons/fi";

const STORAGE_KEY = "create_pastor_form";

const steps = [
  { title: "Bio Data", desc: "Basic personal information" },
  { title: "Academic Data", desc: "Educational background" },
  { title: "Ministry Data", desc: "Ministry journey" },
  { title: "Banking Details", desc: "Financial information" },
  { title: "Others", desc: "Additional remarks" },
];

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

const banks = [
  // ================= COMMERCIAL BANKS =================
  "Access Bank",
  "Zenith Bank",
  "Guaranty Trust Bank (GTBank)",
  "First Bank of Nigeria",
  "United Bank for Africa (UBA)",
  "Fidelity Bank",
  "Wema Bank",
  "Ecobank Nigeria",
  "First City Monument Bank (FCMB)",
  "Sterling Bank",
  "Polaris Bank",
  "Union Bank",
  "Keystone Bank",
  "Unity Bank",
  "Stanbic IBTC Bank",
  "Standard Chartered Bank Nigeria",
  "Citibank Nigeria",
  "Titan Trust Bank",
  "Providus Bank",
  "Parallex Bank",
  "Signature Bank",
  "Globus Bank",
  "Premium Trust Bank",
  "Optimus Bank",
  "Nova Commercial Bank",

  // ================= NON-INTEREST (ISLAMIC) =================
  "Jaiz Bank",
  "TAJ Bank",
  "Lotus Bank",
  "The Alternative Bank",

  // ================= DIGITAL / FINTECH BANKS =================
  "Kuda Bank",
  "Moniepoint Microfinance Bank",
  "Opay (OPay Digital Services)",
  "PalmPay",
  "FairMoney Microfinance Bank",
  "Sparkle Microfinance Bank",
  "VFD Microfinance Bank",
  "Rubies Microfinance Bank",
  "Mintyn Bank",
  "Eyowo",

  // ================= POPULAR MICROFINANCE BANKS =================
  "LAPO Microfinance Bank",
  "AB Microfinance Bank",
  "Baobab Microfinance Bank",
  "Accion Microfinance Bank",
  "Assets Microfinance Bank",
  "RenMoney Microfinance Bank",
  "Fina Trust Microfinance Bank",

  // ================= GOVERNMENT / DEVELOPMENT BANKS =================
  "Bank of Industry",
  "Bank of Agriculture",
  "Development Bank of Nigeria",
  "Federal Mortgage Bank of Nigeria",
  "NEXIM Bank",
  "Infrastructure Bank",
];

const SearchableSelect = ({ label, options, name, value, onChange }: any) => {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);

  const filtered = options.filter((o: string) =>
    o.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <div className={styles.inputGroup}>
      <label>{label}</label>

      <div className={styles.searchSelectWrapper}>
        <input
          className={styles.searchInput}
          placeholder={`Select ${label}`}
          value={query || value || ""}
          onFocus={() => setOpen(true)}
          onBlur={() => setTimeout(() => setOpen(false), 150)}
          onChange={(e) => {
            setQuery(e.target.value);
            onChange(name, "");
          }}
        />

        {open && (
          <div className={styles.searchDropdown}>
            {filtered.length ? (
              filtered.map((item: string) => (
                <div
                  key={item}
                  className={styles.searchOption}
                  onMouseDown={() => {
                    onChange(name, item);
                    setQuery(item);
                    setOpen(false);
                  }}
                >
                  {item}
                </div>
              ))
            ) : (
              <div className={styles.noResult}>No results found</div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};


const CreatePastor = ({branches}: any) => {
  const [step, setStep] = useState(0);
  const [showConfirm, setShowConfirm] = useState(false);

  const [form, setForm] = useState<any>({});

  /* ================= PERSISTENCE ================= */
  useEffect(() => {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) setForm(JSON.parse(saved));
  }, []);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(form));
  }, [form]);

  const updateField = (name: string, value: any) => {
  setForm((prev: any) => {
    const updated = { ...prev, [name]: value };

    if (name === "qualification") {
      if (value === "Other") {
        // 🔥 Clear academic structured fields
        updated.course = null;
        updated.year = null;
      } else {
        // 🔥 Clear custom field
        updated.qualification_details = "";
      }
    }

    return updated;
  });
};

  const next = () => step < 4 && setStep(step + 1);
  const prev = () => step > 0 && setStep(step - 1);

  const submit = () => setShowConfirm(true);

  const confirm = () => {
    router.post("/admin/pastors", form);
    localStorage.removeItem(STORAGE_KEY);
  };

  const [activePlace, setActivePlace] = useState<number | null>(null);

  return (
    <div className={styles.page}>
      <DashboardHeader
        title="Add Pastor"
        description="Add a new pastor to the Censers Church Inc."
      />

      <div className={styles.wrapper}>
        <div className={styles.sidebar}>
          {steps.map((s, i) => (
            <div
              key={i}
              className={`${styles.stepItem} ${
                step === i ? styles.activeStep : ""
              }`}
              onClick={() => setStep(i)}
            >
              <h4>{s.title}</h4>
              <p>{s.desc}</p>
            </div>
          ))}
        </div>

        <div className={styles.formArea}>
          <div className={styles.formHeader}>
            <h2>{steps[step].title}</h2>
            <p>{steps[step].desc}</p>
            <span>Step {step + 1} of 4</span>
          </div>

          <div className={`${styles.formBody} ${step === 0 ? styles.bioGrid : ""}`}>
            
            {/* BIO */}
            {step === 0 && (
              <>
                <Input label="First Name" name="firstName" value={form.firstName} onChange={updateField} placeholder="Enter first name" icon={<FiUser />} />
                <Input label="Last Name" name="lastName" value={form.lastName} onChange={updateField} placeholder="Enter last name" icon={<FiUser />} />
                <Input label="Surname" name="surname" value={form.surname} onChange={updateField} placeholder="Enter surname" icon={<FiUser />} />

                <Input label="Email" name="email" value={form.email} onChange={updateField} placeholder="example@email.com" icon={<FiMail />} />
                <Input label="Phone" name="phone" value={form.phone} onChange={updateField} placeholder="08012345678" icon={<FiPhone />} />
                <Input label="Address" name="address" value={form.address} onChange={updateField} placeholder="Enter home address" icon={<FiMapPin />} />

                <Select label="State of origin" name="state" value={form.state} onChange={updateField} options={states} />
                <Select label="Gender" name="gender" value={form.gender} onChange={updateField} options={["Male", "Female"]} />
                <Input label="Date of Birth" name="dob" value={form.dob} onChange={updateField} type="date" />
                <Select
                  label="Marital Status"
                  name="maritalStatus"
                  value={form.maritalStatus}
                  onChange={updateField}
                  options={[
                    { label: "Single", value: "Single" },
                    { label: "Married", value: "Married" },
                    { label: "Divorced", value: "Divorced" },
                    { label: "Widowed", value: "Widowed" },
                    { label: "Separated", value: "Separated" },
                    { label: "Engaged", value: "Engaged" },
                    { label: "Other", value: "Other" }
                  ]}
                />
              </>
            )}

            {/* ACADEMIC */}
            {step === 1 && (
              <>
                <div
                    className={
                      form.qualification === "Other" ? styles.fullWidth : ""
                    }
                  >
                    <Select
                      label="Highest Qualification"
                      name="qualification"
                      value={form.qualification}
                      onChange={updateField}
                      options={[
                        { label: "OND (Ordinary National Diploma)", value: "OND (Ordinary National Diploma)" },
                        { label: "HND (Higher National Diploma)", value: "HND (Higher National Diploma)" },
                        { label: "NCE (National Certificate in Education)", value: "NCE (National Certificate in Education)" },
                        { label: "B.Sc (Bachelor of Science)", value: "B.Sc (Bachelor of Science)" },
                        { label: "B.A (Bachelor of Arts)", value: "B.A (Bachelor of Arts)" },
                        { label: "B.Eng (Bachelor of Engineering)", value: "B.Eng (Bachelor of Engineering)" },
                        { label: "B.Tech (Bachelor of Technology)", value: "B.Tech (Bachelor of Technology)" },
                        { label: "B.Ed (Bachelor of Education)", value: "B.Ed (Bachelor of Education)" },
                        { label: "MBBS (Medicine & Surgery)", value: "MBBS (Medicine & Surgery)" },
                        { label: "LLB (Law)", value: "LLB (Law)" },
                        { label: "BL (Barrister at Law)", value: "BL (Barrister at Law)" },
                        { label: "Pharm.D (Doctor of Pharmacy)", value: "Pharm.D (Doctor of Pharmacy)" },
                        { label: "DVM (Doctor of Veterinary Medicine)", value: "DVM (Doctor of Veterinary Medicine)" },
                        { label: "BDS (Dentistry)", value: "BDS (Dentistry)" },
                        { label: "PGD (Postgraduate Diploma)", value: "PGD (Postgraduate Diploma)" },
                        { label: "M.Sc (Master of Science)", value: "M.Sc (Master of Science)" },
                        { label: "M.A (Master of Arts)", value: "M.A (Master of Arts)" },
                        { label: "MBA (Master of Business Administration)", value: "MBA (Master of Business Administration)" },
                        { label: "M.Eng (Master of Engineering)", value: "M.Eng (Master of Engineering)" },
                        { label: "M.Ed (Master of Education)", value: "M.Ed (Master of Education)" },
                        { label: "LLM (Master of Laws)", value: "LLM (Master of Laws)" },
                        { label: "Ph.D (Doctor of Philosophy)", value: "Ph.D (Doctor of Philosophy)" },
                        { label: "Other", value: "Other" }
                      ]}
                    />
                  </div>

                {/* 🔥 ONLY SHOW THIS WHEN OTHER */}
                {form.qualification === "Other" && (
                  <div className={styles.fullWidth}>
                    <Textarea
                      label="Tell us about the pastor's educational or vocational background"
                      name="qualification_details"
                      value={form.qualification_details}
                      onChange={updateField}
                      placeholder="Describe educational background..."
                    />
                  </div>
                )}

                {/* 🔥 HIDE THESE WHEN OTHER */}
                {form.qualification !== "Other" && (
                  <>
                    <Input
                      label="Course"
                      placeholder="e.g Computer Science"
                      name="course"
                      value={form.course}
                      onChange={updateField}
                      icon={<FiBook />}
                    />

                    <Input
                      placeholder="Graduation year"
                      label="Graduation Year"
                      name="year"
                      value={form.year}
                      onChange={updateField}
                      type="number"
                    />
                  </>
                )}
              </>
            )}

            {/* MINISTRY */}
            {step === 2 && (
              <>
                <Input label="Date Joined" name="dateJoined" value={form.dateJoined} onChange={updateField} type="date" />
                <Input label="Ordination Date" name="ordinationDate" value={form.ordinationDate} onChange={updateField} type="date" />
                <Input label="Date Left" name="dateLeft" value={form.dateLeft} onChange={updateField} type="date" />

                <div className={styles.fullWidth}>
                  <div className={styles.placesHeader}>
                    <h4>Places Served</h4>
                    <button
                      type="button"
                      onClick={() => {
                        const newList = [
                          ...(form.places_served || []),
                          {
                            branch_id: "",
                            start_date: "",
                            end_date: "",
                            capacity: "",
                            remark: "",
                          },
                        ];

                        updateField("places_served", newList);
                        setActivePlace(newList.length - 1);
                      }}
                    >
                      + Add Place
                    </button>
                  </div>

                  {(form.places_served || []).map((place: any, index: number) => {
                    const isOpen = activePlace === index;
                    const isLast = index === form.places_served.length - 1;

                    // 🚨 OVERLAP CHECK
                    const hasOverlap = form.places_served.some((p: any, i: number) => {
                      if (i === index) return false;
                      if (!p.start_date || !place.start_date) return false;

                      return (
                        new Date(place.start_date) <= new Date(p.end_date || "9999-12-31") &&
                        new Date(p.start_date) <= new Date(place.end_date || "9999-12-31")
                      );
                    });

                    return (
                      <div key={index} className={styles.placeWrapper}>
                        {/* HEADER */}
                        <div className={styles.placeHeader}>
                          <div
                            className={styles.placeTitle}
                            onClick={() => setActivePlace(isOpen ? null : index)}
                          >
                            <h5>
                              {place.capacity || "New Assignment"} •{" "}
                              {place.start_date || "No date"}
                            </h5>

                            {/* ✅ CURRENT BADGE */}
                            {isLast && (
                              <span className={styles.currentBadge}>
                                Current Assignment
                              </span>
                            )}

                            {/* ❌ OVERLAP WARNING */}
                            {hasOverlap && (
                              <span className={styles.errorBadge}>
                                Overlapping Dates
                              </span>
                            )}
                          </div>

                          <div className={styles.placeActions}>
                            {/* MOVE UP */}
                            <button
                              type="button"
                              disabled={index === 0}
                              onClick={(e) => {
                                e.stopPropagation();
                                const updated = [...form.places_served];
                                [updated[index - 1], updated[index]] = [
                                  updated[index],
                                  updated[index - 1],
                                ];
                                updateField("places_served", updated);
                              }}
                            >
                              <FiArrowUp />
                            </button>

                            {/* MOVE DOWN */}
                            <button
                              type="button"
                              disabled={index === form.places_served.length - 1}
                              onClick={(e) => {
                                e.stopPropagation();
                                const updated = [...form.places_served];
                                [updated[index + 1], updated[index]] = [
                                  updated[index],
                                  updated[index + 1],
                                ];
                                updateField("places_served", updated);
                              }}
                            >
                              <FiArrowDown />
                            </button>

                            {/* TOGGLE */}
                            <span onClick={() => setActivePlace(isOpen ? null : index)}>
                              {isOpen ? "−" : "+"}
                            </span>

                            {/* DELETE */}
                            <button
                              type="button"
                              className={styles.removeBtn}
                              onClick={(e) => {
                                e.stopPropagation();
                                const updated = [...form.places_served];
                                updated.splice(index, 1);
                                updateField("places_served", updated);
                                setActivePlace(null);
                              }}
                            >
                              <FiX />
                            </button>
                          </div>
                        </div>

                        {/* BODY */}
                        {isOpen && (
                        <div className={styles.placeCard}>
                          
                          {/* ROW 1 */}
                          <div className={styles.placeRow}>
                            <Select
                              label="Branch"
                              name="branch_id"
                              value={place.branch_id}
                              onChange={(name: string, value: any) => {
                                const updated = [...form.places_served];
                                updated[index].branch_id = value;
                                updateField("places_served", updated);
                              }}
                              options={branches.map((b: any) => ({
                                label: b.name,
                                value: b.id,
                              }))}
                            />

                            <Input
                              label="Start Date"
                              type="date"
                              value={place.start_date}
                              onChange={(name: string, value: any) => {
                                const updated = [...form.places_served];
                                updated[index].start_date = value;
                                updateField("places_served", updated);
                              }}
                            />

                            <Input
                              label="End Date"
                              type="date"
                              value={place.end_date}
                              onChange={(name: string, value: any) => {
                                const updated = [...form.places_served];
                                updated[index].end_date = value;
                                updateField("places_served", updated);
                              }}
                            />
                          </div>

                          {/* ROW 2 */}
                          <div className={styles.placeRow}>
                            <Input
                              label="Capacity"
                              value={place.capacity}
                              onChange={(name: string, value: any) => {
                                const updated = [...form.places_served];
                                updated[index].capacity = value;
                                updateField("places_served", updated);
                              }}
                            />

                            <Input
                              label="Remark"
                              value={place.remark}
                              onChange={(name: string, value: any) => {
                                const updated = [...form.places_served];
                                updated[index].remark = value;
                                updateField("places_served", updated);
                              }}
                            />

                            {/* EMPTY SLOT (keeps alignment clean) */}
                            <div />
                          </div>
                        </div>
                      )}

                        <hr className={styles.placeDivider} />
                      </div>
                    );
                  })}
                </div>
              </>
            )}

            {/* BANKING DETAILS */}
              {step === 3 && (
                <>
                 <SearchableSelect
                  label="Bank Name"
                  name="bank_name"
                  value={form.bank_name}
                  onChange={updateField}
                  options={banks}
                />

                  <Input
                    label="Account Name"
                    name="account_name"
                    value={form.account_name}
                    onChange={updateField}
                    placeholder="Enter account name"
                    icon={<FiUser />}
                  />

                  <Input
                    label="Account Number"
                    name="account_number"
                    value={form.account_number}
                    onChange={(name: string, value: any) => {
                      // allow only digits
                      if (!/^\d*$/.test(value)) return;

                      // max 10 digits
                      if (value.length > 10) return;

                      updateField(name, value);
                    }}
                    placeholder="Enter 10-digit account number"
                  />
                  {form.account_number && form.account_number.length !== 10 && (
                    <span className={styles.error}>
                      Account number must be 10 digits
                    </span>
                  )}
                </>
              )}

            {/* OTHERS */}
            {step === 4 && (
              <>
              <div className={styles.fullWidth}>
                <Select
                  label="Assign Branch (Optional)"
                  name="branch_id"
                  value={form.branch_id}
                  onChange={updateField}
                  options={branches?.map((b: any) => ({
                    label: b.name,
                    value: b.id,
                  })) || []}
                />
              </div>

              <div className={styles.fullWidth}>
                <Textarea label="Other Remarks" name="remarks" value={form.remarks} onChange={updateField} placeholder="Any additional notes..." />
              </div>
              </>
            )}
          </div>

          {/* FOOTER */}
          <div className={styles.footer}>
            <button className={styles.secondaryBtn} onClick={prev} disabled={step === 0}>
              <FiArrowLeft /> Previous
            </button>

            {step === 3 ? (
              <button className={styles.primaryBtn} onClick={submit}>
                Save Details
              </button>
            ) : (
              <button className={styles.primaryOutline} onClick={next}>
                Next <FiArrowRight />
              </button>
            )}
          </div>
        </div>
      </div>

      {/* MODAL */}
      {showConfirm && (
        <ConfirmModal
          isOpen={showConfirm}
          title="Confirm Submission"
          message="Are you sure you want to create this pastor's record?"
          onCancel={() => setShowConfirm(false)}
          onConfirm={confirm}
          // loading={processing}
        />
      )}
    </div>
  );
};

/* ================= COMPONENTS ================= */
const Input = ({ label, icon, name, value, onChange, placeholder, type = "text" }: any) => (
  <div className={styles.inputGroup}>
    <label>{label}</label>
    <div className={styles.inputWrapper}>
      {icon}
      <input
        type={type}
        placeholder={placeholder}
        value={value || ""}
        onChange={(e) => onChange(name, e.target.value)}
      />
    </div>
  </div>
);

const Select = ({ label, options, name, value, onChange }: any) => (
  <div className={styles.inputGroup}>
    <label>{label}</label>
    <select
      value={value || ""}
      onChange={(e) => onChange(name, e.target.value)}
    >
      <option value="">Select {label}</option>

      {options.map((o: any) => {
        const val = typeof o === "object" ? o.value : o;
        const label = typeof o === "object" ? o.label : o;

        return (
          <option key={val} value={val}>
            {label}
          </option>
        );
      })}
    </select>
  </div>
);

const Textarea = ({ label, name, value, onChange, placeholder }: any) => (
  <div className={styles.inputGroup}>
    <label>{label}</label>
    <textarea
      rows={4}
      placeholder={placeholder}
      value={value || ""}
      onChange={(e) => onChange(name, e.target.value)}
    />
  </div>
);

CreatePastor.layout = (page: any) => (
  <AdminLayout title="Create Pastor">{page}</AdminLayout>
);

export default CreatePastor;