"use client";
import { useEffect, useState } from "react";
import { Clock, Pencil, Trash2, Plus, X } from "lucide-react";
import { useMasterDataStore } from "@/app/store/masterDataStore";
import { DoseFrequency } from "@/app/types/masterData";
import PageHeader from "@/components/modals/ui/PageHeader";
import { useDoseFrequencyStore } from "@/app/store/doseFrequencyStore";
import {
  AddDoseFrequencyPayload,
  UpdateDoseFrequencyPayload,
} from "@/app/types/medicalData";
import ConfirmDeleteModal from "@/components/modals/ui/ConfirmDeleteModal";
import toast from "react-hot-toast";

// Extracts a readable message from various possible error shapes
// (axios error response, plain object with `msg`, or a thrown Error).
function getErrorMessage(err: any): string {
  return (
    err?.response?.data?.msg ||
    err?.data?.msg ||
    err?.msg ||
    err?.message ||
    "Something went wrong. Please try again."
  );
}

function DoseFrequencyModal({
  open,
  onClose,
  onSubmit,
  loading,
  initialData,
  error,
  onFormChange,
}: {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: any) => void;
  loading: boolean;
  initialData?: DoseFrequency | null;
  error?: string | null;
  onFormChange?: () => void;
}) {
  const [form, setForm] = useState({
    drLang: "",
    ptLang: "",
  });

  useEffect(() => {
    if (open) {
      setForm({
        drLang: initialData?.drLang || "",
        ptLang: initialData?.ptLang || "",
      });
    }
  }, [open, initialData]);

  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-[500px] rounded-3xl shadow-2xl">
        <div className="flex items-center justify-between px-6 py-5 border-b border-[#f3f4f6]">
          <h2 className="text-lg font-semibold text-[#d4537e]">
            {initialData ? "Edit Dose Frequency" : "Add Dose Frequency"}
          </h2>

          <button
            onClick={onClose}
            className="w-9 h-9 rounded-lg flex items-center justify-center text-[#9ca3af] hover:bg-[#f7f7f8] border-none cursor-pointer"
          >
            <X size={20} />
          </button>
        </div>

        <div className="p-6 flex flex-col gap-6">
          <div>
            <label className="block text-sm font-medium text-[#374151] mb-2">
              Frequency in Dr. Language
            </label>

            <input
              placeholder="i.e. 1-0-1"
              value={form.drLang}
              onChange={(e) => {
                setForm({
                  ...form,
                  drLang: e.target.value,
                });
                onFormChange?.();
              }}
              disabled={!!initialData}
              className={`w-full bg-[#f7f7f8] rounded-xl border outline-none px-4 py-4 text-base text-[#111111] placeholder:text-[#9ca3af] disabled:opacity-50 disabled:cursor-not-allowed ${
                error ? "border-[#ef4444]" : "border-transparent"
              }`}
            />

            {/* {error && (
              <p className="text-sm text-[#ef4444] mt-2">{error}</p>
            )} */}
          </div>

          <div>
            <label className="block text-sm font-medium text-[#374151] mb-2">
              Frequency in Patient Language
            </label>

            <input
              placeholder="i.e. Morning - Noon - Evening"
              value={form.ptLang}
              onChange={(e) =>
                setForm({
                  ...form,
                  ptLang: e.target.value,
                })
              }
              className="w-full bg-[#f7f7f8] rounded-xl border-none outline-none px-4 py-4 text-base text-[#111111] placeholder:text-[#9ca3af]"
            />
          </div>
        </div>

        <div className="px-6 pb-6">
          <button
            disabled={!form.drLang.trim() || loading}
            onClick={() =>
              initialData
                ? onSubmit({
                  id: initialData.id,
                  ...form,
                })
                : onSubmit(form)
            }
            className="w-full bg-[#d4537e] hover:bg-[#993556] text-white text-base font-semibold py-4 rounded-2xl disabled:opacity-50"
          >
            {loading ? "Saving..." : initialData ? "Update Frequency" : "Save"}
          </button>
        </div>
      </div>
    </div>
  );
}

