// import { IndeterminateCheckbox } from "@/components/tanstack-table";
import { confirmModla } from "@/components/confirm-dialog";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { toast } from "@/components/ui/use-toast";
import Axios from "@/lib/Axios";
import { CustomerDataT } from "@/types/customer";
import { UserListT } from "@/types/user";
import { ColumnDef } from "@tanstack/react-table";
import { AxiosError } from "axios";
import { format, isValid } from "date-fns";
import { Info, Pencil, Trash2, ArrowRight, Plus } from "lucide-react";
import Link from "next/link";
import React, { useEffect, useRef, useState } from "react";
import { CustomerOrdersDialog } from "@/components/pages/customer/CustomerOrdersDialog";
import { Button } from "@/components/ui/button";
import { getCurrentUserId } from "@/lib/jwtUtils";
import useUserStore from "@/store/useUserStore";

// Helper function to check if user has access to a customer
function hasCustomerAccess(customer: CustomerDataT): boolean {
  const userData = useUserStore.getState().data;
  const currentUserId = getCurrentUserId(userData);
  const userRole = userData?.role;
  
  // Admin and Owner have access to all customers
  const isAdminOrOwner = userRole === 'Admin' || userRole === 'Owner';
  
  // Check if user has access (created by or assigned to current user, or is Admin/Owner)
  const isCreatedByUser = customer.created_by?.id === currentUserId;
  const isAssignedToUser = customer.assigned_to?.id === currentUserId;
  
  return isAdminOrOwner || isCreatedByUser || isAssignedToUser;
}

// Component for Orders column cell
function OrdersCell({ customer }: { customer: CustomerDataT }) {
  const [isOpen, setIsOpen] = useState(false);
  const customerName = `${customer.first_name} ${customer.last_name}`.trim();
  const hasAccess = hasCustomerAccess(customer);
  
  if (!hasAccess) {
    // For customers without access, show empty div (similar to Action column)
    return (
      <div className="flex justify-center gap-5">
      </div>
    );
  }
  
  // For customers with access, show the Orders button
  return (
    <div className="flex justify-center">
      <Button
        variant="ghost"
        size="icon"
        onClick={(e) => {
          e.stopPropagation();
          setIsOpen(true);
        }}
        className="h-8 w-8"
      >
        <ArrowRight className="w-4 h-4" />
      </Button>
      <CustomerOrdersDialog
        customerId={customer.id}
        customerName={customerName}
        firstName={customer.first_name}
        lastName={customer.last_name}
        open={isOpen}
        onOpenChange={setIsOpen}
      />
    </div>
  );
}

type method = "delete" | "patch";

type IndeterminateCheckboxProps =
  React.InputHTMLAttributes<HTMLInputElement> & {
    indeterminate?: boolean;
  };

const IndeterminateCheckbox = React.forwardRef<
  HTMLInputElement,
  IndeterminateCheckboxProps
>(({ indeterminate = false, ...rest }, ref) => {
  const internalRef = useRef<HTMLInputElement>(null);
  const combinedRef = ref ?? internalRef;

  useEffect(() => {
    if (combinedRef && "current" in combinedRef && combinedRef.current) {
      combinedRef.current.indeterminate = indeterminate;
    }
  }, [combinedRef, indeterminate]);

  return <input type="checkbox" ref={combinedRef} {...rest} />;
});

IndeterminateCheckbox.displayName = "IndeterminateCheckbox";

export default IndeterminateCheckbox;

