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

import { useState, useEffect } from "react";
import DashboardLayout from "@/layouts/dashboard";
import styles from "./account.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";

/* ================= CONSTANTS (UNCHANGED) ================= */
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" },
];


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",
];

/* ================= SEARCHABLE SELECT ================= */
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}
          value={query || value || ""}
          placeholder={`Select ${label}`}
          onFocus={() => setOpen(true)}
          onBlur={() => setTimeout(() => setOpen(false), 150)}
          onChange={(e) => {
            setQuery(e.target.value);
            onChange(name, "");
          }}
        />

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

/* ================= MAIN ================= */
const AccountProfile = ({ pastor, branches }: any) => {

  console.log("DOB:", pastor.date_of_birth)

  const [step, setStep] = useState(0);
  const [showConfirm, setShowConfirm] = useState(false);

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

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

/* ================= PREFILL ================= */
useEffect(() => {
  if (!pastor) return;

  setForm({
    // ================= POSITION =================
    position: pastor.position || "",

    // ================= BIO =================
    firstName: pastor.first_name || "",
    lastName: pastor.last_name || "",
    surname: pastor.surname || "",

    email: pastor.email || "",

    phone: pastor.phone || "",
    address: pastor.address || "",
    state: pastor.state || "",
    gender: pastor.gender || "",

    dob: pastor.date_of_birth
    ? pastor.date_of_birth.split("T")[0]
    : "",

    maritalStatus: pastor.marital_status || "",

    // ================= ACADEMIC =================
    qualification: pastor.qualification || "",
    qualification_details: pastor.qualification_details || "",
    course: pastor.course || "",
    year: pastor.graduation_year || "",

    // ================= MINISTRY =================
    dateJoined: pastor.date_joined
      ? pastor.date_joined.split("T")[0]
      : "",

    ordinationDate: pastor.ordination_date
      ? pastor.ordination_date.split("T")[0]
      : "",

    dateLeft: pastor.date_left
      ? pastor.date_left.split("T")[0]
      : "",

    // 🔥 RELATION: PLACES SERVED
    places_served: (pastor.places_served || []).map((p: any) => ({
      id: p.id, // VERY IMPORTANT FOR UPDATE
      branch_id: p.branch_id || "",
      start_date: p.start_date ? p.start_date.split("T")[0] : "",
      end_date: p.end_date ? p.end_date.split("T")[0] : "",
      capacity: p.capacity || "",
      remark: p.remark || "",
    })),

    // 🔥 RELATION: BANK ACCOUNT (PRIMARY)
    bank_name: pastor.bank_accounts?.[0]?.bank_name || "",
    account_name: pastor.bank_accounts?.[0]?.account_name || "",
    account_number: pastor.bank_accounts?.[0]?.account_number || "",

    // ================= OTHER =================
    remarks: pastor.remarks || "",
  });
}, [pastor]);

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

    // 🔥 HANDLE QUALIFICATION SWITCH
    if (name === "qualification") {
      if (value === "Other") {
        updated.course = "";
        updated.year = "";
      } else {
        updated.qualification_details = "";
      }
    }

    return updated;
  });
};


  const age =
    new Date().getFullYear() -
    new Date(pastor.date_of_birth).getFullYear();

  const years =
    new Date().getFullYear() -
    new Date(pastor.date_joined).getFullYear();

  const initials = `${pastor.first_name[0]}${pastor.last_name[0]}`;

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

  /* ================= SUBMIT ================= */
  const submit = () => setShowConfirm(true);

  const confirm = () => {
    router.post(`/admin/profile/update`, form);
  };


  return (
    <div className={styles.page}>
      <div className={styles.header}>
        <div className={styles.dataHeadText}>{pastor.first_name}'s Information</div>
        <div className={styles.avatar}>{initials}</div>
      </div>

      <div className={styles.profile}>
        <div className={styles.nameRow}>
          <h1>
            {pastor.first_name} {pastor.last_name}
          </h1>

          <span
            className={`${styles.badge} ${
              pastor.is_suspended ? styles.danger : styles.success
            }`}
          >
            {pastor.is_suspended ? "Suspended" : "Active"}
          </span>
        </div>

        <div className={styles.meta}>
          🇳🇬{pastor.branch?.name}
          <span className={styles.dot} />
          {age} Years old
          <span className={styles.dot} />
          {years} Years in service
        </div>
      </div>

      {/* ================= PROFILE ================= */}
        <div className={styles.wrapper}>
          
          {/* SIDEBAR */}
          <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>

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

            <div className={`${styles.formBody} ${step === 0 ? styles.bioGrid : ""}`}>

              {/* ================= BIO ================= */}
              {step === 0 && (
                <>
                  <Input label="First Name" name="firstName" value={form.firstName} onChange={updateField} icon={<FiUser />} />
                  <Input label="Last Name" name="lastName" value={form.lastName} onChange={updateField} icon={<FiUser />} />
                  <Input label="Surname" name="surname" value={form.surname} onChange={updateField} icon={<FiUser />} />
                  <Input label="Email" name="email" value={form.email} onChange={updateField} icon={<FiMail />} />
                  <Input label="Phone" name="phone" value={form.phone} onChange={updateField} icon={<FiPhone />} />
                  <Input label="Address" name="address" value={form.address} onChange={updateField} 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={[
                      "Single","Married","Divorced","Widowed","Separated","Engaged","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>

                  {form.qualification === "Other" && (
                    <div className={styles.fullWidth}>
                      <Textarea
                        label="Qualification Details"
                        name="qualification_details"
                        value={form.qualification_details}
                        onChange={updateField}
                      />
                    </div>
                  )}

                  {form.qualification !== "Other" && (
                    <>
                      <Input label="Course" name="course" value={form.course} onChange={updateField} />
                      <Input label="Graduation Year" name="year" value={form.year} onChange={updateField} />
                    </>
                  )}
                </>
              )}

              {/* ================= MINISTRY (FULL — UNTOUCHED) ================= */}
              {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>
                </>
              )}

              {/* ================= BANK ================= */}
              {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} />
                  <Input label="Account Number" name="account_number" value={form.account_number} onChange={updateField} />
                </>
              )}
            </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={true}
          title="Confirm Update"
          message="Are you sure you want to update this profile?"
          onCancel={()=>setShowConfirm(false)}
          onConfirm={confirm}
        />
      )}
    </div>
  );
};

/* ================= INPUT ================= */
const Input = ({ label, name, value, onChange, icon, type="text" }: any) => (
  <div className={styles.inputGroup}>
    <label>{label}</label>
    <div className={styles.inputWrapper}>
      {icon}
      <input
        type={type}
        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)}
    >
      {/* DEFAULT OPTION */}
      <option value="">Select {label}</option>

      {options.map((o: any, index: number) => {
        //NORMALIZE OPTION
        const val = typeof o === "object" ? o.value : o;
        const text = typeof o === "object" ? o.label : o;

        return (
          <option key={`${val}-${index}`} value={val}>
            {text}
          </option>
        );
      })}
    </select>
  </div>
);

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

AccountProfile.layout = (page:any)=>(
  <DashboardLayout title="Account Profile and Security">{page}</DashboardLayout>
);

export default AccountProfile;