"use client";

import CustomButton from "@/components/customs/custom-button";
import CustomDialog from "@/components/customs/custom-dialog";
import CustomPopup from "@/components/customs/custom-popup";
import DataWrapper from "@/components/customs/DataWrapper";
import Search from "@/components/customs/custom-search";
import StateActive from "@/components/customs/StateActive";
import Table from "@/components/customs/custom-table";

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

import { httpRequest } from "@/services";

import consultationServices, {
  ConsultationItem,
  ConsultationResponse,
} from "@/services/consultationServices";

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

import Link from "next/link";

import { Pencil, ClipboardPlus } from "lucide-react";

import { usePathname, useRouter, useSearchParams } from "next/navigation";

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

import { PATH } from "@/constant/config";
import Pagination from "@/components/customs/custom-pagination";

const MainPageConsultation = () => {
  const router = useRouter();

  const pathname = usePathname();

  const searchParams = useSearchParams();

  const queryClient = useQueryClient();

  /* =========================
        QUERY PARAMS
  ========================= */

  const _page = searchParams.get("_page");

  const _pageSize = searchParams.get("_pageSize");

  const _keyword = searchParams.get("_keyword");

  /* =========================
        STATE
  ========================= */

  const [selectedConsultationId, setSelectedConsultationId] =
    useState<string>("");

  const [openCancelDialog, setOpenCancelDialog] = useState(false);

  const [openCompleteDialog, setOpenCompleteDialog] = useState(false);

  /* =========================
        GET LIST
  ========================= */

  const consultationQuery = useQuery<ConsultationResponse>({
    queryKey: [QUERY_KEY.table_list_consultation, _page, _pageSize, _keyword],

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

        http: consultationServices.getConsultations({
          Page: Number(_page || 1),

          PageSize: Number(_pageSize || 10),

          Search: _keyword || "",

          SortBy: "id",

          Desc: true,
        }),
      });

      return (
        res || {
          items: [],
          page: 1,
          pageSize: 10,
          total: 0,
          totalPages: 0,
        }
      );
    },
  });

  /* =========================
        DATA
  ========================= */

  const consultationData = useMemo(() => {
    return consultationQuery.data?.items || [];
  }, [consultationQuery.data]);

  /* =========================
        UPDATE QUERY
  ========================= */

  const page = _page ? Number(_page) : 1;
  const pageSize = _pageSize ? Number(_pageSize) : 10;

  const updateQuery = (key: string, value: string | number) => {
    const params = new URLSearchParams(searchParams.toString());

    if (!value || value === "" || (key === "_page" && value === 1)) {
      params.delete(key);
    } else {
      params.set(key, String(value));
    }

    if (key === "_pageSize") {
      params.delete("_page");
    }

    const queryString = params.toString();

    router.push(queryString ? `?${queryString}` : pathname);
  };

  /* =========================
        CLOSE POPUP
  ========================= */

  // const handleClosePopup = () => {
  //   const params = new URLSearchParams(searchParams.toString());

  //   params.delete("_create");

  //   params.delete("_update");

  //   const queryString = params.toString();

  //   router.push(queryString ? `?${queryString}` : pathname);
  // };

  /* =========================
        DIALOG
  ========================= */

  const handleOpenCancel = (item: ConsultationItem) => {
    setSelectedConsultationId(item.id);

    setOpenCancelDialog(true);
  };

  const handleOpenComplete = (item: ConsultationItem) => {
    setSelectedConsultationId(item.id);

    setOpenCompleteDialog(true);
  };

  const handleCloseDialog = () => {
    setOpenCancelDialog(false);

    setOpenCompleteDialog(false);
  };

  /* =========================
        CANCEL
  ========================= */

  const cancelConsultationMutation = useMutation({
    mutationFn: async () => {
      return await httpRequest({
        showMessageFailed: true,

        showMessageSuccess: true,

        msgSuccess: "Hủy phiên khám thành công!",

        http: consultationServices.cancelConsultations(selectedConsultationId),
      });
    },

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

      handleCloseDialog();
    },
  });

  /* =========================
        COMPLETE
  ========================= */

  const completeConsultationMutation = useMutation({
    mutationFn: async () => {
      return await httpRequest({
        showMessageFailed: true,

        showMessageSuccess: true,

        msgSuccess: "Hoàn thành phiên khám thành công!",

        http: consultationServices.completeConsultations(
          selectedConsultationId,
        ),
      });
    },

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

      handleCloseDialog();
    },
  });

  /* =========================
        CONFIRM
  ========================= */

  const handleConfirmCancel = () => {
    cancelConsultationMutation.mutate();
  };

  const handleConfirmComplete = () => {
    completeConsultationMutation.mutate();
  };

  return (
    <div className="flex flex-col gap-4 rounded-lg bg-white p-6 shadow">
      {/* HEADER */}
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-semibold text-black">Phiên khám</h2>

        <CustomButton
          variant="midnightBlue"
          fullWidth={false}
          icon={<ClipboardPlus />}
          // onClick={handleOpenCreate}
          href="/consultation/create"
        >
          Tạo phiên khám
        </CustomButton>
      </div>

      {/* SEARCH */}
      <div className="flex items-center justify-between gap-4">
        <div className="w-full md:min-w-[400px]">
          <Search
            keyword={_keyword ?? ""}
            setKeyword={(value) => updateQuery("_keyword", value)}
            placeholder="Tìm kiếm phiên khám..."
          />
        </div>
      </div>

      {/* TABLE */}
      <DataWrapper
        data={consultationData}
        loading={consultationQuery.isLoading}
        title="Không có dữ liệu"
        note="Vui lòng thử lại sau"
      >
        <Table
          rowKey={(item) => item.id}
          data={consultationData}
          column={[
            {
              fixedLeft: true,

              title: "ID PHIÊN KHÁM",

              render: (item: ConsultationItem) => (
                <Link
                  href={`/consultation/${item.id}`}
                  className="text-blue-500 hover:underline"
                >
                  {item.id}
                </Link>
              ),
            },
            {
              title: "TÊN BỆNH NHÂN",

              render: (item: ConsultationItem) => (
                <span>{item.patientName}</span>
              ),
            },

            {
              title: "MÃ PHIÊN KHÁM",

              render: (item: ConsultationItem) => (
                <span>{item.sessionCode}</span>
              ),
            },

            {
              title: "NGÀY KHÁM",

              render: (item: ConsultationItem) => <span>{item.visitDate}</span>,
            },

            {
              title: "DẤU HIỆU",

              render: (item: ConsultationItem) => (
                <span>{item.symptomsText || "---"}</span>
              ),
            },

            {
              title: "CHUẨN ĐOÁN",

              render: (item: ConsultationItem) => (
                <span>{item.diagnosis || "---"}</span>
              ),
            },

            {
              title: "KẾ HOẠCH ĐIỀU TRỊ",

              render: (item: ConsultationItem) => (
                <span>{item.treatmentPlan || "---"}</span>
              ),
            },

            {
              title: "GHI CHÚ BÁC SĨ",

              render: (item: ConsultationItem) => (
                <span>{item.doctorNotes || "---"}</span>
              ),
            },

            {
              title: "TRẠNG THÁI",

              render: (item: ConsultationItem) => (
                <StateActive
                  stateActive={item.status}
                  listState={[
                    {
                      state: TYPE_STATUS.Draft,
                      text: "Đang chờ",
                      textColor: "#000",
                      backgroundColor: "#FFE4C4",
                    },

                    {
                      state: TYPE_STATUS.InProgress,
                      text: "Đang thực hiện",
                      textColor: "#000",
                      backgroundColor: "#ff3300",
                    },

                    {
                      state: TYPE_STATUS.Completed,
                      text: "Hoàn thành",
                      textColor: "#000",
                      backgroundColor: "#3d69eb",
                    },
                    {
                      state: TYPE_STATUS.Cancelled,
                      text: "Đã hủy",
                      textColor: "#000",
                      backgroundColor: "#cccc",
                    },
                  ]}
                />
              ),
            },

            {
              fixedRight: true,

              title: "ACTION",

              render: (item: ConsultationItem) => {
                const isCancelled = item.status === TYPE_STATUS.Cancelled;

                const isCompleted = item.status === TYPE_STATUS.Completed;

                const isDisabled = isCancelled || isCompleted;

                return (
                  <div className="flex items-center gap-2">
                    {/* UPDATE */}
                    <CustomButton
                      size="sm"
                      disabled={isDisabled}
                      icon={<Pencil className="text-blue-400" />}
                      href={`/consultation/update?_id=${item?.id}`}
                    />

                    {/* CANCEL */}
                    <CustomButton
                      size="sm"
                      variant="red"
                      disabled={isDisabled}
                      onClick={() => handleOpenCancel(item)}
                    >
                      Hủy
                    </CustomButton>

                    {/* COMPLETE */}
                    <CustomButton
                      size="sm"
                      variant="green"
                      disabled={isDisabled}
                      onClick={() => handleOpenComplete(item)}
                    >
                      Hoàn thành
                    </CustomButton>
                  </div>
                );
              },
            },
          ]}
        />
      </DataWrapper>
      <Pagination
        total={consultationData.length}
        page={page}
        pageSize={pageSize}
        onSetPage={(value) => updateQuery("_page", value)}
        onSetPageSize={(value) => updateQuery("_pageSize", value)}
        dependencies={[_pageSize, _keyword]}
      />

      {/* CANCEL DIALOG */}
      <CustomDialog
        open={openCancelDialog}
        title="Hủy phiên khám"
        note="Bạn có chắc chắn muốn hủy phiên khám này không?"
        type="error"
        onClose={handleCloseDialog}
        onSubmit={handleConfirmCancel}
        titleCancel="Đóng"
        titleSubmit="Xác nhận"
      />

      {/* COMPLETE DIALOG */}
      <CustomDialog
        open={openCompleteDialog}
        title="Hoàn thành phiên khám"
        note="Bạn có chắc chắn muốn hoàn thành phiên khám này không?"
        type="success"
        onClose={handleCloseDialog}
        onSubmit={handleConfirmComplete}
        titleCancel="Đóng"
        titleSubmit="Xác nhận"
      />
    </div>
  );
};

export default MainPageConsultation;
