import { Combobox } from "@/components/combobox";
import { InnerCard } from "@/components/menu-slider";
import { SearchReportTo } from "@/components/pages/add-emp/searchReportTo";
import {
  Menubar,
  MenubarContent,
  MenubarItem,
  MenubarMenu,
  MenubarTrigger,
} from "@/components/ui/menubar";
import { toast } from "@/components/ui/use-toast";
import Axios from "@/lib/Axios";
import { RespError } from "@/types/auth";
import { CustomerDataT } from "@/types/customer";
import { UserListT } from "@/types/user";
import { useMutation } from "@tanstack/react-query";
import { AxiosError, AxiosResponse } from "axios";
import { Ellipsis, Loader } from "lucide-react";
import Link from "next/link";
import { useEffect } from "react";

const permissionList = [
  "Permission 1",
  "Permission 2",
  "Permission 3",
  "Permission 4",
  "Permission 5",
  "Permission 6",
];

export function CustomerMenuDetails(
  customerData: CustomerDataT,
  refetch: () => void
) {
  const phoneNo = customerData.is_land_line_default!!
    ? customerData.mobile_phone
    : customerData.home_phone;
  return (
    <>
      <InnerCard>
        <>
          <p className="text-danger text-xl underline">Basis Details</p>
          <div className="text-xs mt-2 text-black">
            <p className="">
              Cust ID: <span className="font-medium">{customerData?.id}</span>
            </p>
            <p className="">
              Name:{" "}
              <span className="font-medium">
                {customerData?.first_name + " " + customerData?.last_name}
              </span>
            </p>
            <p className="">
              Phone No.: <span className="font-medium">{phoneNo}</span>
            </p>

            <p className="">
              Address:{" "}
              <span className="font-medium">
                {customerData?.address?.[0]?.address1 || ""}
              </span>
            </p>

            <p className="">
              E-mail ID:{" "}
              <span className="font-medium">{customerData?.email}</span>
            </p>
            <p className="">
              Agent:{" "}
              <span className="font-medium">
                {customerData.assigned_to?.user.name}
              </span>
            </p>
          </div>
        </>
      </InnerCard>
      <InnerCard>
        <p className="text-danger text-xl underline">Orders</p>

        <div className="text-xs mt-2 text-black">
          <p className="">
            Total Order: <span className="font-medium">08</span>
          </p>
          <p className="">
            Pound Value Spend : <span className="font-medium">$750</span>
          </p>
        </div>
      </InnerCard>

      <InnerCard>
        <p className="text-danger text-xl underline mb-2">Assign to</p>
        <AssignToOption customerData={customerData} refetch={refetch} />
      </InnerCard>

      {/* <InnerCard>
        <>
          <p className="text-white text-xl underline mb-3">Notes</p>

          <ListComments id={customerData.id} />

          <div className="text-danger mt-5 flex items-center gap-4">
            <Avatar>
              <AvatarImage alt="@shadcn" />
              <AvatarFallback className="bg-primary text-white">
                {customerData?.first_name.charAt(0).toUpperCase() +
                  customerData?.last_name.charAt(0).toUpperCase()}
              </AvatarFallback>
            </Avatar>

            <SendNote id={customerData.id} />
          </div>
        </>
      </InnerCard> */}
    </>
  );
}

export function Options(customerData: CustomerDataT) {
  return (
    <Menubar className="bg-transparent p-0 border border-none">
      <MenubarMenu>
        <MenubarTrigger className=" ">
          <Ellipsis className="cursor-pointer" />
        </MenubarTrigger>
        <MenubarContent>
          <MenubarItem>
            <Link
              href={
                "customer/customer-manage/" +
                customerData.id +
                "?firstName=" +
                customerData.first_name +
                "&lastName=" +
                customerData.last_name
              }
              className="flex gap-2 items-center w-full"
            >
              Edit
            </Link>
          </MenubarItem>
          <MenubarItem>
            <Link
              href={
                "customer/view-details//" +
                customerData.id +
                "?firstName=" +
                customerData.first_name +
                "&lastName=" +
                customerData.last_name
              }
              className="flex gap-2 items-center w-full"
            >
              View
            </Link>
          </MenubarItem>
        </MenubarContent>
      </MenubarMenu>
    </Menubar>
  );
}

function AssignToOption({
  customerData,
  refetch,
}: {
  customerData: CustomerDataT;
  refetch: () => void;
}) {
  const mutationSend = useMutation<
    AxiosResponse<any>,
    AxiosError<RespError>,
    any
  >({
    mutationFn: sendData,
    onSuccess: (data) => {
      toast({
        title: "Success",
        description: "User has been saved successfully",
      });
      refetch();
    },
    onError: (error) => {
      const errorObj: Record<any, string[]> = error.response?.data.data!;
      let message = "";
      for (let key in errorObj) {
        if (errorObj.hasOwnProperty(key)) {
          let value = errorObj[key];
          message += key + " " + value[0] + "\n";
        }
      }
      toast({
        variant: "destructive",
        title: "Error",
        description: message,
      });
    },
  });

  function sendData(id?: number) {
    const data = {
      customer_ids: [customerData.id],
      assigned_to_id: id,
    };

    return Axios.patch("/customer/management/bulk_assign/", data);
  }

  return (
    <div className="flex items-center gap-2">
      <Combobox<UserListT>
        placeholder={customerData?.assigned_to?.user.name || "Assign to"}
        onSelect={(e) => {
          console.log(e);
          if (e === null) {
            return;
          }
          mutationSend.mutate(e.id);
        }}
      >
        <SearchReportTo />
      </Combobox>
      {mutationSend.isPending && (
        <Loader className="text-white animate-spin " />
      )}
    </div>
  );
}
