"use client";

import React, { useEffect, useState } from "react";

import { X } from "lucide-react";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import CustomButton from "@/components/customs/custom-button";

import FormCustom from "@/components/utils/FormCustom";

import InputForm from "@/components/utils/FormCustom/components/InputForm";

import TextArea from "@/components/utils/FormCustom/components/TextArea";

import { QUERY_KEY } from "@/constant/config/enum";

import { httpRequest } from "@/services";

import consultationServices, {
  ConsultationDetail,
} from "@/services/consultationServices";
import { ContextFormCustom } from "@/components/utils/FormCustom/contexts";

interface PopupUpdateConsultationProps {
  id: string;
  onClose: () => void;
}

interface IUpdateConsul {
  chiefComplaint: string;
  symptomsText: string;
  vitalSigns: string;
  diagnosis: string;
  treatmentPlan: string;
  doctorNotes: string;
}

const defaultForm: IUpdateConsul = {
  chiefComplaint: "",
  symptomsText: "",
  vitalSigns: "",
  diagnosis: "",
  treatmentPlan: "",
  doctorNotes: "",
};

const PopupUpdateConsultation = ({
  id,
  onClose,
}: PopupUpdateConsultationProps) => {
  const queryClient = useQueryClient();
  const [form, setForm] = useState<IUpdateConsul>(defaultForm);

  const consulDetailQuery = useQuery<ConsultationDetail>({
    queryKey: [QUERY_KEY.chi_tiet_phien_kham, id],
    enabled: !!id,
    queryFn: async () => {
      const res = await httpRequest<ConsultationDetail>({
        showMessageFailed: true,
        http: consultationServices.detailConsultations(id),
      });
      return (
        res || {
          id: "",
          patientId: "",
          sessionCode: "",
          visitDate: "",
          status: 1,
          chiefComplaint: null,
          symptomsText: null,
          vitalSigns: null,
          diagnosis: null,
          treatmentPlan: null,
          doctorNotes: null,
          createdBy: "",
          isDeleted: false,
        }
      );
    },
  });

  useEffect(() => {
    const consul = consulDetailQuery.data;

    if (!consul) return;

    setForm({
      chiefComplaint: consul.chiefComplaint || "",
      symptomsText: consul.symptomsText || "",
      vitalSigns: consul.vitalSigns || "",
      diagnosis: consul.diagnosis || "",
      treatmentPlan: consul.treatmentPlan || "",
      doctorNotes: consul.doctorNotes || "",
    });
  }, [consulDetailQuery.data]);

  /* =========================
      SUBMIT
  ========================= */

  const updateConsultationMutation = useMutation({
    mutationFn: async () => {
      return httpRequest({
        showMessageFailed: true,
        showMessageSuccess: true,
        msgSuccess: "Cập nhật phiên khám thành công!",
        http: consultationServices.putConsultations(id, {
          chiefComplaint: form.chiefComplaint,
          symptomsText: form.symptomsText,
          vitalSigns: form.vitalSigns,
          diagnosis: form.diagnosis,
          treatmentPlan: form.treatmentPlan,
          doctorNotes: form.doctorNotes,
        }),
      });
    },

    onSuccess(data) {
      if (!data) return;

      queryClient.invalidateQueries({
        queryKey: [QUERY_KEY.table_list_consultation],
      });

      queryClient.invalidateQueries({
        queryKey: [QUERY_KEY.chi_tiet_phien_kham, id],
      });

      onClose();
    },
  });

  const handleSubmit = () => {
    updateConsultationMutation.mutate();
  };

  if (consulDetailQuery.isLoading) {
    return (
      <div className="flex items-center justify-center p-10">
        Đang tải dữ liệu...
      </div>
    );
  }

  return (
    <FormCustom form={form} setForm={setForm} onSubmit={handleSubmit}>
      <div
        className="
          relative
          h-[680px]
          w-[640px]
          max-w-[95vw]
          rounded-3xl
          bg-white
          shadow-xl
          flex
          flex-col
          overflow-hidden
        "
      >
        {/* CLOSE */}
        <button
          type="button"
          onClick={onClose}
          className="
            absolute
            right-5
            top-5
            z-10
            text-gray-400
            transition
            hover:text-gray-600
          "
        >
          <X size={22} />
        </button>

        {/* HEADER */}
        <div
          className="
            shrink-0
            border-b
            px-7
            py-5
            bg-white
          "
        >
          <h2 className="text-[30px] font-semibold text-[#111827]">
            Chỉnh sửa phiên khám
          </h2>
        </div>

        {/* BODY */}
        <div className="flex-1 overflow-y-auto px-7 py-5">
          <div className="space-y-5">
            <InputForm
              label="Lý do khám"
              name="chiefComplaint"
              type="text"
              value={form.chiefComplaint}
              placeholder="Nhập lý do khám"
            />

            <TextArea
              label="Triệu chứng"
              name="symptomsText"
              placeholder="Nhập triệu chứng"
              value={form.symptomsText}
            />

            <TextArea
              label="Dấu hiệu sinh tồn"
              name="vitalSigns"
              placeholder="Nhập dấu hiệu sinh tồn"
              value={form.vitalSigns}
            />

            <TextArea
              label="Chẩn đoán"
              name="diagnosis"
              placeholder="Nhập chẩn đoán"
              value={form.diagnosis}
            />

            <TextArea
              label="Kế hoạch điều trị"
              name="treatmentPlan"
              placeholder="Nhập kế hoạch điều trị"
              value={form.treatmentPlan}
            />

            <TextArea
              label="Ghi chú bác sĩ"
              name="doctorNotes"
              placeholder="Nhập ghi chú"
              value={form.doctorNotes}
            />
          </div>
        </div>

        {/* FOOTER */}
        <div
          className="
            shrink-0
            border-t
            bg-white
            px-7
            py-5
            flex
            items-center
            justify-end
            gap-3
          "
        >
          <CustomButton variant="grey" rounded="md" onClick={onClose}>
            Hủy bỏ
          </CustomButton>

          <ContextFormCustom.Consumer>
            {({ isDone }) => (
              <CustomButton
                disabled={!isDone || updateConsultationMutation.isPending}
                variant="midnightBlue"
                rounded="md"
                type="submit"
              >
                {updateConsultationMutation.isPending
                  ? "Đang cập nhật..."
                  : "Cập nhật"}
              </CustomButton>
            )}
          </ContextFormCustom.Consumer>
        </div>
      </div>
    </FormCustom>
  );
};

export default PopupUpdateConsultation;
