"use client";
import { useCallback, useState } from "react";

import styles from "@/components/administrator/PostEditor/posteditor.module.css";

import Dropdown from "../../form/Dropdown/dropdown";
import Input from "../../form/Input/input";
import Button from "@/components/ui/Button/button";
import Loader from "@/components/web/Loader/loader";

import { formatDateRange } from "@/app/library/library";
import { api } from "@/app/services/config/api.config";
import usePostManagement from "@/hooks/usePostManagement";

import { MdDateRange, MdDeleteForever, MdEdit } from "react-icons/md";
import { FaLocationDot } from "react-icons/fa6";

const JadwalPelatihan = (props) => {
  const [dataJadwal, setDataJadwal] = useState({ method: "Offline" });
  const [dataJadwalList, setDataJadwalList] = useState(
    props.additional_data?.jadwalPelatihanList || []
  );
  const [isLoading, setIsLoading] = useState(false);
  const { execute } = usePostManagement();

  const addJadwalPelatihan = useCallback(
    async (event) => {
      event.preventDefault();
      execute({
        call: async () => {
          setIsLoading(true);

          const response = await api.patch(`/admin/jadwal-pelatihan`, {
            ...dataJadwal,
            post_id: props.data._id,
          });

          setDataJadwalList((prev) => {
            const alreadyData = prev.find((item) => item._id === response._id);
            if (alreadyData) {
              return prev.map((item) =>
                item._id === response._id ? response : item
              );
            } else {
              return [...prev, response];
            }
          });
          setDataJadwal({ method: "Offline" });
        },
        onError: "Updating Jadwal Pelatihan Failed! Contact Administrator.",
        onSuccess: "Updated Jadwal Pelatihan Successfully!",
        successAction: () => setIsLoading(false),
        errorAction: () => setIsLoading(false),
      });
    },
    [dataJadwal, execute, props]
  );
  // console.log(props);
  const deleteJadwal = async (_id) => {
    execute({
      call: async () => {
        await api.delete(`/admin/jadwal-pelatihan?_id=${_id}`);
      },
      onError: "Deleting Jadwal Pelatihan Failed! Contact Administrator.",
      onSuccess: "Deleted Jadwal Pelatihan Successfully!",
      successAction: () => {
        setDataJadwalList((prev) => prev.filter((item) => item._id !== _id));
      },
    });
  };

  return (
    <>
      <div className={styles.form_jadwal_pelatihan}>
        <Dropdown
          label="Method"
          labelclassname={styles.label}
          className={styles.input}
          data={[{ name: "Offline" }, { name: "Online" }, { name: "Blended" }]}
          display="name"
          value={{ name: dataJadwal.method }}
          onChange={(data) =>
            setDataJadwal((prev) => ({ ...prev, method: data.name }))
          }
        />
        <Input
          type="date"
          label="Date Start"
          className={styles.input}
          value={dataJadwal.date_start || ""}
          onChange={(e) =>
            setDataJadwal((prev) => ({ ...prev, date_start: e.target.value }))
          }
        />
        <Input
          type="date"
          label="Date End"
          className={styles.input}
          value={dataJadwal.date_end || ""}
          onChange={(e) =>
            setDataJadwal((prev) => ({ ...prev, date_end: e.target.value }))
          }
        />
        <Input
          type="text"
          label="City"
          className={styles.input}
          value={dataJadwal.city || ""}
          onChange={(e) =>
            setDataJadwal((prev) => ({ ...prev, city: e.target.value }))
          }
        />
        <Input
          type="text"
          label="Location"
          className={styles.input}
          value={dataJadwal.location || ""}
          onChange={(e) =>
            setDataJadwal((prev) => ({ ...prev, location: e.target.value }))
          }
        />

        <Dropdown
          label="Status"
          labelclassname={styles.label}
          className={styles.input}
          data={[{ name: "" }, { name: "Almost" }, { name: "Running" }]}
          display="name"
          value={{ name: dataJadwal.status }}
          onChange={(data) =>
            setDataJadwal((prev) => ({ ...prev, status: data.name }))
          }
        />
      </div>
      <div
        style={{
          clear: "both",
          display: "flex",
          gap: "10px",
          marginBottom: "10px",
          justifyContent: "flex-end",
        }}>
        {dataJadwal._id && (
          <Button
            className={styles.button + " " + styles.red}
            onClick={() => setDataJadwal({ method: "Offline" })}>
            Cancel
          </Button>
        )}

        <Button
          className={styles.button + " " + styles.blue}
          onClick={addJadwalPelatihan}
          disabled={isLoading}>
          {isLoading && <Loader color="#fff" />}Save
        </Button>
      </div>
      {dataJadwalList.length === 0 && (
        <div
          style={{ textAlign: "center", fontStyle: "italic", color: "#777" }}>
          No data available in table
        </div>
      )}
      <div className={styles.jadwal_list}>
        {dataJadwalList.map((element) => (
          <div key={element._id}>
            <div style={{ flex: 1 }}>
              <MdDateRange />{" "}
              {formatDateRange(element.date_start, element.date_end)}
            </div>
            <div style={{ flex: 1 }}>
              <FaLocationDot /> {element.city}, {element.location}
            </div>
            <div style={{ flex: 1 }}>{element.method}</div>
            <div style={{ flex: 1 }}>{element.status}</div>
            <div style={{ flex: 1 }}>
              <Button
                className={styles.button + " " + styles.red}
                onClick={() => deleteJadwal(element._id)}>
                <MdDeleteForever />
              </Button>
              <Button
                className={styles.button + " " + styles.blue}
                onClick={() => setDataJadwal(element)}>
                <MdEdit />
              </Button>
            </div>
          </div>
        ))}
      </div>
    </>
  );
};
export default JadwalPelatihan;
