"use client";
import { useEffect, useState } from "react";
import {
  Pill,
  Trash2,
  Plus,
  X,
  Tablets,
  Pill as CapsuleIcon,
  FlaskConical,
  Droplet,
  Brush,
  PackageOpen,
  Syringe,
  BriefcaseMedical,
  Users,
  Smile,
  User,
  PersonStanding,
  LucideIcon,
} from "lucide-react";
import { useMasterDataStore } from "@/app/store/masterDataStore";
import { useMedicineStore } from "@/app/store/medicineStore";
import { Medicine, AddMedicinePayload } from "@/app/types/medicalData";
import PageHeader from "@/components/modals/ui/PageHeader";
import ConfirmDeleteModal from "@/components/modals/ui/ConfirmDeleteModal";
import { DEFAULT_CATEGORIES } from "../category-order/page";

/* -------------------------------------------------------------------- */
/*  One single source of truth for "medicine type → icon".               */
/*  Used for: the type chips inside the Add-Medicine modal, the page's   */
/*  tab bar, AND the empty-state illustration — so the same icon always  */
/*  represents the same type everywhere in the app.                      */
/* -------------------------------------------------------------------- */

const MEDICINE_TYPES: { label: string; icon: LucideIcon }[] = [
  { label: "Tablet", icon: Tablets },
  { label: "Capsule", icon: CapsuleIcon },
  { label: "Syrup", icon: FlaskConical },
  { label: "Drops", icon: Droplet },
  { label: "Oint", icon: Brush },
  { label: "Powder", icon: PackageOpen },
  { label: "Injection", icon: Syringe },
  { label: "Surg. Items", icon: BriefcaseMedical },
];

function iconForType(type: string): LucideIcon {
  return MEDICINE_TYPES.find((t) => t.label === type)?.icon ?? Pill;
}

const PATIENT_TYPES = [
  { label: "All", value: "all", icon: Users },
  { label: "Pediatric", value: "pediatric", icon: Smile },
  { label: "Adult", value: "adult", icon: User },
  { label: "Geriatric", value: "geriatric", icon: PersonStanding },
];

const DOSES = ["½", "1", "1½", "2", "2½", "3", "3½", "4", "4½", "5"];
const QUANTITIES = ["1", "2", "3", "4", "5", "6", "8", "10", "20", "30"];

