"use client";

import React, { useMemo, useState } from "react";
import moment from "moment";
import { useQuery } from "@tanstack/react-query";
import { Users, Stethoscope, Pill } from "lucide-react";

import Table from "@/components/customs/custom-table";
import DataWrapper from "@/components/customs/DataWrapper";

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

import { httpRequest } from "@/services";

import consultationServices, {
  ReportResponse,
} from "@/services/consultationServices";
import FilterDateRange from "@/components/utils/FilterDateRage";

const MainPageStatistical = () => {
  const [date, setDate] = useState<{
    from: Date | null;
    to: Date | null;
  } | null>(null);
  const [typeDate, setTypeDate] = useState<TYPE_DATE>(TYPE_DATE.TODAY);

  const isInvalidDate =
    !!date?.from && moment(date.from).isAfter(moment().endOf("day"));

  const reportQuery = useQuery<ReportResponse>({
    queryKey: [
      QUERY_KEY.table_list_report,
      date?.from?.toISOString(),
      date?.to?.toISOString(),
    ],

    enabled: !!date?.from && !!date?.to && !isInvalidDate,

    queryFn: async () => {
      const fromDate = moment(date?.from).format("YYYY-MM-DD");
      const toDate = moment(date?.to).format("YYYY-MM-DD");

      console.log({
        FromDate: fromDate,
        ToDate: toDate,
      });

      const res = await httpRequest<ReportResponse>({
        showMessageFailed: true,
        http: consultationServices.getConsultationsReport({
          FromDate: fromDate,
          ToDate: toDate,
        }),
      });

      return res as ReportResponse;
    },
  });

  const report = reportQuery.data;

  const reportData = useMemo(() => {
    return report?.specialtyDetails || [];
  }, [report]);

  return (
    <div className="flex flex-col gap-6">
      {/* HEADER */}
      <div className="rounded-xl bg-white p-6 shadow">
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-semibold">Thống kê phiên khám</h2>

          <FilterDateRange
            date={date}
            setDate={setDate}
            typeDate={typeDate}
            setTypeDate={setTypeDate}
          />
        </div>
      </div>

      {/* CARDS */}
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
        <div className="rounded-xl bg-white p-5 shadow">
          <div className="mb-3 flex items-center justify-between">
            <Users size={22} />
          </div>

          <p className="text-sm text-gray-500">Tổng lượt khám</p>

          <h3 className="mt-2 text-3xl font-bold">
            {report?.totalSessions || 0}
          </h3>
        </div>

        <div className="rounded-xl bg-white p-5 shadow">
          <div className="mb-3 flex items-center justify-between">
            <Stethoscope size={22} />
          </div>

          <p className="text-sm text-gray-500">Lượt khám chuyên khoa</p>

          <h3 className="mt-2 text-3xl font-bold">
            {report?.totalSpecialtySubSessions || 0}
          </h3>
        </div>

        <div className="rounded-xl bg-white p-5 shadow">
          <div className="mb-3 flex items-center justify-between">
            <Pill size={22} />
          </div>

          <p className="text-sm text-gray-500">Đơn thuốc đã cấp</p>

          <h3 className="mt-2 text-3xl font-bold">
            {report?.totalPrescriptionsIssued || 0}
          </h3>
        </div>
      </div>

      {/* BẢNG THỐNG KÊ */}
      <div className="rounded-xl bg-white p-6 shadow">
        <h3 className="mb-4 text-lg font-semibold">
          Thống kê theo chuyên khoa
        </h3>

        <DataWrapper
          data={reportData}
          loading={reportQuery.isLoading}
          title="Không có dữ liệu"
          note="Vui lòng thử lại sau"
        >
          <Table
            rowKey={(item) => item.specialtyId}
            data={reportData}
            column={[
              {
                title: "MÃ CHUYÊN KHOA",
                render: (item) => <span>{item.specialtyCode}</span>,
              },
              {
                title: "TÊN CHUYÊN KHOA",
                render: (item) => <span>{item.specialtyName}</span>,
              },
              {
                title: "SỐ CA KHÁM",
                render: (item) => (
                  <span className="font-semibold">{item.totalCases}</span>
                ),
              },
            ]}
          />
        </DataWrapper>
      </div>

      {/* BÁO CÁO TỔNG HỢP */}
      <div className="rounded-xl bg-white p-6 shadow">
        <h3 className="mb-4 text-lg font-semibold">Báo cáo tổng hợp</h3>

        <div className="space-y-3 text-[15px]">
          <p>
            Số lượt khám bệnh nhân đạo:
            <strong> {report?.totalSpecialtySubSessions || 0}</strong> lượt
            người dân được khám chuyên khoa, cụ thể như sau:
          </p>

          <ul className="list-disc space-y-2 pl-6">
            {reportData.map((item) => (
              <li key={item.specialtyId}>
                <strong>{item.specialtyName}</strong>: {item.totalCases} ca
              </li>
            ))}
          </ul>

          <p>
            Tổng số đơn thuốc đã cấp:
            <strong> {report?.totalPrescriptionsIssued || 0}</strong> đơn.
          </p>

          {/* <p>
            Số suất quà được phát:
            <strong> {report?.totalGiftPackagesIssued || 0}</strong> suất.
          </p> */}
        </div>
      </div>
    </div>
  );
};

export default MainPageStatistical;
