"use client";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

import { useToast } from "@/components/ui/use-toast";
import Axios from "@/lib/Axios";
import { PermissionsDataT } from "@/types/global";
import { PermissionRespT, RoleRespT } from "@/types/roleAndPermissions";
import { UserListT } from "@/types/user";
import { yupResolver } from "@hookform/resolvers/yup";
import { useMutation, useQuery } from "@tanstack/react-query";
import { Camera } from "lucide-react";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { AddUserSchemaT, addUserSchema } from "../_schema";
import useUserStore from "@/store/useUserStore";

import { Combobox } from "@/components/combobox";
import { SearchPermission } from "@/components/pages/add-emp/searchPermissions";
import { SearchReportTo } from "@/components/pages/add-emp/searchReportTo";
import { RespError } from "@/types/auth";
import { AxiosError, AxiosResponse } from "axios";
import { useRouter } from "next/navigation";
import FormReviewe from "./_helper/formReview";

export type PlaceholdersT = {
  role?: string;
  report_to?: string;
};

const ManageUser = ({ params }: { params: { slug: string } }) => {
  const { toast } = useToast();
  const router = useRouter();
  const {
    register,
    handleSubmit,
    setValue,
    reset,
    watch,
    formState: { errors, isSubmitting },
  } = useForm<AddUserSchemaT>({
    resolver: yupResolver(addUserSchema),
    defaultValues: {
      permissions: [],
    },
  });

  const permissions = watch("permissions");
  const [placeholders, setPlaceholders] = useState<PlaceholdersT>({
    role: "",
    report_to: "",
  });

  const { data, error, isLoading } = useQuery({
    queryKey: ["user-roles"],
    queryFn: getRoles,
  });



  const {
    data: permissionsData,
    error: permissionsError,
    isLoading: permissionsIsLoading,
  } = useQuery<PermissionRespT>({
    queryKey: ["permissions"],
    queryFn: getPermissions,
  });
const datas = useUserStore((state) => state.data);
  const [hydrated, setHydrated] = useState(false);

  useEffect(() => {
    setHydrated(true);
  }, []);

  // Redirect to /login if data is null or blank, but only after hydration
  useEffect(() => {
    if (hydrated && (!datas || !datas.tokens?.access)) {
      router.push("/login");
    }
  }, [hydrated, datas, router]);

  const mutationSend = useMutation<
    AxiosResponse<UserListT>,
    AxiosError<RespError>,
    any
  >({
    mutationFn: sendData,
    onSuccess: (data) => {
      toast({
        title: "Success",
        description: "User has been saved successfully",
      });
      router.push("/user");
    },
    onError: (error) => {
      const errorMessage = error.response?.data?.message || "An error occurred";
      toast({
        variant: "destructive",
        title: "Error",
        description: errorMessage,
      });
    }
  });

  function sendData(data?: AddUserSchemaT) {
    if (!!params?.slug?.length) {
      return Axios.patch("/users/employees/" + params?.slug[0] + "/", data);
    } else {
      return Axios.post("/users/employees/", data);
    }
  }

  async function getData() {
    try {
      const resp = await Axios.get<UserListT>(
        "/users/employees/" + params?.slug[0]
      ).then((res) => res.data);

      const permissions = resp.granted_permissions.map((per) => per.id + "");

      const obj: AddUserSchemaT = {
        permissions: permissions,
        reports_to_id: resp.reports_to?.id || ("" as any),
        role_id: resp.role?.id || ("" as any),
        user: {
          name: resp.user.name,
          email: resp.user.email,
        },
      };

      placeholders.report_to = resp.reports_to?.user.name || "";
      placeholders.role = resp.role?.name || "";

      reset(obj);
    } catch (error) { }
  }

  async function onSubmit(data: AddUserSchemaT) {
    console.log("Submitting user data:", data);
    await mutationSend.mutateAsync(data);
  }

  async function getPermissions() {
    return Axios.get<PermissionRespT>("/users/permissions/").then(
      (res) => res.data
    );
  }

  async function getRoles() {
    return Axios.get<RoleRespT>("/users/roles/").then((res) => res.data.data);
  }

  function onSelectPermission(data: PermissionsDataT) {
    console.log(permissions?.indexOf(data.id + ""));
    console.log(permissions);
    const index = permissions?.indexOf(data.id + "");
    if (index === -1) {
      setValue("permissions", [...permissions!, data.id + ""]);
    } else {
      const list = [...permissions!];
      list.splice(index!, 1);
      setValue("permissions", [...list]);
    }
  }

  useEffect(() => {
    if (!!params?.slug?.length) getData();
  }, []);

  // Utility to get other permissions
  function getOtherPermissions(all: any[], customer: any[], user: any[]) {
    const customerIds = new Set(customer.map((p) => p.id));
    const userIds = new Set(user.map((p) => p.id));
    return all.filter((p) => !customerIds.has(p.id) && !userIds.has(p.id));
  }

  function handleSelectGroup(ids: string[]) {
    // If all group permissions are already selected, remove them; otherwise, add them
    const current = watch("permissions") || [];
    const set = new Set(current);
    const allSelected = ids.every((id) => set.has(id));
    let newPermissions;
    if (allSelected) {
      // Deselect all in group
      const idsSet = new Set(ids);
      newPermissions = current.filter((value: string | undefined) => value !== undefined && !idsSet.has(value));
    } else {
      // Select all in group (add missing ones)
      newPermissions = Array.from(new Set([...current, ...ids]));
    }
    setValue("permissions", newPermissions);
  }

  if (!hydrated) return null;

  return (
    <div className="grid grid-cols-1 xl:grid-cols-2 gap-14 min-h-[40rem] mt-10 mb-20">
      <form
        onSubmit={handleSubmit(onSubmit)}
        className="left-card  border rounded-sm"
      >
        <div className="bg-secondary flex items-center gap-10 py-3 pl-6">
          <div className="relative">
            <Avatar className="w-16 h-16">
              <AvatarImage src="/assets/images/user.png" />
              <AvatarFallback>Profile</AvatarFallback>
            </Avatar>
            {/* <div className="cursor-pointer absolute w-8 h-8 -right-2 -bottom-3 rounded-full flex justify-center items-center text-white bg-yellowish">
              <Camera className="scale-75" />
            </div> */}
          </div>

          <p className="text-white text-xl ">User Details</p>
        </div>

        <div className="px-10 space-y-8 mt-8">
          <Input
            makePlacholderAsLabel
            capitalize
            {...register("user.name")}
            placeholder="Name"
            className="rounded-none"
            errorMsg={errors.user?.name?.message}
          />
          <Input
            makePlacholderAsLabel
            {...register("user.email")}
            placeholder="E-mail ID"
            className="rounded-none"
            errorMsg={errors.user?.email?.message}
          />

          <div className="">
            <div className="h-6">
              {placeholders.report_to && (
                <label htmlFor="" className="text-sm">
                  Report to
                </label>
              )}
            </div>
            <Combobox<UserListT>
              placeholder={placeholders.report_to || "Report to"}
              onSelect={(e) => {
                console.log(e);
                setPlaceholders((prev) => ({
                  ...prev,
                  report_to: e.user.name,
                }));

                setValue("reports_to_id", String(e.id));
              }}
            >
              <SearchReportTo />
            </Combobox>
            <p className="text-xs text-red-500">
              {errors.reports_to_id?.message}
            </p>
          </div>

          <div className="">
            <div className="h-6">
              {placeholders.role && (
                <label htmlFor="" className="text-sm">
                  Role
                </label>
              )}
            </div>
            <Select
              onValueChange={(e) => {
                const selectedRole = data?.find((val) => val.id === Number(e));
                let rolePermissions = selectedRole?.permissions!.map((item) => String(item.id)) || [];
                const defaultCustomerPermissionCodenames = [
                  "add_address",
                  "change_address",
                  "view_address",
                  "add_customer",
                  "change_customer",
                  "view_customer",
                  "add_customernotes",
                  "view_customernotes",
                ];
                if (
                  selectedRole &&
                  (selectedRole.name === "Owner" || selectedRole.name === "Admin") &&
                  permissionsData?.customer_permissions &&
                  permissionsData?.user_permissions
                ) {
                  // For Owner/Admin, select all customer and user permissions
                  const customerPermissionIds = permissionsData.customer_permissions.map((perm) => String(perm.id));
                  const userPermissionIds = permissionsData.user_permissions.map((perm) => String(perm.id));
                  rolePermissions = Array.from(new Set([...customerPermissionIds, ...userPermissionIds]));
                } else if (
                  selectedRole &&
                  permissionsData?.customer_permissions
                ) {
                  // For non-Owner/Admin, only select the default subset of customer permissions
                  const defaultCustomerPermissionIds = permissionsData.customer_permissions
                    .filter((perm) => defaultCustomerPermissionCodenames.includes(perm.codename))
                    .map((perm) => String(perm.id));
                  rolePermissions = Array.from(new Set([...rolePermissions, ...defaultCustomerPermissionIds]));
                }
                // Always set a new array reference
                setValue("permissions", [...rolePermissions]);
                setValue("role_id", e);
                setPlaceholders((prev) => ({
                  ...prev,
                  role: e,
                }));
              }}
            >
              <SelectTrigger className="">
                <SelectValue placeholder={placeholders.role || "Role"} />
              </SelectTrigger>

              <SelectContent>
                <SelectGroup>
                  {data?.map((dt) => (
                    <SelectItem key={dt.id} value={dt.id + ""}>
                      {dt.name}
                    </SelectItem>
                  ))}
                </SelectGroup>
              </SelectContent>
            </Select>
            <p className="text-xs text-red-500">{errors.role_id?.message}</p>
          </div>

          <SearchPermission
            checkList={permissions}
            onSelectResult={onSelectPermission}
            customerPermissions={permissionsData?.customer_permissions || []}
            userPermissions={permissionsData?.user_permissions || []}
            otherPermissions={getOtherPermissions(
              permissionsData?.data || [],
              permissionsData?.customer_permissions || [],
              permissionsData?.user_permissions || []
            )}
            onSelectGroup={handleSelectGroup}
          />

          {/* <ScrollArea className="h-52 w-full rounded-md border p-5">
            <div className="flex flex-col items-start flex-wrap gap-2 ">
              {permissionsData?.map((item, index) => {
                return (
                  <div key={item.id} className="flex  ">
                    <Input
                      // checked={checkedPermissions.some(
                      //   (val) => val.id === item.id
                      // )}
                      type="checkbox"
                      {...register(`permissions`)}
                      id={item.id + ""}
                      value={item.id}
                      className="w-8"
                    />
                    <label
                      htmlFor={item.id + ""}
                      className="text-sm text-brownish whitespace-nowrap  leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      {item.name}
                    </label>
                  </div>
                );
              })}
            </div>
          </ScrollArea> */}
          <p className="text-xs text-red-500">{errors.permissions?.message}</p>
        </div>
        <div className="flex justify-center">
          <Button
            type="submit"
            disabled={isSubmitting}
            className="w-80 mx-auto my-5"
          >
            SAVE
          </Button>
        </div>
      </form>
      <FormReviewe
        watch={watch}
        roleData={data}
        permissionsData={[
          ...(permissionsData?.data || []),
          ...(permissionsData?.customer_permissions || []),
          ...(permissionsData?.user_permissions || []),
        ]}
        placeholder={placeholders}
      />
    </div>
  );
};

export default ManageUser;