export function getUserTableColumns(refetch: () => Promise<any>) {
  async function activateDeActivateUser(
    method: method,
    id: number,
    endpoint: string
  ) {
    try {
      await Axios[method]("users/employees/" + id + "/" + endpoint, {
        is_active: true,
      });
      await refetch();
      toast({
        title: "Success",
        description:
          method === "delete"
            ? "User has been De-activated successfully."
            : "User has been Re-activated successfully.",
      });
    } catch (error) {
      const er = error as AxiosError;
      toast({
        variant: "destructive",
        title: er.message,
      });
    }
  }

  const columns = React.useMemo<ColumnDef<UserListT>[]>(
    () => [
      // {
      //   id: "select",
      //   header: ({ table }) => (
      //     <IndeterminateCheckbox
      //       {...{
      //         checked: table.getIsAllRowsSelected(),
      //         indeterminate: table.getIsSomeRowsSelected(),
      //         onChange: table.getToggleAllRowsSelectedHandler(),
      //       }}
      //     />
      //   ),
      //   cell: ({ row }) => (
      //     <div className="px-1" onClick={(e) => e.stopPropagation()}>
      //       <IndeterminateCheckbox
      //         {...{
      //           checked: row.getIsSelected(),
      //           disabled: !row.getCanSelect(),
      //           indeterminate: row.getIsSomeSelected(),
      //           onChange: row.getToggleSelectedHandler(),
      //         }}
      //       />
      //     </div>
      //   ),
      // },
      {
        id: "name",
        accessorKey: "user.name",
        cell: (info) => info.getValue(),
        header: () => <span className="block text-center">NAME</span>,
      },
      {
        id: "role",
        accessorKey: "role.name",
        cell: (info) => info.getValue() || "-",
        header: () => <span className="block text-center">ROLE</span>,
      },
      {
        id: "email",
        accessorKey: "user.email",
        header: () => <span className="block text-center">E-MAIL ID</span>,
      },
      {
        id: "report",
        accessorKey: "reports_to.user.name",
        cell: (info) => info.getValue() || "-",
        header: () => <span className="block text-center">REPORTS TO</span>,
      },
      {
        id: "last_login",
        accessorKey: "user.last_login",
        header: () => <span className="block text-center">LAST LOGIN</span>,
        cell: (info) =>
          isValid(new Date((info.getValue() as string) || ""))
            ? format(new Date(info.getValue() as string), "EEE dd LLL yyyy") +
              " at " +
              format(new Date(info.getValue() as string), "h:mm a")
            : "-",
      },
      {
        id: "status",
        accessorKey: "is_active",
        header: () => <span className="block text-center">STATUS</span>,
        cell: (props) => (
          <div className="flex justify-center">
            <Badge
              className={`${
                props.row.original.is_active ? "bg-primary" : "bg-brownish"
              }`}
            >
              {props.row.original.is_active ? "Active" : "Inactive"}
            </Badge>
          </div>
        ),
      },
      {
        id: "action",
        header: () => <span className="block text-center">ACTION</span>,
        cell: (props) => (
          <div className="flex justify-center gap-5">
            <Link
              href={"user/manage-user/" + props.row.original.id}
              className="flex gap-2 items-center"
              onClick={(e) => {
                e.stopPropagation();
                console.log(props.row.original);
              }}
            >
              <span>
                <Pencil width={18} />
              </span>
              Edit
            </Link>
            <button
              className="flex gap-2 items-center"
              onClick={async (e) => {
                e.stopPropagation();
                const resp = await confirmModla(
                  "Are you sure you want to change user status?"
                );
                if (!resp) return;

                const method = props.row.original.is_active ? "delete" : "patch";
                const id = props.row.original.id;
                (e.target as HTMLElement).classList.toggle("loading");
                const endpoint = props.row.original.is_active ? "" : "reactivate/";
                await activateDeActivateUser(method, id, endpoint);
                (e.target as HTMLElement).classList.toggle("loading");
              }}
            >
              <span>
                <Trash2 width={18} />
              </span>
              {props.row.original.is_active ? "De-Activate" : "Re-Activate"}
            </button>
          </div>
        ),
      },
    ],
    []
  );

  return { columns };
}