function Chip({
  label,
  selected,
  onClick,
  icon: Icon,
}: {
  label: string;
  selected: boolean;
  onClick: () => void;
  icon?: React.ComponentType<{ size?: number }>;
}) {
  return (
    <button
      onClick={onClick}
      className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium cursor-pointer transition-colors border-none ${selected
        ? "bg-[#d4537e] text-white"
        : "bg-[#f7f7f8] text-[#374151] hover:bg-[#fceef3] hover:text-[#d4537e]"
        }`}
    >
      {Icon && <Icon size={16} />}
      {label}
    </button>
  );
}

/* -------------------------------------------------------------------- */
/*  Empty state — shown per-tab whenever the active type has zero saved  */
/*  medicines. Icon matches the active tab's icon (from MEDICINE_TYPES). */
/* -------------------------------------------------------------------- */

function EmptyTypeState({ type }: { type: string }) {
  const ActiveIcon = iconForType(type);
  return (
    <div className="flex flex-col items-center justify-center gap-4 text-center px-6">
      <span className="w-28 h-28 rounded-[28px] bg-[#fceef3] text-[#d4537e] flex items-center justify-center">
        <ActiveIcon size={48} strokeWidth={1.6} />
      </span>
      <div>
        <p className="text-xl font-semibold text-[#111111]">
          No {type} added yet
        </p>
        <p className="text-base text-[#9ca3af] mt-1.5">
          Use &ldquo;Add New&rdquo; below to get started
        </p>
      </div>
    </div>
  );
}

function AddMedicineModal({
  open,
  onClose,
  frequencies,
  onAdd,
  loading,
  defaultType,
}: {
  open: boolean;
  onClose: () => void;
  frequencies: { drLang: string }[];
  onAdd: (p: AddMedicinePayload) => void;
  loading: boolean;
  defaultType: string;
}) {
  const empty: AddMedicinePayload = {
    type: defaultType,
    name: "",
    dose: "½",
    dose_frequency: "",
    qty: "1",
    meal_time: "After Meal",
    patient_type: "all",
  };
  const [form, setForm] = useState<AddMedicinePayload>(empty);
  const upd = (k: keyof AddMedicinePayload, v: string) =>
    setForm((p) => ({ ...p, [k]: v }));

  useEffect(() => {
    if (open) {
      setForm({
        ...empty,
        type: defaultType,
        dose_frequency: frequencies[0]?.drLang || "",
      });
    }
  }, [open, defaultType, frequencies]);

  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-white w-full max-w-[680px] rounded-3xl shadow-2xl max-h-[92vh] overflow-hidden flex flex-col">
        <div className="flex items-center justify-between px-7 py-5 border-b border-[#f3f4f6] flex-shrink-0">
          <p className="text-lg font-semibold text-[#d4537e]">Add Medicine</p>
          <button
            onClick={onClose}
            className="w-9 h-9 rounded-lg flex items-center justify-center text-[#9ca3af] hover:bg-[#f7f7f8] bg-transparent border-none cursor-pointer"
          >
            <X size={20} />
          </button>
        </div>

        <div className="px-7 py-6 overflow-y-auto flex-1 flex flex-col gap-6">
          {/* Type */}
          <div>
            <p className="text-sm font-medium text-[#374151] mb-3">
              Select Medicine Type
            </p>
            <div className="flex flex-wrap gap-2">
              {MEDICINE_TYPES.map(({ label, icon }) => (
                <Chip
                  key={label}
                  label={label}
                  icon={icon}
                  selected={form.type === label}
                  onClick={() => upd("type", label)}
                />
              ))}
            </div>
          </div>
          {/* For whom */}
          <div>
            <p className="text-sm font-medium text-[#374151] mb-3">
              For whom (multiple selection)
            </p>
            <div className="flex flex-wrap gap-2">
              {PATIENT_TYPES.map(({ label, value, icon }) => (
                <Chip
                  key={value}
                  label={label}
                  icon={icon}
                  selected={form.patient_type === value}
                  onClick={() => upd("patient_type", value)}
                />
              ))}
            </div>
          </div>
          {/* Name */}
          <input
            type="text"
            placeholder="Name"
            value={form.name}
            onChange={(e) => upd("name", e.target.value)}
            className="w-full bg-[#f7f7f8] rounded-xl border-none outline-none px-4 py-3.5 text-base text-[#111111] placeholder:text-[#9ca3af]"
          />
          {/* Dose */}
          <div>
            <p className="text-sm font-medium text-[#374151] mb-3">Dose</p>
            <div className="flex flex-wrap gap-2">
              {DOSES.map((d) => (
                <Chip
                  key={d}
                  label={d}
                  selected={form.dose === d}
                  onClick={() => upd("dose", d)}
                />
              ))}
            </div>
          </div>
          {/* Frequency */}
          {frequencies.length > 0 && (
            <div>
              <p className="text-sm font-medium text-[#374151] mb-3">
                Frequency
              </p>
              <div className="flex flex-wrap gap-2">
                {frequencies.map(({ drLang }) => (
                  <Chip
                    key={drLang}
                    label={drLang}
                    selected={form.dose_frequency === drLang}
                    onClick={() => upd("dose_frequency", drLang)}
                  />
                ))}
              </div>
            </div>
          )}
          {/* Quantity */}
          <div>
            <p className="text-sm font-medium text-[#374151] mb-3">
              Quantity (To buy from Pharmacy)
            </p>
            <div className="flex flex-wrap gap-2">
              {QUANTITIES.map((q) => (
                <Chip
                  key={q}
                  label={q}
                  selected={form.qty === q}
                  onClick={() => upd("qty", q)}
                />
              ))}
            </div>
          </div>
          {/* Meal */}
          <div>
            <p className="text-sm font-medium text-[#374151] mb-3">
              Before / After Meal
            </p>
            <div className="flex rounded-2xl overflow-hidden border border-[#e5e7eb]">
              {["Before Meal", "After Meal"].map((m) => (
                <button
                  key={m}
                  onClick={() => upd("meal_time", m)}
                  className={`flex-1 py-3.5 text-base font-medium cursor-pointer border-none transition-colors ${form.meal_time === m ? "bg-[#d4537e] text-white" : "bg-white text-[#9ca3af]"}`}
                >
                  {m}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="px-7 pb-7 pt-4 flex-shrink-0">
          <button
            onClick={() => onAdd(form)}
            disabled={!form.name.trim() || loading}
            className="w-full bg-[#d4537e] hover:bg-[#993556] text-white text-base font-semibold py-4 rounded-2xl cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? "Adding..." : "Add Medicine"}
          </button>
        </div>
      </div>
    </div>
  );
}

export default function SavedMedicinesPage({
  onClose,
}: {
  onClose: () => void;
}) {
  const {
    masterData,
    fetchMasterData,
    loading: masterLoading,
  } = useMasterDataStore();
  const { addMedicine, removeMedicine, loading } = useMedicineStore();

  const [activeType, setActiveType] = useState("");
  const [addOpen, setAddOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Medicine | null>(null);
  const categoryOrder: string[] = (() => {
    try {
      const saved = localStorage.getItem("category-order");
      return saved ? JSON.parse(saved) : DEFAULT_CATEGORIES;
    } catch {
      return DEFAULT_CATEGORIES;
    }
  })();

  useEffect(() => {
    if (!masterData) fetchMasterData();
  }, []);

  const medicines: Medicine[] = masterData?.medicines || [];
  const frequencies = masterData?.dose_frequencies || [];

  // ── Tabs are STATIC: every category always shows up, whether or not it
  // has saved medicines yet. Data-less tabs simply render the empty
  // state below instead of disappearing. ──
  const types = categoryOrder;

  useEffect(() => {
    if (types.length && !types.includes(activeType)) setActiveType(types[0]);
  }, [medicines.length]);

  const filtered = medicines.filter((m) => m.type === activeType);

  const handleAdd = async (payload: AddMedicinePayload) => {
    const ok = await addMedicine(payload);
    if (ok) setAddOpen(false);
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    const ok = await removeMedicine(deleteTarget.id);
    if (ok) setDeleteTarget(null);
  };

  return (
    // ── h-full, NOT min-h-screen ──
    // This component is rendered inside a fixed-height parent (a drawer /
    // modal panel that already has its own header + close button). Using
    // min-h-screen made it taller than that panel, forcing the *whole*
    // panel to scroll — which cut the "Add new medicine" button off at
    // the bottom and produced the double scrollbar you saw.
    //
    // With h-full this fills exactly the space the parent gives it.
    // Only the middle list/empty-state region scrolls (overflow-y-auto);
    // the tab bar stays pinned at the top and "Add new medicine" stays
    // pinned at the bottom, always visible.
    <div className="h-full bg-[#f5f5f7] flex flex-col overflow-hidden">
      <PageHeader
        icon={<Pill size={20} />}
        title="Saved medicines"
        subtitle="View, edit, or delete previously saved medicines"
                onClose={onClose}

      />

      <div className="flex-1 flex flex-col w-full max-w-[680px] mx-auto min-h-0">
        {masterLoading && !masterData ? (
          <p className="text-sm text-[#9ca3af] text-center py-10">
            Loading...
          </p>
        ) : types.length === 0 ? (
          <p className="text-sm text-[#9ca3af] text-center py-10">
            No medicine categories configured
          </p>
        ) : (
          <>
            {/* Tabs — pinned at the top, never scroll away */}
            <div className="flex gap-1 border-b border-[#e5e7eb] px-7 overflow-x-auto overflow-y-hidden bg-white flex-shrink-0">
              {types.map((t) => (
                <button
                  key={t}
                  onClick={() => setActiveType(t)}
                  className={`px-4 py-3.5 text-sm font-medium whitespace-nowrap border-b-2 -mb-px cursor-pointer transition-colors bg-transparent ${activeType === t ? "border-[#d4537e] text-[#d4537e]" : "border-transparent text-[#9ca3af] hover:text-[#374151]"}`}
                >
                  {t}
                </button>
              ))}
            </div>

            {/* Content — the ONLY scrollable region */}
            <div className="flex-1 min-h-0 overflow-y-auto px-7">
              {filtered.length === 0 ? (
                <div className="h-full flex items-center justify-center">
                  <EmptyTypeState type={activeType} />
                </div>
              ) : (
                <div className="py-6 flex flex-col gap-3">
                  {filtered.map((med) => (
                    <div
                      key={med.id}
                      className="flex items-center justify-between gap-4 bg-white border border-[#e5e7eb] rounded-xl px-4 py-3.5"
                    >
                      <div className="min-w-0">
                        <p className="text-base font-semibold text-[#111111]">
                          {med.name}
                        </p>
                        <p className="text-sm text-[#9ca3af] mt-0.5">
                          {[med.dose, med.dose_frequency, med.meal_time]
                            .filter(Boolean)
                            .join("  •  ")}
                        </p>
                      </div>
                      <button
                        onClick={() => setDeleteTarget(med)}
                        className="w-9 h-9 rounded-lg flex items-center justify-center text-[#ef4444] bg-[#fff1f1] hover:bg-[#ffe1e1] border-none cursor-pointer flex-shrink-0 transition-colors"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </>
        )}

        {/* Add new medicine — pinned at the bottom, always visible */}
        <div className="px-7 py-5 flex-shrink-0 bg-[#f5f5f7]">
          <button
            onClick={() => setAddOpen(true)}
            className="w-full flex items-center gap-4 bg-white border border-[#e5e7eb] rounded-2xl px-6 py-4 cursor-pointer hover:bg-[#fafafa] transition-colors"
          >
            <span className="w-10 h-10 rounded-xl bg-[#fceef3] text-[#d4537e] flex items-center justify-center flex-shrink-0">
              <Plus size={20} />
            </span>
            <div className="text-left">
              <p className="text-base font-medium text-[#111111]">
                Add new medicine
              </p>
              <p className="text-sm text-[#9ca3af]">
                Not listed? Add it to your medicines
              </p>
            </div>
          </button>
        </div>
      </div>

      <AddMedicineModal
        open={addOpen}
        onClose={() => setAddOpen(false)}
        frequencies={frequencies}
        onAdd={handleAdd}
        loading={loading}
        defaultType={activeType}
      />
      <ConfirmDeleteModal
        open={!!deleteTarget}
        title="Delete Medicine?"
        description={`Are you sure you want to remove ${deleteTarget?.name}?`}
        onCancel={() => setDeleteTarget(null)}
        onConfirm={handleDelete}
        loading={loading}
      />
    </div>
  );
}