"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { ChevronLeft, LogOut, Calendar, Stethoscope, X, Menu, ChevronDown } from "lucide-react";
import { myHospitalsApi } from "@/app/services/hospial";
import { addPatientQueueApi } from "@/app/services/patientQueue";
import { DoctorOption } from "@/app/types/patientQueue";
import { useAuthStore } from "@/app/store/useAuthStore";
import { useUserStore } from "@/app/store/userStore";
import ReceptionistSidebar from "@/components/modals/ui/ReceptionistSidebar";

const C = {
  pink: "#f06292",
  purple: "#3a1280",
  bg: "#f5f5f7",
  white: "#ffffff",
  cardBorder: "#e8e2f0",
  fieldBg: "#f0ecf8",
  textMain: "#1a1a2e",
  textSub: "#6b6b8a",
  textLabel: "#4b5563",
};

// ── Static value used in place of the removed Mobile Number field ──
const STATIC_MOBILE_NUMBER = "9999999999";

export default function ReceptionistNewPrescription() {
  const router = useRouter();
  const { logout } = useAuthStore();
  const { user, loadUserFromStorage } = useUserStore();

  const [sidebarOpen, setSidebarOpen] = useState(false);

  const [patientName, setPatientName] = useState("");
  const [age, setAge] = useState("");
  const [ageUnit, setAgeUnit] = useState<"Y" | "M">("Y");
  const [weight, setWeight] = useState("");
  const [bp, setBp] = useState("");
  const [pulse, setPulse] = useState("");
  const [spo2, setSpo2] = useState("");
  const [temp, setTemp] = useState("");
  const [gender, setGender] = useState<number>(-1);

  const [doctorOptions, setDoctorOptions] = useState<DoctorOption[]>([]);
  const [selectedDoctor, setSelectedDoctor] = useState<DoctorOption | null>(null);
  const [showDoctorModal, setShowDoctorModal] = useState(false);
  const [isLoadingDoctors, setIsLoadingDoctors] = useState(false);
  const doctorDropdownRef = useRef<HTMLDivElement>(null);

  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  const now = new Date();
  const dateLabel = now.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  const timeLabel = now.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" });

  useEffect(() => {
    loadUserFromStorage();
  }, []);

  useEffect(() => {
    const fetchHospitals = async () => {
      try {
        setIsLoadingDoctors(true);
        const response = await myHospitalsApi();

        if (response?.status === 1) {
          const hospitals = response?.data ?? [];

          const collected: DoctorOption[] = [];
          for (const hospital of hospitals) {
            const hospitalName = hospital?.name ?? "Unknown Hospital";
            const doctorMembers = (hospital?.members ?? []).filter(
              (m: any) => m.user_role === "doctor"
            );

            for (const member of doctorMembers) {
              const userId = member?.user?._id || member?.user?.id;
              if (!userId) continue;
              const name = member?.user?.fullname ?? "Unknown Doctor";
              collected.push({ id: userId, name, hospitalName });
            }
          }
          setDoctorOptions(collected);
        } else {
          setDoctorOptions([]);
        }
      } catch (error) {
        console.error(error);
        setDoctorOptions([]);
      } finally {
        setIsLoadingDoctors(false);
      }
    };

    fetchHospitals();
  }, []);

  // ── Close the doctor dropdown when clicking anywhere outside it ──
  useEffect(() => {
    if (!showDoctorModal) return;
    function handleClickOutside(e: MouseEvent) {
      if (doctorDropdownRef.current && !doctorDropdownRef.current.contains(e.target as Node)) {
        setShowDoctorModal(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [showDoctorModal]);

  const handleNext = async () => {
    if (!selectedDoctor) {
      setSubmitError("Please select a doctor");
      return;
    }

    try {
      setSubmitting(true);
      setSubmitError(null);

      const today = new Date().toISOString().split("T")[0];

      const payload = {
        patient_info: {
          patient_visit_date: today,
          patient_name: patientName,
          patient_age: age,
          patient_age_in_years: ageUnit === "Y" ? Number(age) || 0 : 0,
          patient_weight: weight,
          patient_bp: bp,
          patient_pulse: pulse,
          patient_spo2: spo2,
          patient_temp: temp,
          patient_mobile: STATIC_MOBILE_NUMBER,
          patient_gender: gender,
        },
        doctorId: selectedDoctor.id,
      };

      const res = await addPatientQueueApi(payload);

      if (res?.status === 1) {
        router.push("/receptionist-dashboard");
      } else {
        setSubmitError(res?.msg || "Failed to add patient to queue");
      }
    } catch (error: any) {
      setSubmitError(
        error?.response?.data?.msg || error?.message || "Failed to add patient to queue"
      );
    } finally {
      setSubmitting(false);
    }
  };

  const genderOptions = [
    { label: "Male", value: 0 },
    { label: "Female", value: 1 },
    { label: "Rather not to say", value: 2 },
  ];

  return (
    <div style={{ display: "flex", width: "100%", minHeight: "100vh", background: C.bg }}>
      {/* Desktop sidebar */}
      <aside className="hidden md:block w-64 shrink-0 bg-white border-r border-[#e5e7eb] sticky top-0 h-screen">
        <ReceptionistSidebar user={user} />
      </aside>

      {/* Mobile sidebar drawer */}
      {sidebarOpen && (
        <div className="fixed inset-0 z-50 md:hidden">
          <div className="absolute inset-0 bg-black/40" onClick={() => setSidebarOpen(false)} />
          <div className="absolute left-0 top-0 bottom-0 w-60 bg-white py-6 overflow-y-auto">
            <ReceptionistSidebar user={user} onClose={() => setSidebarOpen(false)} />
          </div>
        </div>
      )}

      <div style={{ flex: 1, minWidth: 0 }}>
        {/* Header */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "18px clamp(16px, 4vw, 40px)",
            background: C.white,
            borderBottom: `1px solid ${C.cardBorder}`,
            position: "sticky",
            top: 0,
            zIndex: 10,
          }}
        >

          <h1 style={{ fontSize: 20, fontWeight: 800, color: C.purple, margin: 0 }}>
            Patient Information
          </h1>
          <button
            onClick={() => logout()}
            style={{
              width: 40,
              height: 40,
              borderRadius: "50%",
              background: C.purple,
              border: "none",
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              flexShrink: 0,
            }}
          >
            <LogOut size={18} color="#fff" />
          </button>
        </div>

        {/* Full-width content area */}
        <div
          style={{
            width: "100%",
            maxWidth: 900,
            margin: "0 auto",
            padding: "clamp(16px, 3vw, 32px)",
          }}
        >
          {/* Date/time pill */}
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 20 }}>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                background: C.white,
                borderRadius: 24,
                padding: "12px 22px",
                fontWeight: 700,
                color: C.purple,
                fontSize: 15,
                border: `1px solid ${C.cardBorder}`,
              }}
            >
              <Calendar size={16} color={C.pink} />
              {dateLabel} &nbsp; {timeLabel}
            </div>
          </div>

          {/* Card */}
          <div
            style={{
              background: C.white,
              borderRadius: 20,
              border: `1px solid ${C.cardBorder}`,
              padding: "clamp(20px, 3vw, 32px)",
              display: "flex",
              flexDirection: "column",
              gap: 18,
            }}
          >
            {/* Patient name */}
            <div>
              <FieldLabel>Patient Name</FieldLabel>
              <input
                style={fieldStyle}
                placeholder="Full name"
                value={patientName}
                onChange={(e) => setPatientName(e.target.value)}
              />
            </div>

            {/* Age + Weight */}
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",
                gap: 14,
              }}
            >


              <div>
                <FieldLabel>Weight (KG)</FieldLabel>
                <input
                  style={fieldStyle}
                  placeholder="e.g. 65"
                  value={weight}
                  onChange={(e) => setWeight(e.target.value)}
                />
              </div>
              <div>
                <FieldLabel>Age</FieldLabel>
                <div style={{ display: "flex", gap: 6 }}>
                  <input
                    style={{ ...fieldStyle, flex: 1, minWidth: 0 }}
                    placeholder="e.g. 32"
                    value={age}
                    onChange={(e) => setAge(e.target.value)}
                  />
                  <div
                    style={{
                      display: "flex",
                      borderRadius: 12,
                      overflow: "hidden",
                      border: `1.5px solid ${C.cardBorder}`,
                      flexShrink: 0,
                    }}
                  >
                    {(["Y", "M"] as const).map((u) => (
                      <button
                        key={u}
                        onClick={() => setAgeUnit(u)}
                        style={{
                          padding: "0 16px",
                          border: "none",
                          cursor: "pointer",
                          fontWeight: 700,
                          fontSize: 14,
                          background: ageUnit === u ? C.pink : C.white,
                          color: ageUnit === u ? "#fff" : C.textSub,
                          transition: "all .15s",
                        }}
                      >
                        {u}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Gender */}
            <div>
              <FieldLabel>Gender</FieldLabel>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))",
                  gap: 8,
                }}
              >
                {genderOptions.map((g) => {
                  const sel = gender === g.value;
                  return (
                    <button
                      key={g.value}
                      onClick={() => setGender(sel ? -1 : g.value)}
                      style={{
                        padding: "13px 10px",
                        borderRadius: 12,
                        border: `1.5px solid ${sel ? C.pink : C.cardBorder}`,
                        background: sel ? C.pink : C.white,
                        color: sel ? "#fff" : C.textMain,
                        fontWeight: 700,
                        fontSize: 13,
                        cursor: "pointer",
                        transition: "all .15s",
                      }}
                    >
                      {g.label}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Divider + Vitals section */}
            <div style={{ borderTop: `1px solid ${C.cardBorder}`, paddingTop: 16 }}>
              <FieldLabel>Vitals</FieldLabel>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 14,
                  marginTop: 4,
                }}
              >
                <div>
                  <FieldLabel>BP (mmHg)</FieldLabel>
                  <input style={fieldStyle} placeholder="120/80" value={bp} onChange={(e) => setBp(e.target.value)} />
                </div>
                <div>
                  <FieldLabel>Pulse (bpm)</FieldLabel>
                  <input style={fieldStyle} placeholder="72" value={pulse} onChange={(e) => setPulse(e.target.value)} />
                </div>
                <div>
                  <FieldLabel>SpO₂ (%)</FieldLabel>
                  <input style={fieldStyle} placeholder="98" value={spo2} onChange={(e) => setSpo2(e.target.value)} />
                </div>
                <div>
                  <FieldLabel>Temperature</FieldLabel>
                  <input style={fieldStyle} placeholder="98.6°F" value={temp} onChange={(e) => setTemp(e.target.value)} />
                </div>
              </div>
            </div>

            {/* Doctor selector — inline dropdown, anchored under the button */}
            <div style={{ borderTop: `1px solid ${C.cardBorder}`, paddingTop: 16, position: "relative" }} ref={doctorDropdownRef}>
              <FieldLabel>Doctor</FieldLabel>
              <button
                onClick={() => setShowDoctorModal((v) => !v)}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  border: `1.5px solid ${showDoctorModal ? C.pink : C.cardBorder}`,
                  borderRadius: 12,
                  padding: "14px 16px",
                  background: "none",
                  cursor: "pointer",
                  textAlign: "left",
                  width: "100%",
                  boxSizing: "border-box",
                  transition: "border-color .15s",
                }}
              >
                <Stethoscope size={18} color={C.pink} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div
                    style={{
                      fontSize: 15,
                      fontWeight: 700,
                      color: selectedDoctor ? C.textMain : C.textSub,
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      whiteSpace: "nowrap",
                    }}
                  >
                    {selectedDoctor
                      ? `${selectedDoctor.name} — ${selectedDoctor.hospitalName}`
                      : "Select Doctor"}
                  </div>
                </div>
                <ChevronDown
                  size={18}
                  color={C.textSub}
                  style={{
                    flexShrink: 0,
                    transition: "transform .15s",
                    transform: showDoctorModal ? "rotate(180deg)" : "rotate(0deg)",
                  }}
                />
              </button>

              {/* Dropdown panel */}
              {showDoctorModal && (
                <div
                  style={{
                    position: "absolute",
                    top: "100%",
                    left: 0,
                    right: 0,
                    marginTop: 8,
                    background: C.white,
                    border: `1px solid ${C.cardBorder}`,
                    borderRadius: 14,
                    boxShadow: "0 12px 32px rgba(58,18,128,0.16)",
                    maxHeight: 320,
                    overflowY: "auto",
                    zIndex: 50,
                    padding: 8,
                  }}
                >
                  {isLoadingDoctors ? (
                    <p style={{ color: C.textSub, fontSize: 14, padding: "12px 8px", margin: 0 }}>
                      Loading doctors...
                    </p>
                  ) : doctorOptions.length === 0 ? (
                    <p style={{ color: C.textSub, fontSize: 14, padding: "12px 8px", margin: 0 }}>
                      No doctors found.
                    </p>
                  ) : (
                    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                      {doctorOptions.map((doc) => {
                        const isSelected = selectedDoctor?.id === doc.id;
                        return (
                          <button
                            key={doc.id}
                            onClick={() => {
                              setSelectedDoctor(doc);
                              setShowDoctorModal(false);
                            }}
                            style={{
                              display: "flex",
                              alignItems: "center",
                              gap: 12,
                              background: isSelected ? C.fieldBg : "transparent",
                              border: "none",
                              borderRadius: 10,
                              padding: "10px 10px",
                              cursor: "pointer",
                              textAlign: "left",
                              width: "100%",
                              boxSizing: "border-box",
                            }}
                            onMouseEnter={(e) => {
                              if (!isSelected) e.currentTarget.style.background = C.fieldBg;
                            }}
                            onMouseLeave={(e) => {
                              if (!isSelected) e.currentTarget.style.background = "transparent";
                            }}
                          >
                            <div
                              style={{
                                width: 34,
                                height: 34,
                                borderRadius: "50%",
                                background: "#4a90e2",
                                color: "#fff",
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "center",
                                fontWeight: 700,
                                fontSize: 14,
                                flexShrink: 0,
                              }}
                            >
                              {doc.name.charAt(0).toUpperCase()}
                            </div>
                            <div style={{ minWidth: 0 }}>
                              <div
                                style={{
                                  fontWeight: 700,
                                  fontSize: 14,
                                  color: C.textMain,
                                  overflow: "hidden",
                                  textOverflow: "ellipsis",
                                  whiteSpace: "nowrap",
                                }}
                              >
                                {doc.name}
                              </div>
                              <div style={{ fontSize: 11.5, color: C.textSub }}>{doc.hospitalName}</div>
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>
              )}
            </div>

            {submitError && (
              <p style={{ color: "red", fontSize: 13, margin: 0 }}>{submitError}</p>
            )}

            <button
              onClick={handleNext}
              disabled={submitting}
              style={{
                marginTop: 4,
                background: C.pink,
                color: "#fff",
                border: "none",
                borderRadius: 16,
                padding: "16px",
                fontWeight: 800,
                fontSize: 16,
                cursor: "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 8,
                opacity: submitting ? 0.6 : 1,
              }}
            >
              {submitting ? "Please wait..." : "Next"} →
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function FieldLabel({ children }: { children: React.ReactNode }) {
  return (
    <div
      style={{
        fontSize: 11,
        fontWeight: 700,
        color: "#4b5563",
        marginBottom: 6,
        textTransform: "uppercase",
        letterSpacing: "0.06em",
      }}
    >
      {children}
    </div>
  );
}

const fieldStyle: React.CSSProperties = {
  width: "100%",
  padding: "13px 15px",
  borderRadius: 10,
  border: "1px solid #ddd8ee",
  background: "#f0ecf8",
  fontSize: 14,
  color: "#1a1a2e",
  outline: "none",
  boxSizing: "border-box",
};