export function getCustomerTableColumns(refetch: () => Promise<any>) {
  const columns: ColumnDef<CustomerDataT>[] = [
    {
      id: "select",
      header: ({ table }) => (
        <div className="flex justify-center">
          <IndeterminateCheckbox
            {...{
              checked: table.getIsAllRowsSelected(),
              indeterminate: table.getIsSomeRowsSelected(),
              onChange: table.getToggleAllRowsSelectedHandler(),
            }}
          />
        </div>
      ),
      cell: ({ row }) => (
        <div className="flex justify-center px-1">
          <IndeterminateCheckbox
            {...{
              checked: row.getIsSelected(),
              disabled: !row.getCanSelect(),
              indeterminate: row.getIsSomeSelected(),
              onChange: row.getToggleSelectedHandler(),
            }}
          />
        </div>
      ),
    },
    {
      id: "customer_id",
      accessorKey: "id",
      cell: (info) => info.getValue(),
      header: () => <span className="block text-center">CUSTOMER ID</span>,
    },
    {
      id: "name",
      cell: (props) => {
        const data = props.cell.row?.original;
        const displayTitle = data.title ? `${data.title}. ` : "";
        return <div className="text-center">{`${displayTitle}${data.first_name} ${data.last_name}`}</div>;
      },
      header: () => <span className="block text-center">NAME</span>,
    },
    {
      id: "status",
      header: () => <span className="block text-center">STATUS</span>,
      cell: (props) => {
        const customer = props.cell.row?.original;
        const status = customer.DNC ? "DNC" : "Active";
        return (
          <div className="flex justify-center">
            <Badge
              className={`${
                customer.DNC ? "bg-brownish" : "bg-primary"
              }`}
            >
              {status}
            </Badge>
          </div>
        );
      },
    },
    {
      id: "assigned_to",
      accessorKey: "assigned_to.user.name",
      header: () => <span className="block text-center">Assigned To</span>,
    },
    {
      id: "created_by",
      header: () => <span className="block text-center">Created By</span>,
      cell: (props) => {
        const createdBy = props.cell.row?.original.created_by;
        console.log("created_by value:", createdBy);
        let name = "Unknown";
        
        if (Array.isArray(createdBy)) {
          if (createdBy.length > 0) {
            name = createdBy[0]?.user?.name || "No Name";
          } else {
            name = "Empty Array";
          }
        } else if (createdBy && typeof createdBy === "object") {
          name = createdBy.user?.name || "No User Name";
        } else {
          name = "Invalid Data";
        }
        
        return <div className="text-center">{name}</div>;
      },
    },
    
    {
      id: "action",
      header: () => <span className="block text-center">ACTION</span>,
      cell: (props) => {
        const customer = props.row.original;
        // Get user data from store in the cell renderer
        const userData = useUserStore.getState().data;
        const currentUserId = getCurrentUserId(userData);
        const userRole = userData?.role;
        
        // Admin and Owner have access to all customers
        const isAdminOrOwner = userRole === 'Admin' || userRole === 'Owner';
        
        // Check if user has access (created by or assigned to current user, or is Admin/Owner)
        const isCreatedByUser = customer.created_by?.id === currentUserId;
        const isAssignedToUser = customer.assigned_to?.id === currentUserId;
        const hasAccess = isAdminOrOwner || isCreatedByUser || isAssignedToUser;
        
        if (!hasAccess) {
          // For customers without access, show limited view link only
          return (
            <div className="flex justify-center gap-5">
              <Link
                href={
                  "/customer/view-details/" +
                  customer.id +
                  "?firstName=" +
                  customer.first_name +
                  "&lastName=" +
                  customer.last_name
                }
                className="flex gap-2 items-center"
                onClick={(e) => {
                  e.stopPropagation();
                }}
              >
                {/* <span>
                  <Info width={18} />
                </span> */}
                
              </Link>
            </div>
          );
        }
        
        // For customers with access, show both Edit and View links
        return (
          <div className="flex justify-center gap-5">
            <Link
              href={
                "/customer/customer-manage/" +
                customer.id +
                "?firstName=" +
                customer.first_name +
                "&lastName=" +
                customer.last_name
              }
              className="flex gap-2 items-center"
              onClick={(e) => {
                e.stopPropagation();
                console.log(customer);
              }}
            >
              <span>
                <Pencil width={18} />
              </span>
              Edit
            </Link>
            {/* <Link
              href={
                "/customer/view-details/" +
                customer.id +
                "?firstName=" +
                customer.first_name +
                "&lastName=" +
                customer.last_name
              }
              className="flex gap-2 items-center"
              onClick={(e) => {
                e.stopPropagation();
                console.log(customer);
              }}
            >
              <span>
                <Info width={18} />
              </span>
              
            </Link> */}
          </div>
        );
      },
    },
    {
      id: "orders",
      header: () => <span className="block text-center">ORDERS</span>,
      cell: (props) => <OrdersCell customer={props.row.original} />,
    },
  ];

  return { columns };
}
// export const columnsUseMemo = React.useMemo<ColumnDef<UserListT>[]>(
//   () => [
//     {
//       id: "select",
//       header: ({ table }) => (
//         <Input
//           type="checkbox"
//           {...{
//             checked: table.getIsAllRowsSelected(),
//             indeterminate: table.getIsSomeRowsSelected(),
//             onChange: table.getToggleAllRowsSelectedHandler(),
//           }}
//         />
//         // <IndeterminateCheckbox
//         //   {...{
//         //     checked: table.getIsAllRowsSelected(),
//         //     indeterminate: table.getIsSomeRowsSelected(),
//         //     onChange: table.getToggleAllRowsSelectedHandler(),
//         //   }}
//         // />
//       ),
//       cell: ({ row }) => (
//         <div className="px-1" onClick={(e) => e.stopPropagation()}>
//           <Input
//             type="checkbox"
//             {...{
//               checked: row.getIsSelected(),
//               disabled: !row.getCanSelect(),
//               indeterminate: row.getIsSomeSelected(),
//               onChange: row.getToggleSelectedHandler(),
//             }}
//           />
//           {/* <IndeterminateCheckbox
//             {...{
//               checked: row.getIsSelected(),
//               disabled: !row.getCanSelect(),
//               indeterminate: row.getIsSomeSelected(),
//               onChange: row.getToggleSelectedHandler(),
//             }}
//           /> */}
//         </div>
//       ),
//     },

