"use client";
import { useEffect, useState } from "react";
import ReceptionistSidebar from "@/components/modals/ui/ReceptionistSidebar";
import { useUserStore } from "@/app/store/userStore";
import Link from "next/link";
import { Plus, Users, Clock, CheckCircle2, Stethoscope, Search, RefreshCw } from "lucide-react";
// import { getPatientQueueApi } from "@/app/services/patientQueue";

const C = {
  pink: "#f06292",
  pinkLight: "#fce4ef",
  purple: "#3a1280",
  purpleLight: "#f0ecfb",
  bg: "#f5f5f7",
  white: "#ffffff",
  cardBorder: "#e8e2f0",
  textMain: "#1a1a2e",
  textSub: "#6b6b8a",
  textHint: "#b0adc8",
  green: "#16a34a",
  greenLight: "#e8f9ee",
  amber: "#d97706",
  amberLight: "#fef3e0",
};

interface QueueItem {
  id: string;
  patientName: string;
  age?: string;
  gender?: number;
  doctorName?: string;
  status: "waiting" | "with_doctor" | "completed";
  addedAt: string;
}

function StatCard({
  icon, label, value, tint, tintText,
}: { icon: React.ReactNode; label: string; value: number | string; tint: string; tintText: string }) {
  return (
    <div
      style={{
        background: C.white,
        borderRadius: 16,
        border: `1px solid ${C.cardBorder}`,
        padding: "18px 20px",
        display: "flex",
        alignItems: "center",
        gap: 14,
        flex: 1,
        minWidth: 200,
      }}
    >
      <div
        style={{
          width: 46, height: 46, borderRadius: 12, background: tint,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: tintText, flexShrink: 0,
        }}
      >
        {icon}
      </div>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, color: C.textMain, lineHeight: 1.1 }}>{value}</div>
        <div style={{ fontSize: 12, color: C.textSub, marginTop: 2 }}>{label}</div>
      </div>
    </div>
  );
}

function StatusBadge({ status }: { status: QueueItem["status"] }) {
  const map = {
    waiting: { label: "Waiting", bg: C.amberLight, color: C.amber },
    with_doctor: { label: "With Doctor", bg: C.pinkLight, color: C.pink },
    completed: { label: "Completed", bg: C.greenLight, color: C.green },
  } as const;
  const s = map[status];
  return (
    <span
      style={{
        display: "inline-flex", alignItems: "center", gap: 6,
        padding: "5px 12px", borderRadius: 20,
        background: s.bg, color: s.color,
        fontSize: 12, fontWeight: 700, whiteSpace: "nowrap",
      }}
    >
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: s.color }} />
      {s.label}
    </span>
  );
}

