"use client";
import { useState, useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  setOpenActionMenu,
  closeActionMenu,
  setViewCustomer,
} from "@/src/redux/appActions";
import { RootState } from "@/src/redux/store";
import { Input } from "@/components/ui/input";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { MoreHorizontal, Search, CheckCircle2, XCircle } from "lucide-react";
import Image from "next/image";
import { Customer } from "@/src/utils/types";
import { usePathname } from "next/navigation";
import Popup from "./popup";
import {
  useGetCustomers,
  useGetDeletedCustomers,
} from "@/src/utils/hooks/useGetAdmindashboardStats";
import { Button } from "@/components/ui/button";
import SectionSkeleton from "./Loading";
import { useGetUserBioData } from "@/src/utils/hooks/useGetBioData";

export default function CustomerList() {
  const dispatch = useDispatch();
  const openActionMenuId = useSelector(
    (state: RootState) => state.counter.openActionMenuId
  );
  const [customers, setCustomers] = useState<Customer[] | null>(null);
  const [unFilteredCustomers, setUnFilteredCustomers] = useState<
    Customer[] | null
  >(null);
  const [searchTerm, setSearchTerm] = useState<string>("");
  const [openPop, setOpenPop] = useState<boolean>(false);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [totalPages, setTotalPages] = useState<number>(1);
  const [dataFetchLoading, setDataFetchLoading] = useState<boolean>(false);
  const [dropdownDirection, setDropdownDirection] = useState<"up" | "down">(
    "down"
  );

  const pathname = usePathname();

  const { data, isLoading, refetch } = useGetCustomers(currentPage);

  const {
    data: deletedCustomers,
    isLoading: deletedCustomersLoading,
    refetch: deletedCustomersRefetch,
  } = useGetDeletedCustomers(currentPage);

  const shouldShowPagination = () => {
    const currentPayload = pathname.includes("customers")
      ? data?.payload
      : deletedCustomers?.payload;

    return (
      currentPayload &&
      (currentPayload.prev_page_url !== null ||
        currentPayload.next_page_url !== null ||
        currentPayload.last_page > 1)
    );
  };

  useEffect(() => {
    if (pathname.includes("customers")) {
      setDataFetchLoading(isLoading);
    } else if (pathname.includes("deleted-accounts")) {
      setDataFetchLoading(deletedCustomersLoading);
    } else {
      setDataFetchLoading(false);
    }
  }, [isLoading, pathname, deletedCustomersLoading]);

  useEffect(() => {
    if (pathname.includes("customers")) {
      if (data && data?.payload) {
        const transformedData = data.payload.data.map((customer: any) => ({
          id: customer.id,
          name: customer.name || "N/A",
          phoneNumber: customer.phone_number || "N/A",
          email: customer.email,
          subscribedAccounts: customer.subscribe_account_count,
          avatar: "/images/avatar-placeholder.svg",
          isAddressVerified: customer.is_address_verified,
        }));

        setCustomers(transformedData);
        setUnFilteredCustomers(transformedData);
        setTotalPages(data.payload.last_page);
      }
    } else if (pathname.includes("deleted-accounts")) {
      if (deletedCustomers && deletedCustomers?.payload) {
        const transformedData = deletedCustomers.payload.data.map(
          (customer: any, index: number) => ({
            id: customer.id + (currentPage - 1) * 15,
            name: customer.name || "N/A",
            phoneNumber: customer.phone_number || "N/A",
            email: customer.email,
            subscribedAccounts: customer.subscribe_account_count,
            avatar: "/images/avatar-placeholder.svg",
            isAddressVerified: customer.is_address_verified,
          })
        );

        setCustomers(transformedData);
        setUnFilteredCustomers(transformedData);
        setTotalPages(deletedCustomers.payload.last_page);
      }
    } else {
      return;
    }
  }, [data, deletedCustomers, currentPage]);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    if (pathname.includes("customers")) {
      refetch();
    } else if (pathname.includes("deleted-accounts")) {
      deletedCustomersRefetch();
    } else {
      return;
    }
  };

  const dropdownRef = useRef<HTMLTableCellElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        dispatch(closeActionMenu());
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [dispatch]);

  useEffect(() => {
    if (searchTerm && unFilteredCustomers) {
      const filtered = unFilteredCustomers.filter(
        (customer) =>
          customer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          customer.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
          customer.phoneNumber.toString().includes(searchTerm)
      );
      setCustomers(filtered);
    } else {
      setCustomers(unFilteredCustomers);
    }
  }, [searchTerm, unFilteredCustomers]);

  const handleView = (customer: Customer) => {
    console.log("Viewing customer:", customer);
    dispatch(setViewCustomer(customer));
    dispatch(closeActionMenu());
  };

  const handleVerifyAddress = (customerId: number) => {
    if (customers) {
      const customer = customers.find((c) => c.id === customerId);
      console.log(`Verify address for customer:`, customer);
      setOpenPop(true);
      dispatch(closeActionMenu());
    }
  };

  const handleDelete = (customerId: number) => {
    if (customers) {
      const customer = customers.find((c) => c.id === customerId);
      console.log(`Delete customer:`, customer);
      dispatch(closeActionMenu());
    }
  };

  if (dataFetchLoading) {
    return (
      <div className="w-full">
        <SectionSkeleton />
      </div>
    );
  }

  return (
    <div className="w-full">
      <div className="flex md:flex-nowrap flex-wrap justify-between md:items-center gap-y-4 mb-6">
        <h1 className="text-2xl font-semibold text-[16px] text-black">
          {pathname.includes("deleted-accounts")
            ? "Deleted customers"
            : "Customer List"}
        </h1>
        <div className="relative w-full md:w-64">
          <Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-500" />
          <Input
            placeholder="Search customers"
            className="pl-8 pr-4"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
      </div>

      <div className="overflow-x-auto text-[#00000099] text-[12px]">
        <table className="w-full border-collapse">
          <thead className="font-semibold text-[12px]">
            <tr className="border-b border-gray-200">
              <th className="py-4 px-2 md:px-4 text-left w-8 md:w-12">#</th>
              <th className="py-4 px-2 md:px-4 text-left">Name</th>
              <th className="py-4 px-2 md:px-4 text-left hidden sm:table-cell">
                Phone Number
              </th>
              <th className="py-4 px-2 md:px-4 text-left hidden md:table-cell">
                Email address
              </th>
              <th className="py-4 px-2 md:px-4 text-left hidden lg:table-cell">
                Subscribed accounts
              </th>
              <th className="py-4 px-2 md:px-4 text-left hidden xl:table-cell">
                Address Verified
              </th>
              {!pathname.includes("/deleted-accounts") && (
                <th className="py-4 px-2 md:px-4 text-center">Action</th>
              )}
            </tr>
          </thead>
          <tbody>
            {customers && customers.length > 0 ? (
              customers.map((customer, index) => {
                const isLast = index === customers.length - 1;

                return (
                  <tr
                    key={customer.id}
                    className={`border-b border-gray-200 ${
                      index % 2 === 0 ? "bg-white" : "bg-gray-50"
                    }`}
                  >
                    <td className="py-3 px-2 md:px-4">{index + 1}</td>
                    <td className="py-3 px-2 md:px-4 text-black text-[13px] font-semibold">
                      <div className="flex items-center">
                        <span className="truncate">{customer.name}</span>
                      </div>
                    </td>
                    <td className="py-3 px-2 md:px-4 hidden sm:table-cell">
                      {customer.phoneNumber}
                    </td>
                    <td className="py-3 px-2 md:px-4 hidden md:table-cell">
                      {customer.email}
                    </td>
                    <td className="py-3 px-2 md:px-4 hidden lg:table-cell">
                      {customer.subscribedAccounts}
                    </td>
                    <td className="py-3 px-2 md:px-4 hidden xl:table-cell">
                      <div className="flex items-center justify-start">
                        {customer.isAddressVerified ? (
                          <CheckCircle2 className="h-4 w-4 text-green-500 mr-1" />
                        ) : (
                          <XCircle className="h-4 w-4 text-red-500 mr-1" />
                        )}
                        <span>
                          {customer.isAddressVerified
                            ? "Verified"
                            : "Not Verified"}
                        </span>
                      </div>
                    </td>
                    {!pathname.includes("/deleted-accounts") && (
                      <td className="py-3 px-2 md:px-4 relative text-center">
                        <button
                          className="focus:outline-none cursor-pointer text-[#16166C]"
                          onClick={() => {
                            if (openActionMenuId === customer.id) {
                              dispatch(closeActionMenu());
                            } else {
                              dispatch(setOpenActionMenu(customer.id));
                            }
                          }}
                        >
                          <MoreHorizontal
                            className="h-5 w-5 text-gray-500 mx-auto"
                            color="#2D9CDB"
                          />
                        </button>

                        {openActionMenuId === customer.id && (
                          <div
                            className={`w-20 absolute right-4 ${
                              isLast ? "bottom-10" : "top-10"
                            } bg-white hover:bg-gray-100 cursor-pointer border rounded-md shadow-md z-50 py-1 px-2`}
                            ref={dropdownRef}
                          >
                            <button
                              onClick={() => handleView(customer)}
                              className="w-full text-left px-2 py-1 text-sm hover:bg-gray-100 cursor-pointer"
                            >
                              View
                            </button>
                          </div>
                        )}
                      </td>
                    )}
                  </tr>
                );
              })
            ) : (
              <tr>
                <td colSpan={7} className="py-4 text-center">
                  No customers found
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {shouldShowPagination() && (
        <div className="flex flex-wrap justify-center mt-4 gap-2 px-2">
          {(() => {
            const currentPayload = pathname.includes("customers")
              ? data?.payload
              : deletedCustomers?.payload;

            return (
              <>
                <Button
                  variant="outline"
                  size="sm"
                  disabled={!currentPayload?.prev_page_url}
                  onClick={() => handlePageChange(currentPage - 1)}
                  className="text-xs sm:text-sm cursor-pointer"
                >
                  Previous
                </Button>

                {/* Mobile View - Only show current page */}
                <div className="sm:hidden flex items-center">
                  <Button
                    variant="default"
                    size="sm"
                    className="text-xs bg-[#16166C] hover:bg-[#16166c]/85"
                  >
                    {currentPayload?.current_page} of{" "}
                    {currentPayload?.last_page}
                  </Button>
                </div>

                {/* Tablet/Desktop View */}
                <div className="hidden sm:flex items-center gap-x-1">
                  {/* Show first page button if not in first few pages */}
                  {currentPage > 2 && totalPages > 3 && (
                    <>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handlePageChange(1)}
                        className="text-xs sm:text-sm cursor-pointer"
                      >
                        1
                      </Button>
                      {currentPage > 3 && (
                        <span className="px-1 self-center">...</span>
                      )}
                    </>
                  )}

                  {/* Show pages around current page */}
                  {Array.from({ length: Math.min(3, totalPages) }, (_, i) => {
                    let pageNum;

                    if (totalPages <= 3) {
                      pageNum = i + 1;
                    } else if (currentPage === 1) {
                      pageNum = i + 1;
                    } else if (currentPage === totalPages) {
                      pageNum = totalPages - 2 + i;
                    } else {
                      pageNum = currentPage - 1 + i;
                    }

                    return pageNum > 0 && pageNum <= totalPages ? (
                      <Button
                        key={pageNum}
                        variant={
                          currentPage === pageNum ? "default" : "outline"
                        }
                        size="sm"
                        onClick={() => handlePageChange(pageNum)}
                        className={`text-xs sm:text-sm cursor-pointer ${
                          currentPage === pageNum
                            ? "bg-[#16166C] hover:bg-[#16166c]/85"
                            : "bg-white"
                        }`}
                      >
                        {pageNum}
                      </Button>
                    ) : null;
                  })}

                  {/* Show last page button if not in last few pages */}
                  {currentPage < totalPages - 1 && totalPages > 3 && (
                    <>
                      {currentPage < totalPages - 2 && (
                        <span className="px-1 self-center">...</span>
                      )}
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handlePageChange(totalPages)}
                        className="text-xs sm:text-sm cursor-pointer"
                      >
                        {totalPages}
                      </Button>
                    </>
                  )}
                </div>

                {/* Next button - only show if there's actually a next page */}
                {currentPayload?.next_page_url && (
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={currentPage === totalPages}
                    onClick={() => handlePageChange(currentPage + 1)}
                    className="text-xs sm:text-sm cursor-pointer"
                  >
                    Next
                  </Button>
                )}
              </>
            );
          })()}
        </div>
      )}

      <Popup
        isOpen={openPop}
        onClose={() => setOpenPop(false)}
        title="Verify Physical Address"
        message="Are you sure you want to verify this user's physical address?
          Proceeding with this action means this user address has been checked
          and accredited."
      />
    </div>
  );
}
