"use client";
import { Button } from "@/components/ui/button";
import Select, { MultiValue } from "react-select";

import { Icon } from "@iconify/react/dist/iconify.js";
import { useEffect, useState } from "react";
import { Separator } from "@/components/ui/separator";
import {
  getCuratorUser,
  saveCollaborationTeams,
} from "@/service/communication/communication";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { close, loading } from "@/config/swal";
import { useParams } from "next/navigation";
import { useToast } from "@/components/ui/use-toast";
import { stringify } from "querystring";

const assigneeOptions = [
  { value: "mahedi", label: "Mahedi Amin", image: "/images/avatar/av-1.svg" },
  { value: "sovo", label: "Sovo Haldar", image: "/images/avatar/av-2.svg" },
  {
    value: "rakibul",
    label: "Rakibul Islam",
    image: "/images/avatar/av-3.svg",
  },
  { value: "pritom", label: "Pritom Miha", image: "/images/avatar/av-4.svg" },
];
export default function UsersCard(props: { team: any; fetchData: () => void }) {
  const params = useParams();
  const id = params?.id;
  const [openSearch, setOpenSearch] = useState(false);
  const [selectedUsers, setSelectedUsers] = useState<any>([]);
  const [allUser, setAllUser] = useState([]);
  const MySwal = withReactContent(Swal);
  const { toast } = useToast();

  useEffect(() => {
    async function getUser() {
      const res = await getCuratorUser();

      if (res?.data !== null) {
        const rawUser = res?.data?.data?.content;
        const optionArr: any = [];

        rawUser.map((option: any) => {
          optionArr.push({
            id: option.id,
            label: option.username,
            value: option.id,
          });
        });

        setAllUser(optionArr);
      }
    }
    getUser();
  }, []);

  const inviteHandle = () => {
    MySwal.fire({
      title: "Undang Pengguna Ke Kolom Diskusi?",
      text: "",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Simpan",
    }).then((result) => {
      if (result.isConfirmed) {
        inviteUser();
      }
    });
  };

  async function inviteUser() {
    const userId: any = [];

    selectedUsers?.map((user: any) => {
      userId.push(user.id);
    });
    loading();
    const res = await saveCollaborationTeams(String(id), userId);

    if (res?.error) {
      toast({ title: stringify(res?.message) });
      return false;
    }
    close();

    toast({ title: "Berhasil menambahkan user" });
    props.fetchData();
  }

  return (
    <div className="flex flex-col bg-white p-4 rounded-t-xl w-[30%]">
      <div className="flex justify-between items-center mb-3">
        <div className="flex flex-row gap-3 items-center">
          <p>Kolaborator</p>
          <p className="p-2 rounded-full bg-slate-300 w-5 h-5 flex justify-center items-center">
            {props?.team?.length}
          </p>
        </div>
        <a onClick={() => setOpenSearch(!openSearch)}>
          <Icon icon="material-symbols:search" width={24} />
        </a>
      </div>
      {openSearch && (
        <div className="flex flex-col">
          <Select
            className="react-select my-2 transition-shadow"
            classNamePrefix="select"
            options={allUser}
            isMulti
            onChange={(selectedOption) => setSelectedUsers(selectedOption)}
            placeholder="Select users"
          />
          {selectedUsers?.length > 0 && (
            <div className="flex justify-end">
              <Button color="primary" size="sm" onClick={inviteHandle}>
                Invie
              </Button>
            </div>
          )}
        </div>
      )}
      <div className="mt-3 flex flex-col gap-2">
        {props?.team?.map((list: any) => (
          <div key={list.id} className="flex flex-col">
            <div className="flex flex-row gap-2 items-center">
              <Icon icon="qlementine-icons:user-16" width={36} />
              <div className="flex flex-col">
                <p className="text-sm">{list?.fullname}</p>
                <p className="text-xs">{list?.username}</p>
              </div>
            </div>
            <Separator className="my-2" />
          </div>
        ))}
      </div>
    </div>
  );
}