//     {
//       id: "name",
//       accessorKey: "user.name",
//       cell: (info) => info.getValue(),
//       // footer: (props) => props.column.id,
//       header: () => <span>NAME</span>,
//     },
//     {
//       // accessorFn: (row) => (row as any).stats.views,
//       id: "role",
//       accessorKey: "role.name",
//       cell: (info) => info.getValue() || "-",
//       header: () => <span>ROLE</span>,
//     },

//     {
//       id: "email",
//       accessorKey: "user.email",
//       header: () => "E-MAIL ID",
//     },

//     {
//       id: "report",
//       accessorKey: "reports_to.user.name",
//       cell: (info) => info.getValue() || "-",
//       header: () => <span>REPORTS TO</span>,
//     },
//     {
//       id: "last_login",
//       accessorKey: "user.last_login",
//       header: "LAST LOGIN",
//       cell: (info) =>
//         isValid(info.getValue())
//           ? format(info.getValue() as string, "dd-MM-yyyy hh:mm")
//           : info.getValue() + "",
//     },
//     {
//       id: "status",
//       accessorKey: "is_active",
//       header: "STATUS",
//       cell: (props) => {
//         return (
//           <Badge
//             className={`${
//               props.row.original.is_active ? "bg-primary" : "bg-danger"
//             }`}
//           >
//             {props.row.original.is_active ? "Active" : "Inactive"}
//           </Badge>
//         );
//       },
//     },

//     {
//       id: "action",
//       header: "ACTION",
//       cell(props) {
//         return (
//           <div className="flex gap-5">
//             <Link
//               href={"user/manage-user/" + props.row.original.id + ""}
//               className="flex gap-2 items-center"
//               onClick={(e) => {
//                 e.stopPropagation();
//                 console.log(props.row.original);
//               }}
//             >
//               <span>
//                 <Pencil width={18} />
//               </span>
//               Edit
//             </Link>

//             <button
//               className="flex gap-2 items-center "
//               onClick={async (e) => {
//                 e.stopPropagation();
//                 const resp = await confirmModla(
//                   "Are you sure you want to change user status?"
//                 );
//                 if (!resp) return;

//                 const method = props.row.original.is_active
//                   ? "delete"
//                   : "patch";
//                 const id = props.row.original.id;
//                 (e.target as HTMLElement).classList.toggle("loading");
//                 const endpoint = props.row.original.is_active
//                   ? ""
//                   : "reactivate/";
//                 // await activateDeActivateUser(method, id, endpoint);
//                 (e.target as HTMLElement).classList.toggle("loading");
//               }}
//             >
//               <span>
//                 <Trash2 width={18} />
//               </span>
//               {props.row.original.is_active ? "De-Activate" : "Re-Activate"}
//             </button>
//           </div>
//         );
//       },
//     },
//   ],
//   []
// );
