"use client";
import {
  Button,
  Input,
  Radio,
  RadioGroup,
  Select,
  SelectItem,
  SelectSection,
  Slider,
  Switch,
  Tab,
  Table,
  Tabs,
  Textarea,
  User,
} from "@heroui/react";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { TimesIcon } from "@/components/icons";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { close, error, loading } from "@/config/swal";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import dynamic from "next/dynamic";
import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  createUserLevels,
  editUserLevels,
  getAllUserLevels,
  getUserLevels,
} from "@/services/user-levels/user-levels-service";
import ReactSelect from "react-select";
import makeAnimated from "react-select/animated";

const createArticleSchema = z.object({
  name: z.string().min(2, {
    message: "Required",
  }),
  aliasName: z.string().optional(),
  group: z.string().min(2, {
    message: "Required",
  }),
});

const groups = [
  { id: 1, name: "Mabes", value: "mabes", level: 1 },
  { id: 2, name: "Polda", value: "polda", level: 2 },
  { id: 3, name: "Satker", value: "satker", level: 2 },
  { id: 4, name: "Polres", value: "polres", level: 3 },
  { id: 5, name: "Subdiv", value: "subdiv", level: 3 },
];

export default function EditUserLevelForm() {
  const router = useRouter();
  const MySwal = withReactContent(Swal);
  const animatedComponents = makeAnimated();
  const [needApproval, setNeedApproval] = useState(false);
  const [parentList, setParentList] = useState<any>([]);
  const [selectedParent, setSelectedParent] = useState<any>();
  const params = useParams();
  const id = params?.id;

  const formOptions = {
    resolver: zodResolver(createArticleSchema),
    defaultValues: { name: "", group: "" },
  };
  type UserSettingSchema = z.infer<typeof createArticleSchema>;
  const {
    register,
    control,
    handleSubmit,
    formState: { errors, isValid },
    setValue,
    getValues,
    watch,
    setError,
    clearErrors,
  } = useForm<UserSettingSchema>(formOptions);

  const watchName = watch("name");
  const selectedGroup = watch("group");

  const generateSlug = (title: string) => {
    return title
      .toLowerCase()
      .trim()
      .replace(/[^\w\s-]/g, "")
      .replace(/\s+/g, "-");
  };

  useEffect(() => {
    setValue("aliasName", generateSlug(watchName));
  }, [watchName]);

  const findSelectedLevel = (group: string) => {
    const selectedLevel = groups.find((a) => a.value === group);
    return selectedLevel ? selectedLevel : null;
  };

  const save = async (data: any) => {
    const findParent = (group: string) => {
      if (group === "mabes") {
        return 0;
      }
      //  else if (group === "polda" || group === "satker") {
      //   if (group === "polda") {
      //     return 1;
      //   } else {
      //     return 555;
      //   }
      // }
      else {
        return selectedParent?.id;
      }
    };

    const request = {
      name: data.name,
      aliasName: data.aliasName,
      levelNumber: findSelectedLevel(data.group)?.level,
      isActive: true,
      group: data.group,
      parentLevelId: findParent(data.group),
      provinceId: 0,
      isApprovalActive: needApproval,
    };

    loading();
    const res = await editUserLevels(String(id), request);
    if (res.error) {
      error(res.message);
      return false;
    }
    close();
    successSubmit("/admin/user-level");
  };

  async function onSubmit(data: any) {
    MySwal.fire({
      title: "Save Data",
      text: "",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Save",
    }).then((result) => {
      if (result.isConfirmed) {
        save(data);
      }
    });
  }

  function successSubmit(redirect: string) {
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        router.push(redirect);
      }
    });
  }

  useEffect(() => {
    if (findSelectedLevel(selectedGroup)?.level !== 1) {
      fetchCategory();
    }
  }, [selectedGroup]);

  const fetchCategory = async () => {
    loading();
    const request = {
      limit: -1,
      levelNumber: findSelectedLevel(selectedGroup)?.level
        ? findSelectedLevel(selectedGroup)!.level - 1
        : "",
    };
    const res = await getAllUserLevels(request);
    close();
    if (res?.data?.data) {
      return setupParent(res?.data?.data);
    }
  };

  const setupParent = (data: any) => {
    const temp = [];
    for (const element of data) {
      temp.push({
        id: element.id,
        label: element.name,
        value: element.aliasName,
      });
    }
    setParentList(temp);
    return temp;
  };

  useEffect(() => {
    initFetch();
  }, []);

  const initFetch = async () => {
    const parent = await fetchCategory();
    const res = await getUserLevels(String(id));
    const data = res?.data?.data;
    setValue("name", data?.name);
    setValue("aliasName", data?.aliasName);
    setValue("group", data?.group);
    const parentId = parent?.find((a: any) => a.id === data?.parentLevelId);
    setSelectedParent(parentId);
  };

  return (
    <form
      className="flex flex-col lg:flex-row gap-8 text-black p-4 lg:p-8"
      onSubmit={handleSubmit(onSubmit)}
    >
      <div className="w-full lg:w-1/2 bg-white rounded-lg p-4 lg:p-8 flex flex-col gap-1 shadow-lg">
        <p className="text-sm">
          Name<span className="text-danger">*</span>
        </p>
        <Controller
          control={control}
          name="name"
          render={({ field: { onChange, value } }) => (
            <Input
              type="text"
              id="name"
              placeholder=""
              label=""
              value={value}
              onChange={onChange}
              labelPlacement="outside"
              className="w-full "
              classNames={{
                inputWrapper: [
                  "border-1 rounded-lg",
                  "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                ],
              }}
              variant="bordered"
            />
          )}
        />
        {errors?.name && (
          <p className="text-red-400 text-sm mb-3">{errors.name?.message}</p>
        )}
        <p className="text-sm mt-3">Alias Name</p>
        <Controller
          control={control}
          name="aliasName"
          render={({ field: { onChange, value } }) => (
            <Input
              type="text"
              id="alias"
              placeholder=""
              label=""
              isReadOnly
              value={value}
              onChange={onChange}
              labelPlacement="outside"
              className="w-full "
              classNames={{
                inputWrapper: [
                  "border-1 rounded-lg",
                  "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                ],
              }}
              variant="bordered"
            />
          )}
        />
        {errors?.aliasName && (
          <p className="text-red-400 text-sm mb-3">
            {errors.aliasName?.message}
          </p>
        )}
        <p className="text-sm mt-3">
          Group<span className="text-danger">*</span>
        </p>
        <Controller
          control={control}
          name="group"
          render={({ field: { onChange, value } }) => (
            <Select
              variant="bordered"
              label=""
              labelPlacement="outside"
              selectedKeys={[value]}
              onChange={onChange}
              classNames={{
                trigger: [
                  "border-1 rounded-lg",
                  "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                ],
              }}
            >
              {groups.map((group) => (
                <SelectItem key={group.value}>{group.name}</SelectItem>
              ))}
            </Select>
          )}
        />
        {errors?.name && (
          <p className="text-red-400 text-sm mb-3">{errors.name?.message}</p>
        )}

        <p className="text-sm mt-3">Need Approval</p>
        <Switch isSelected={needApproval} onValueChange={setNeedApproval}>
          <p className="text-sm text-black">
            {needApproval ? "Active" : "Inactive"}
          </p>
        </Switch>
        {selectedGroup && findSelectedLevel(selectedGroup)?.level !== 1 && (
          <>
            <p className="text-sm mt-3">Parent</p>
            <ReactSelect
              className="basic-single text-black z-50"
              classNames={{
                control: (state: any) =>
                  "!rounded-lg bg-white !border-1 !border-gray-200 dark:!border-stone-500",
              }}
              classNamePrefix="select"
              value={selectedParent}
              onChange={setSelectedParent}
              closeMenuOnSelect={false}
              components={animatedComponents}
              isClearable={true}
              isSearchable={true}
              isMulti={false}
              placeholder=""
              name="sub-module"
              options={parentList}
            />
          </>
        )}

        <div className="flex flex-row gap-3 mt-5">
          <Button
            color="primary"
            type="submit"
            isDisabled={
              findSelectedLevel(selectedGroup)?.level === 3 && !selectedParent
            }
          >
            Simpan
          </Button>
          <Link href="/admin/master-user-level">
            <Button color="danger">Kembali</Button>
          </Link>
        </div>
      </div>
    </form>
  );
}
