"use client";

import { QUERY_KEY } from "@/constant/config/enum";
import { httpRequest } from "@/services";
import prescriptionServices, {
  PrescriptionDetail,
} from "@/services/prescriptionServices";
import consultationServices, {
  ConsultationItem,
} from "@/services/consultationServices";
import { useQuery } from "@tanstack/react-query";
import Image from "next/image";
import { useParams, useRouter } from "next/navigation";
import React, { useState } from "react";
import CustomPopup from "@/components/customs/custom-popup";
import { ArrowLeft } from "lucide-react";

const DetailPrescription = () => {
  const router = useRouter();
  const params = useParams();
  const PrescriptionId = params?.id as string;
  const [openImagePreview, setOpenImagePreview] = useState(false);

  const prescriptionDetailQuery = useQuery<PrescriptionDetail>({
    queryKey: [QUERY_KEY.chi_tiet_don_thuoc, PrescriptionId],

    enabled: !!PrescriptionId,

    queryFn: async () => {
      const res = await httpRequest<PrescriptionDetail>({
        showMessageFailed: true,

        http: prescriptionServices.detailPrescription(PrescriptionId),
      });

      return (
        res || {
          id: "",
          examinationSessionSpecialtyId: "",
          prescriptionCode: "",
          prescriptionImg: null,
          notes: "",
          createdBy: "",
          items: [],
        }
      );
    },
  });

  const data = prescriptionDetailQuery.data;

  const specialtyListQuery = useQuery<ConsultationItem[]>({
    queryKey: [QUERY_KEY.examination_specialty_list],
    enabled: !!data?.examinationSessionSpecialtyId,
    queryFn: async () => {
      const res = await httpRequest<{
        items: ConsultationItem[];
      }>({
        showMessageFailed: false,
        http: consultationServices.getConsultations({ PageSize: 1000 }),
      });

      return res?.items || [];
    },
  });

  const specialtyName = React.useMemo(() => {
    const specialtyId = data?.examinationSessionSpecialtyId;
    if (!specialtyId) return "";

    const items = specialtyListQuery.data || [];
    for (const session of items) {
      const found = session.specialtyClinics?.find((s) => s.id === specialtyId);
      if (found) return found.specialtyName || "";
    }

    return "";
  }, [data?.examinationSessionSpecialtyId, specialtyListQuery.data]);

  return (
    <div className="p-6 bg-white rounded-lg shadow">
      <div
        className="flex items-center gap-1 cursor-pointer"
        onClick={() => router.back()}
      >
        <ArrowLeft />

        <h2 className="text-xl font-semibold text-[#111827]">
          Chi tiết đơn thuốc
        </h2>
      </div>

      {/* LOADING */}
      {prescriptionDetailQuery.isLoading && <p>Đang tải...</p>}

      {/* ERROR */}
      {prescriptionDetailQuery.isError && (
        <p className="text-red-500">Lỗi tải dữ liệu</p>
      )}

      {/* CONTENT */}
      {data && (
        <div className="space-y-4">
          <div>
            <strong>Mã đơn thuốc:</strong> {data.prescriptionCode}
          </div>

          <div>
            <strong>Chuyên khoa:</strong>{" "}
            {specialtyName || data.examinationSessionSpecialtyId || "---"}
          </div>

          <div>
            <strong>Ghi chú:</strong> {data.notes || "---"}
          </div>

          {/* IMAGE */}
          <div>
            <strong>Ảnh đơn thuốc:</strong>
            <div className="mt-2">
              {data.prescriptionImg ? (
                <>
                  <Image
                    src={`${data.prescriptionImg}`}
                    alt="prescription"
                    width={140}
                    height={140}
                    className="h-10 w-10 rounded object-cover cursor-pointer hover:opacity-80 transition-opacity"
                    onClick={() => setOpenImagePreview(true)}
                    unoptimized
                  />

                  {/* IMAGE PREVIEW POPUP */}
                  <CustomPopup
                    open={openImagePreview}
                    onClose={() => setOpenImagePreview(false)}
                  >
                    <div className="relative rounded-lg p-4 max-w-[90vw] max-h-[90vh] flex items-center justify-center">
                      <Image
                        src={`${process.env.NEXT_PUBLIC_IMAGE}${data.prescriptionImg}`}
                        alt="prescription preview"
                        width={600}
                        height={600}
                        className="max-w-full max-h-full object-contain"
                        unoptimized
                      />
                    </div>
                  </CustomPopup>
                </>
              ) : (
                <span className="text-gray-400">Không có ảnh</span>
              )}
            </div>
          </div>

          {/* ITEMS */}
          <div>
            <strong>Danh sách thuốc:</strong>

            <div className="mt-2 space-y-2">
              {data.items?.length ? (
                data.items.map((item, index) => (
                  <div key={item.id || index} className="p-3 border rounded">
                    <p>
                      <b>Tên thuốc:</b> {item.medicineName}
                    </p>
                    <p>
                      <b>Liều lượng:</b> {item.dosage}
                    </p>
                    <p>
                      <b>Tần suất:</b> {item.frequency}
                    </p>
                    <p>
                      <b>Thời gian:</b> {item.duration}
                    </p>
                    <p>
                      <b>Hướng dẫn:</b> {item.instructions}
                    </p>
                  </div>
                ))
              ) : (
                <p className="text-gray-400">Không có thuốc</p>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default DetailPrescription;