export default function DoseFrequenciesPage({
  onClose,
}: {
  onClose: () => void;
}) {
  const { masterData, fetchMasterData, loading } = useMasterDataStore();
  const {
    addDoseFrequency,
    updateDoseFrequency,
    removeDoseFrequency,
    loading: actionLoading,
  } = useDoseFrequencyStore();
  const [addOpen, setAddOpen] = useState(false);
  const [editFrequency, setEditFrequency] = useState<DoseFrequency | null>(
    null,
  );
  const [deleteFrequency, setDeleteFrequency] = useState<DoseFrequency | null>(
    null,
  );
  const [addError, setAddError] = useState<string | null>(null);
  const [editError, setEditError] = useState<string | null>(null);

  const handleAddFrequency = async (payload: AddDoseFrequencyPayload) => {
    setAddError(null);
    try {
      const success = await addDoseFrequency(payload);

      if (success) {
        setAddOpen(false);
      } else {
        // Store returned a falsy result without throwing — show a generic
        // message since no error details are available in this case.
        setAddError("Dose frequency with this drLang already exists");
        toast.error("Dose frequency with this drLang already exists");
      }
    } catch (err) {
      const message = getErrorMessage(err);
      setAddError(message);
      toast.error(message);
    }
  };

  const handleUpdateFrequency = async (payload: UpdateDoseFrequencyPayload) => {
    setEditError(null);
    try {
      const success = await updateDoseFrequency(payload);

      if (success) {
        setEditFrequency(null);
      } else {
        setEditError("Dose frequency with this drLang already exists");
        toast.error("Dose frequency with this drLang already exists");
      }
    } catch (err) {
      const message = getErrorMessage(err);
      setEditError(message);
      toast.error(message);
    }
  };

  const handleDeleteFrequency = async () => {
    if (!deleteFrequency) return;

    try {
      const success = await removeDoseFrequency(deleteFrequency.id);

      if (success) {
        setDeleteFrequency(null);
      }
    } catch (err) {
      toast.error(getErrorMessage(err));
    }
  };

  useEffect(() => {
    if (!masterData) fetchMasterData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

  if (loading && !masterData) {
    return (
      <div className="bg-[#f7f7f8]">
        <PageHeader
          icon={<Clock size={20} />}
          title="Saved dose frequencies"
          subtitle="View, edit, or delete previously saved dose frequencies"

        />
        <main className="max-w-[680px] mx-auto p-7">
          <p className="text-sm text-[#9ca3af] text-center py-10">Loading...</p>
        </main>
      </div>
    );
  }

  return (
    <div className="bg-[#f7f7f8]">
      <PageHeader
        icon={<Clock size={20} />}
        title="Saved dose frequencies"
        subtitle="View, edit, or delete previously saved dose frequencies"
        onClose={onClose}

      />

      <div className="min-h-[calc(100vh-140px)] flex flex-col px-7 pt-7 pb-7 max-w-[680px] mx-auto">
        <div className="flex-1">
          {frequencies.length === 0 ? (
            <p className="text-sm text-[#9ca3af] text-center py-10">
              No dose frequencies saved yet
            </p>
          ) : (
            <div className="flex flex-col gap-3">
              {frequencies.map((f) => (
                <div
                  key={f.id}
                  className="flex items-center justify-between gap-4 bg-white border border-[#e5e7eb] rounded-2xl px-5 py-4"
                >
                  <div className="min-w-0">
                    <p className="text-base font-semibold text-[#111111]">
                      {f.drLang}
                    </p>
                    {f.ptLang && (
                      <p className="text-sm text-[#9ca3af] mt-0.5">
                        {f.ptLang}
                      </p>
                    )}
                  </div>
                  <div className="flex items-center gap-2 flex-shrink-0">
                    <button
                      className="w-9 h-9 rounded-lg flex items-center justify-center text-[#d4537e] bg-[#fceef3] hover:bg-[#f8d9e4] border-none cursor-pointer transition-colors"
                      onClick={() => {
                        setEditError(null);
                        setEditFrequency(f);
                      }}
                    >
                      <Pencil size={16} />
                    </button>
                    <button
                      className="w-9 h-9 rounded-lg flex items-center justify-center text-[#ef4444] bg-[#fff1f1] hover:bg-[#ffe1e1] border-none cursor-pointer transition-colors"
                      onClick={() => setDeleteFrequency(f)} // TODO: wire delete API
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
        <button
          className="w-full flex items-center gap-4 bg-white border border-[#e5e7eb] rounded-2xl px-6 py-4 mt-6 cursor-pointer hover:bg-[#f7f7f8] transition-colors"
          onClick={() => {
            setAddError(null);
            setAddOpen(true);
          }}
        >
          <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 dose frequency
            </p>
            <p className="text-sm text-[#9ca3af]">
              Not listed above? Add your own
            </p>
          </div>
        </button>
      </div>
      <DoseFrequencyModal
        open={addOpen}
        onClose={() => {
          setAddError(null);
          setAddOpen(false);
        }}
        onSubmit={handleAddFrequency}
        loading={actionLoading}
        error={addError}
        onFormChange={() => setAddError(null)}
      />

      <DoseFrequencyModal
        open={!!editFrequency}
        initialData={editFrequency}
        onClose={() => {
          setEditError(null);
          setEditFrequency(null);
        }}
        onSubmit={handleUpdateFrequency}
        loading={actionLoading}
        error={editError}
        onFormChange={() => setEditError(null)}
      />

      <ConfirmDeleteModal
        open={!!deleteFrequency}
        title="Delete Dose Frequency?"
        description={`Are you sure you want to remove ${deleteFrequency?.drLang}?`}
        onCancel={() => setDeleteFrequency(null)}
        onConfirm={handleDeleteFrequency}
        loading={actionLoading}
      />
    </div>
  );
}