export default function ReceptionistDashboard() {
  const { user, loadUserFromStorage } = useUserStore();
  const [queue, setQueue] = useState<QueueItem[]>([]);
  const [isLoadingQueue, setIsLoadingQueue] = useState(false);
  const [search, setSearch] = useState("");
  const [sidebarOpen, setSidebarOpen] = useState(false);

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

  async function fetchQueue() {
    try {
      setIsLoadingQueue(true);
      // ── TODO: wire this up to your real "get today's patient queue" API ──
      // const response = await getPatientQueueApi();
      // if (response?.status === 1) {
      //   setQueue(response?.data ?? []);
      // } else {
      //   setQueue([]);
      // }
    } catch (error) {
      console.error(error);
      setQueue([]);
    } finally {
      setIsLoadingQueue(false);
    }
  }

  const filteredQueue = search
    ? queue.filter((q) => q.patientName.toLowerCase().includes(search.toLowerCase()))
    : queue;

  const stats = {
    total: queue.length,
    waiting: queue.filter((q) => q.status === "waiting").length,
    withDoctor: queue.filter((q) => q.status === "with_doctor").length,
    completed: queue.filter((q) => q.status === "completed").length,
  };

  const now = new Date();
  const hour = now.getHours();
  const greeting = hour < 12 ? "Good morning" : hour < 17 ? "Good afternoon" : "Good evening";

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

      {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's props type doesn't include onClose in its declaration
                Cast to any for the mobile instance so we can pass onClose without editing
                the sidebar component file. */}
            {(() => {
              const MobileSidebar = ReceptionistSidebar as any;
              return <MobileSidebar user={user} onClose={() => setSidebarOpen(false)} />;
            })()}
          </div>
        </div>
      )}

      <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
        {/* Sticky white header - same style as Dashboard page */}
        <header
          style={{
            height: 72,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "0 28px",
            background: C.white,
            borderBottom: "1px solid #e5e7eb",
            position: "sticky",
            top: 0,
            zIndex: 20,
          }}
        >
          <div>
            <h1 style={{ fontSize: 18, fontWeight: 700, color: C.textMain, margin: 0 }}>
              Receptionist Dashboard
            </h1>
            <p style={{ fontSize: 12, color: "#9ca3af", fontWeight: 500, marginTop: 2 }}>
              {greeting}, {user?.fullname ?? "Receptionist"} — overview of today's practice
            </p>
          </div>

          <Link
            href="/receptionist-dashboard/new-prescription"
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              background: C.pink,
              color: "#fff",
              borderRadius: 12,
              padding: "10px 20px",
              textDecoration: "none",
              fontWeight: 700,
              fontSize: 14,
              whiteSpace: "nowrap",
            }}
          >
            <Plus size={18} />
            New Prescription
          </Link>
        </header>

        <div style={{ flex: 1, padding: "clamp(20px, 3vw, 40px)", maxWidth: 1200, margin: "0 auto", width: "100%" }}>
          {/* Stats row */}
          <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginBottom: 28 }}>
            <StatCard
              icon={<Users size={20} />}
              label="Patients today"
              value={stats.total}
              tint={C.purpleLight}
              tintText={C.purple}
            />
            <StatCard
              icon={<Clock size={20} />}
              label="Waiting"
              value={stats.waiting}
              tint={C.amberLight}
              tintText={C.amber}
            />
            <StatCard
              icon={<Stethoscope size={20} />}
              label="With doctor"
              value={stats.withDoctor}
              tint={C.pinkLight}
              tintText={C.pink}
            />
            <StatCard
              icon={<CheckCircle2 size={20} />}
              label="Completed"
              value={stats.completed}
              tint={C.greenLight}
              tintText={C.green}
            />
          </div>

          {/* Queue card */}
          <div
            style={{
              background: C.white, borderRadius: 18, border: `1px solid ${C.cardBorder}`,
              overflow: "hidden",
            }}
          >
            <div
              style={{
                display: "flex", alignItems: "center", justifyContent: "space-between",
                flexWrap: "wrap", gap: 12, padding: "18px 22px",
                borderBottom: `1px solid ${C.cardBorder}`,
              }}
            >
              <span style={{ fontWeight: 800, fontSize: 16, color: C.textMain }}>Today's Queue</span>

              <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                <div
                  style={{
                    display: "flex", alignItems: "center", gap: 8,
                    background: "#f0ecf8", borderRadius: 10, padding: "9px 13px",
                  }}
                >
                  <Search size={15} color={C.textHint} />
                  <input
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder="Search patient…"
                    style={{
                      border: "none", background: "transparent", outline: "none",
                      fontSize: 13, color: C.textMain, width: 160,
                    }}
                  />
                </div>
                <button
                  onClick={fetchQueue}
                  title="Refresh"
                  style={{
                    width: 36, height: 36, borderRadius: 10, border: `1px solid ${C.cardBorder}`,
                    background: C.white, cursor: "pointer", display: "flex",
                    alignItems: "center", justifyContent: "center", color: C.textSub,
                    flexShrink: 0,
                  }}
                >
                  <RefreshCw size={15} className={isLoadingQueue ? "animate-spin" : ""} />
                </button>
              </div>
            </div>

            {isLoadingQueue ? (
              <div style={{ padding: "48px 20px", textAlign: "center", color: C.textSub, fontSize: 13 }}>
                Loading queue...
              </div>
            ) : filteredQueue.length === 0 ? (
              <div style={{ padding: "56px 20px", textAlign: "center" }}>
                <div
                  style={{
                    width: 64, height: 64, borderRadius: 18, background: C.pinkLight,
                    color: C.pink, display: "flex", alignItems: "center", justifyContent: "center",
                    margin: "0 auto 16px",
                  }}
                >
                  <Users size={28} />
                </div>
                <div style={{ fontWeight: 700, fontSize: 15, color: C.textMain, marginBottom: 4 }}>
                  {search ? `No patients matching "${search}"` : "No patients in queue yet"}
                </div>
                <div style={{ fontSize: 13, color: C.textSub }}>
                  {search ? "Try a different name." : "Add a patient to get started."}
                </div>
              </div>
            ) : (
              <div style={{ overflowX: "auto" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 560 }}>
                  <thead>
                    <tr style={{ background: "#faf9fc" }}>
                      {["Patient", "Age / Gender", "Doctor", "Added at", "Status"].map((h) => (
                        <th
                          key={h}
                          style={{
                            textAlign: "left", padding: "12px 22px", fontSize: 11,
                            fontWeight: 700, color: C.textSub, textTransform: "uppercase",
                            letterSpacing: "0.05em", whiteSpace: "nowrap",
                          }}
                        >
                          {h}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {filteredQueue.map((q) => (
                      <tr key={q.id} style={{ borderTop: `1px solid ${C.cardBorder}` }}>
                        <td style={{ padding: "14px 22px", fontWeight: 700, fontSize: 14, color: C.textMain }}>
                          {q.patientName}
                        </td>
                        <td style={{ padding: "14px 22px", fontSize: 13, color: C.textSub }}>
                          {q.age || "—"}
                        </td>
                        <td style={{ padding: "14px 22px", fontSize: 13, color: C.textMain }}>
                          {q.doctorName || "—"}
                        </td>
                        <td style={{ padding: "14px 22px", fontSize: 13, color: C.textSub }}>
                          {q.addedAt}
                        </td>
                        <td style={{ padding: "14px 22px" }}>
                          <StatusBadge status={q.status} />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}