"use client";

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 { ContextFormCustom } from "@/components/utils/FormCustom/contexts";
import { QUERY_KEY, TYPE_GENDER } from "@/constant/config/enum";
import { X } from "lucide-react";
import React, { useState } from "react";

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

import { httpRequest } from "@/services";

import patientServices from "@/services/patientServices";

export interface ICreatePatient {
  identificationNumber: string;
  fullName: string;
  dateOfBirth: string;
  gender: string;
  phone: string;
  email: string;
  address: string;
}

export interface PropsPopupCreatePatient {
  onClose: () => void;
}

/* QUERY KEY */
// export const QUERY_KEY = {
//   table_list_patient: "table_list_patient",
// };

const PopupCreatePatient = ({ onClose }: PropsPopupCreatePatient) => {
  const queryClient = useQueryClient();

  const [form, setForm] = useState<ICreatePatient>({
    identificationNumber: "",
    fullName: "",
    dateOfBirth: "",
    gender: "",
    phone: "",
    email: "",
    address: "",
  });

  const createPatientMutation = useMutation({
    mutationFn: async () => {
      return await httpRequest({
        showMessageFailed: true,
        showMessageSuccess: true,
        msgSuccess: "Tạo bệnh nhân thành công!",

        http: patientServices.createPatient({
          identificationNumber: form.identificationNumber,
          fullName: form.fullName,
          dateOfBirth: form.dateOfBirth,
          gender: form.gender,
          phone: form.phone,
          email: form.email,
          address: form.address,
        }),
      });
    },

    onSuccess() {
      /* REFRESH LIST */
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEY.table_list_patient],
      });

      onClose();
    },
  });

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

  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]">
            Thêm bệnh nhân
          </h2>
        </div>

        {/* BODY */}
        <div
          className="
            flex-1
            overflow-y-auto
            px-7
            py-5
          "
        >
          <div className="space-y-5">
            <InputForm
              label={
                <span>
                  Mã định danh
                  <span className="text-red-500"> *</span>
                </span>
              }
              placeholder="Mã định danh"
              name="identificationNumber"
              type="text"
              value={form.identificationNumber}
              isRequired
            />

            <InputForm
              label={
                <span>
                  Tên bệnh nhân
                  <span className="text-red-500"> *</span>
                </span>
              }
              placeholder="Tên bệnh nhân"
              name="fullName"
              type="text"
              value={form.fullName}
              isRequired
            />

            <div className="space-y-3">
              <label className="block text-sm font-medium text-gray-700">
                Giới tính <span className="text-red-500">*</span>
              </label>

              <div className="flex items-center gap-6">
                {/* NAM */}
                <label className="flex cursor-pointer select-none items-center gap-2.5">
                  <input
                    id="male"
                    type="radio"
                    name="gender"
                    value={form.gender}
                    checked={form.gender === TYPE_GENDER.MALE}
                    onChange={() =>
                      setForm((prev: any) => ({
                        ...prev,
                        gender: TYPE_GENDER.MALE,
                      }))
                    }
                    className="h-5 w-5 cursor-pointer"
                  />

                  <span className="cursor-pointer text-sm font-medium text-gray-700">
                    Nam
                  </span>
                </label>

                {/* NỮ */}
                <label className="flex cursor-pointer select-none items-center gap-2.5">
                  <input
                    id="female"
                    type="radio"
                    name="gender"
                    value={form.gender}
                    checked={form.gender === TYPE_GENDER.FEMALE}
                    onChange={() =>
                      setForm((prev: any) => ({
                        ...prev,
                        gender: TYPE_GENDER.FEMALE,
                      }))
                    }
                    className="h-5 w-5 cursor-pointer"
                  />

                  <span className="cursor-pointer text-sm font-medium text-gray-700">
                    Nữ
                  </span>
                </label>
              </div>
            </div>

            <InputForm
              label={
                <span>
                  Ngày sinh
                  <span className="text-red-500"> *</span>
                </span>
              }
              placeholder="Ngày sinh"
              name="dateOfBirth"
              type="Date"
              value={form.dateOfBirth}
              isRequired
            />

            <InputForm
              label={
                <span>
                  Số điện thoại
                  <span className="text-red-500"> *</span>
                </span>
              }
              placeholder="Số điện thoại"
              name="phone"
              type="text"
              value={form.phone}
              isRequired
            />

            <InputForm
              label={
                <span>
                  Email
                  <span className="text-red-500"> *</span>
                </span>
              }
              placeholder="Email"
              name="email"
              type="text"
              value={form.email}
              isRequired
            />

            <TextArea
              name="address"
              placeholder="Địa chỉ"
              label="Địa chỉ"
              isBlur
              max={5000}
            />
          </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 || createPatientMutation.isPending}
                variant="midnightBlue"
                rounded="md"
                type="submit"
              >
                {createPatientMutation.isPending ? "Đang tạo..." : "Tạo"}
              </CustomButton>
            )}
          </ContextFormCustom.Consumer>
        </div>
      </div>
    </FormCustom>
  );
};

export default PopupCreatePatient;
