"use client";

import React, { useEffect, useState, useCallback, useRef } from "react";
import Link from "next/link";
import { warehouseShipmentService } from "../../../../services/api";
import { Shipment } from "../../../../types/shipment";
import {
  MdArrowBack,
  MdArrowForward,
  MdVisibility,
  MdSearch,
  MdFilterList,
  MdEvent,
  MdDescription,
  MdArrowUpward,
  MdArrowDownward,
} from "react-icons/md";
import { FiMoreVertical } from "react-icons/fi";
import { useRouter, useSearchParams } from "next/navigation";
import { debounce } from "lodash";
import FilterPopover from "./components/FilterPopover";
import DateFilterPopover from "./components/DateFilterPopover";
import ActionDropdown from "../../../../components/ui/ActionDropdown";
import { formatDate } from "../../../../utils/dateUtils";
import { getShipmentStatusLabelForRole, getShipmentStatusColorForRole } from "../../../../utils/roleStatusLabels";
import ShipmentStatusModal from "../../../../components/ui/ShipmentStatusModal";
import { PaginationMeta } from "@/types/pagination";

export default function WarehouseManageShipmentsPage() {
  const router = useRouter();
  const searchParams = useSearchParams();

  // Function to handle row click navigation
  const handleRowClick = (shipment: Shipment) => {
    router.push(`/warehouses/shipments/${shipment.id}`);
  };

  // Function to handle status badge click
  const handleStatusClick = (shipment: any, e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedShipment(shipment);
    setStatusModalOpen(true);
  };

  // Get initial values from URL query params
  const initialPage = Number(searchParams.get("page")) || 1;
  const initialLimit = Number(searchParams.get("limit")) || 10;
  const initialSearch = searchParams.get("search") || "";
  const initialStatus = searchParams.get("status") || null;
  const initialStartDate = searchParams.get("startDate") || null;
  const initialEndDate = searchParams.get("endDate") || null;
  const initialSortBy = searchParams.get("sortBy") || "createdAt";
  const initialSortOrder =
    (searchParams.get("sortOrder") as "ASC" | "DESC") || "DESC";

  const [shipments, setShipments] = useState<Shipment[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(initialPage);
  const [itemsPerPage, setItemsPerPage] = useState(initialLimit);
  const [searchQuery, setSearchQuery] = useState(initialSearch);
  const [filterStatus, setFilterStatus] = useState<string | null>(
    initialStatus
  );
  const [startDate, setStartDate] = useState<string | null>(initialStartDate);
  const [endDate, setEndDate] = useState<string | null>(initialEndDate);
  const [sortBy, setSortBy] = useState<string>(initialSortBy);
  const [sortOrder, setSortOrder] = useState<"ASC" | "DESC">(initialSortOrder);
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [isDateFilterOpen, setIsDateFilterOpen] = useState(false);
  const [openMenuId, setOpenMenuId] = useState<string | null>(null);
  const menuRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});

  // Modal state
  const [statusModalOpen, setStatusModalOpen] = useState(false);
  const [selectedShipment, setSelectedShipment] = useState<any>(null);

  const [paginationMeta, setPaginationMeta] = useState<PaginationMeta>({
    currentPage: initialPage,
    itemsPerPage: initialLimit,
    totalItems: 0,
    totalPages: 1,
    hasNextPage: false,
    hasPreviousPage: false,
  });

  // Update URL with current pagination and filter state
  const updateUrlParams = useCallback(() => {
    const params = new URLSearchParams();
    params.set("page", currentPage.toString());
    params.set("limit", itemsPerPage.toString());
    if (searchQuery) params.set("search", searchQuery);
    if (filterStatus) params.set("status", filterStatus);
    if (startDate) params.set("startDate", startDate);
    if (endDate) params.set("endDate", endDate);
    if (sortBy) params.set("sortBy", sortBy);
    if (sortOrder) params.set("sortOrder", sortOrder);

    // Update URL without refreshing the page
    router.push(`?${params.toString()}`, { scroll: false });
  }, [
    currentPage,
    itemsPerPage,
    searchQuery,
    filterStatus,
    startDate,
    endDate,
    sortBy,
    sortOrder,
    router,
  ]);

  // Fetch shipments with filters
  const fetchShipments = useCallback(async () => {
    try {
      setLoading(true);

      const response = await warehouseShipmentService.getAllShipments({
        page: currentPage,
        limit: itemsPerPage,
        search: searchQuery,
        status: filterStatus || undefined,
        startDate: startDate || undefined,
        endDate: endDate || undefined,
        sortBy,
        sortOrder,
      });

      // Handle both old and new API response formats
      if (response.data.data && response.data.meta) {
        // New paginated format
        setShipments(response.data.data);
        setPaginationMeta(response.data.meta);
      } else {
        // Old format - treat as single page
        setShipments(response.data);
        setPaginationMeta({
          currentPage: 1,
          itemsPerPage: response.data.length,
          totalItems: response.data.length,
          totalPages: 1,
          hasNextPage: false,
          hasPreviousPage: false,
        });
      }

      setError(null);

      // Update URL after successful fetch
      updateUrlParams();
    } catch (err) {
      console.error("Failed to fetch shipments:", err);
      setError("Failed to load shipments. Please try again.");
    } finally {
      setLoading(false);
    }
  }, [
    currentPage,
    itemsPerPage,
    searchQuery,
    filterStatus,
    startDate,
    endDate,
    sortBy,
    sortOrder,
    updateUrlParams,
  ]);

  // Debounced search handler
  const debouncedSearch = useCallback(
    debounce((value: string) => {
      setSearchQuery(value);
      setCurrentPage(1); // Reset to first page on new search
    }, 500),
    []
  );

  // Handle search input change
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    debouncedSearch(value);
  };

  // Handle filter toggle
  const handleFilterToggle = () => {
    setIsFilterOpen(!isFilterOpen);
  };

  // Handle date filter toggle
  const handleDateFilterToggle = () => {
    setIsDateFilterOpen(!isDateFilterOpen);
  };

  // Handle filter apply
  const handleFilterApply = ({ status }: { status: string | null }) => {
    setFilterStatus(status);
    setCurrentPage(1); // Reset to first page when applying filters
  };

  // Handle date filter apply
  const handleDateFilterApply = (start: string | null, end: string | null) => {
    setStartDate(start);
    setEndDate(end);
    setCurrentPage(1); // Reset to first page when applying date filters
  };

  // Handle sorting
  const handleSort = (field: string) => {
    if (sortBy === field) {
      // Toggle sort order if same field
      setSortOrder(sortOrder === "ASC" ? "DESC" : "ASC");
    } else {
      // Set new field with default DESC order
      setSortBy(field);
      setSortOrder("DESC");
    }
    setCurrentPage(1); // Reset to first page when sorting
  };

  // Handle pagination
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const handleItemsPerPageChange = (size: number) => {
    setItemsPerPage(size);
    setCurrentPage(1); // Reset to first page when changing page size
  };

  // Handle menu toggle
  const handleMenuToggle = (e: React.MouseEvent, id: string) => {
    e.preventDefault();
    e.stopPropagation();
    setOpenMenuId(openMenuId === id ? null : id);
  };

  const setMenuRef = (id: string, el: HTMLDivElement | null) => {
    menuRefs.current[id] = el;
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        openMenuId &&
        menuRefs.current[openMenuId] &&
        !menuRefs.current[openMenuId]?.contains(event.target as Node)
      ) {
        setOpenMenuId(null);
      }
    }

    if (openMenuId) {
      document.addEventListener("mousedown", handleClickOutside);
    }

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

  // Fetch shipments on component mount and when dependencies change
  useEffect(() => {
    fetchShipments();
  }, [fetchShipments]);

  const getFilterCount = () => {
    let count = 0;
    if (filterStatus) count++;
    return count;
  };

  const getDateFilterCount = () => {
    return startDate || endDate ? 1 : 0;
  };

  const startItem = (currentPage - 1) * itemsPerPage + 1;
  const endItem = Math.min(
    currentPage * itemsPerPage,
    paginationMeta.totalItems
  );

  return (
    <div className="warehouse-shipments-page">
      {/* Sticky Header */}
      <div className="sticky top-0 z-30 bg-gradient-to-l from-white to-[#DFF9FF] shadow-sm border-b border-gray-200 backdrop-blur-sm">
        <div className="px-4 md:px-6 py-4">
          <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center space-y-4 sm:space-y-0">
            <div>
              <h1 className="text-xl md:text-2xl font-bold text-gray-800">
                Manage Shipments
              </h1>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="m-4 md:m-6">
        {/* Single Card for Shipment List, Search/Filters, Table, and Pagination */}
        <div className="bg-white rounded-lg shadow-[0px_4px_34px_0px_rgba(0,59,113,0.16)]">
          {/* Shipment List Title */}
          <div className="px-6 py-4 border-b border-gray-200">
            <h2 className="text-lg font-bold text-gray-800">Shipment List</h2>
          </div>

          {/* Search and Filters */}
          <div className="p-4 md:p-6 flex flex-col md:flex-row justify-between items-center space-y-4 md:space-y-0 md:space-x-4">
            <div className="flex items-center bg-gray-100 p-2 rounded-md w-full md:w-1/3">
              <MdSearch size={20} color="#6B7280" className="mr-2" />
              <input
                type="text"
                placeholder="Search..."
                defaultValue={searchQuery}
                onChange={handleSearchChange}
                className="bg-transparent outline-none w-full text-sm text-gray-700 placeholder-gray-500"
              />
            </div>
            <div className="flex items-center space-x-4">
              <button
                className="flex items-center text-gray-600 hover:text-gray-800 text-sm bg-gray-100 p-2 rounded-md relative"
                onClick={handleFilterToggle}
              >
                <MdFilterList size={20} className="mr-2" />
                Filters
                {getFilterCount() > 0 && (
                  <span className="absolute -top-2 -right-2 bg-blue-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                    {getFilterCount()}
                  </span>
                )}
              </button>
              <button
                className="flex items-center text-gray-600 hover:text-gray-800 text-sm bg-gray-100 p-2 rounded-md relative"
                onClick={handleDateFilterToggle}
              >
                <MdEvent size={20} className="mr-2" />
                Date Filter
                {getDateFilterCount() > 0 && (
                  <span className="absolute -top-2 -right-2 bg-blue-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                    {getDateFilterCount()}
                  </span>
                )}
              </button>
            </div>
          </div>

          {loading ? (
            <div className="flex justify-center items-center h-40">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3"></div>
              <span>Loading shipments...</span>
            </div>
          ) : error ? (
            <div className="p-6 bg-red-100 text-red-700">
              <p className="font-medium">Error</p>
              <p>{error}</p>
            </div>
          ) : shipments.length === 0 ? (
            <div className="p-8 text-center">
              <MdDescription className="h-16 w-16 text-gray-300 mx-auto mb-4" />
              <p className="text-gray-500 text-lg">No shipments found</p>
              <p className="text-gray-400 text-sm mb-6">
                No shipments match your current filters.
              </p>
            </div>
          ) : (
            <div>
              {/* Desktop Table View */}
              <div className="hidden lg:block overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th
                        scope="col"
                        className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider"
                      >
                        Shipment #
                      </th>
                      <th
                        scope="col"
                        className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider"
                      >
                        <button
                          className="flex items-center space-x-1 hover:text-gray-900 focus:outline-none"
                          onClick={() => handleSort("shipmentDate")}
                        >
                          <span>Date</span>
                          <div className="flex flex-col">
                            <MdArrowUpward
                              size={12}
                              color={
                                sortBy === "shipmentDate" && sortOrder === "ASC"
                                  ? "#3997E0"
                                  : "#9CA3AF"
                              }
                            />
                            <MdArrowDownward
                              size={12}
                              color={
                                sortBy === "shipmentDate" &&
                                sortOrder === "DESC"
                                  ? "#3997E0"
                                  : "#9CA3AF"
                              }
                            />
                          </div>
                        </button>
                      </th>
                      <th
                        scope="col"
                        className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider"
                      >
                        Created By
                      </th>
                      <th
                        scope="col"
                        className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider"
                      >
                        Pallet
                      </th>
                      <th
                        scope="col"
                        className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider"
                      >
                        Status
                      </th>
                      <th
                        scope="col"
                        className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider"
                      ></th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {shipments.map((shipment, index) => (
                      <tr
                        key={shipment.id}
                        className={`${
                          index % 2 === 0 ? "bg-white" : "bg-[#F2F9FF]"
                        } hover:bg-gray-100 cursor-pointer transition-colors`}
                        onClick={() => handleRowClick(shipment)}
                      >
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                          <span className="font-medium">
                            {shipment.shipmentNumber}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                          {formatDate(shipment.shipmentDate)}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                          {shipment.actor?.firstname} {shipment.actor?.lastname}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                          {shipment.shipmentPallets?.length || 0} pallets
                        </td>
                        <td
                          className="px-6 py-4 whitespace-nowrap text-sm text-gray-700"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <div
                            onClick={(e) => handleStatusClick(shipment, e)}
                            className="cursor-pointer hover:opacity-80 transition-opacity"
                          >
                            <span
                              className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getShipmentStatusColorForRole(getShipmentStatusLabelForRole(shipment.status, 'admin'), 'admin')}`}
                            >
                              {getShipmentStatusLabelForRole(shipment.status, 'admin')}
                            </span>
                          </div>
                        </td>
                        <td
                          className="px-6 py-4 whitespace-nowrap text-sm text-gray-700"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <div className="text-center">
                            <ActionDropdown
                              actions={[
                                {
                                  id: "view",
                                  label: "View",
                                  icon: MdVisibility,
                                  href: `/warehouses/shipments/${shipment.id}`,
                                  onClick: () => {
                                    router.push(
                                      `/warehouses/shipments/${shipment.id}`
                                    );
                                  },
                                },
                              ]}
                              align="right"
                            />
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Mobile Card View */}
              <div className="lg:hidden space-y-4">
                {shipments.map((shipment, index) => (
                  <div
                    key={shipment.id}
                    className={`rounded-lg border cursor-pointer ${
                      index % 2 === 0 ? "bg-white" : "bg-[#F2F9FF]"
                    } hover:bg-gray-50 transition-colors`}
                    onClick={() => handleRowClick(shipment)}
                  >
                    {/* Mobile Card Info Section */}
                    <div className="p-4">
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex-1">
                          <div className="flex items-center justify-between mb-2">
                            <span className="font-semibold text-gray-900">
                              {shipment.shipmentNumber}
                            </span>
                            <div
                              onClick={(e) => {
                                e.stopPropagation();
                                handleStatusClick(shipment, e);
                              }}
                              className="cursor-pointer hover:opacity-80 transition-opacity"
                            >
                              <span
                                className={`px-2 py-1 text-xs font-semibold rounded-full ${getShipmentStatusColorForRole(getShipmentStatusLabelForRole(shipment.status, 'admin'), 'admin')}`}
                              >
                                {getShipmentStatusLabelForRole(shipment.status, 'admin')}
                              </span>
                            </div>
                          </div>
                        </div>
                        <div
                          className="ml-3"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <ActionDropdown
                            actions={[
                              {
                                id: "view",
                                label: "View & Scan",
                                icon: MdVisibility,
                                href: `/warehouses/shipments/${shipment.id}`,
                                onClick: () => {
                                  router.push(
                                    `/warehouses/shipments/${shipment.id}`
                                  );
                                },
                              },
                            ]}
                            align="right"
                          />
                        </div>
                      </div>
                      <div className="space-y-2">
                        <div className="text-sm text-gray-600">
                          <span className="font-medium">Date:</span>{" "}
                          {formatDate(shipment.shipmentDate)}
                        </div>
                        <div className="text-sm text-gray-600">
                          <span className="font-medium">Created By:</span>{" "}
                          {shipment.actor?.firstname} {shipment.actor?.lastname}
                        </div>
                        <div className="text-sm text-gray-600">
                          <span className="font-medium">Pallet:</span>{" "}
                          {shipment.shipmentPallets?.length || 0} pallets
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {/* Pagination - Responsive */}
              <div className="px-4 lg:px-6 py-4 border-t border-gray-200">
                {/* Mobile Pagination */}
                <div className="lg:hidden space-y-4">
                  <div className="flex justify-between items-center text-sm text-gray-600">
                    <div className="flex items-center space-x-2">
                      <select
                        value={itemsPerPage}
                        onChange={(e) =>
                          handleItemsPerPageChange(Number(e.target.value))
                        }
                        className="border border-gray-300 rounded-md px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white text-sm"
                      >
                        <option value={10}>10</option>
                        <option value={20}>20</option>
                        <option value={50}>50</option>
                      </select>
                      <span className="text-xs">per page</span>
                    </div>
                    <span className="text-xs">
                      {paginationMeta.totalItems === 0
                        ? "0-0 of 0"
                        : `${startItem}-${endItem} of ${paginationMeta.totalItems}`}
                    </span>
                  </div>

                  <div className="flex justify-between items-center">
                    <button
                      onClick={() => handlePageChange(currentPage - 1)}
                      disabled={currentPage <= 1}
                      className="flex items-center px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <MdArrowBack size={16} className="mr-1" />
                      Previous
                    </button>

                    <div className="flex items-center space-x-2">
                      <select
                        value={currentPage}
                        onChange={(e) =>
                          handlePageChange(Number(e.target.value))
                        }
                        className="border border-gray-300 rounded-md px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white"
                      >
                        {Array.from(
                          { length: paginationMeta.totalPages },
                          (_, i) => i + 1
                        ).map((page) => (
                          <option key={page} value={page}>
                            {page}
                          </option>
                        ))}
                      </select>
                      <span className="text-sm text-gray-600">
                        of {paginationMeta.totalPages}
                      </span>
                    </div>

                    <button
                      onClick={() => handlePageChange(currentPage + 1)}
                      disabled={currentPage >= paginationMeta.totalPages}
                      className="flex items-center px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Next
                      <MdArrowForward size={16} className="ml-1" />
                    </button>
                  </div>
                </div>

                {/* Desktop Pagination */}
                <div className="hidden lg:flex justify-between items-center text-sm text-gray-600">
                  <div className="flex items-center">
                    <select
                      value={itemsPerPage}
                      onChange={(e) =>
                        handleItemsPerPageChange(Number(e.target.value))
                      }
                      className="border border-gray-300 rounded-md px-2 py-1 mr-2 focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white"
                    >
                      <option value={10}>10</option>
                      <option value={20}>20</option>
                      <option value={50}>50</option>
                    </select>
                    <span>Items per page</span>
                    <span className="ml-4">
                      {paginationMeta.totalItems === 0
                        ? "0-0 of 0"
                        : `${startItem}-${endItem} of ${paginationMeta.totalItems} items`}
                    </span>
                  </div>

                  <div className="flex items-center">
                    <div className="flex items-center mr-4">
                      <select
                        value={currentPage}
                        onChange={(e) =>
                          handlePageChange(Number(e.target.value))
                        }
                        className="border border-gray-300 rounded-md px-2 py-1 mr-1 focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white"
                      >
                        {Array.from(
                          { length: paginationMeta.totalPages },
                          (_, i) => i + 1
                        ).map((page) => (
                          <option key={page} value={page}>
                            {page}
                          </option>
                        ))}
                      </select>
                      <span>of {paginationMeta.totalPages} pages</span>
                    </div>
                    <button
                      onClick={() => handlePageChange(currentPage - 1)}
                      disabled={currentPage <= 1}
                      className="p-1 rounded-md hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed leading-[0]"
                    >
                      <MdArrowBack size={20} />
                    </button>
                    <button
                      onClick={() => handlePageChange(currentPage + 1)}
                      disabled={currentPage >= paginationMeta.totalPages}
                      className="p-1 rounded-md hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed leading-[0]"
                    >
                      <MdArrowForward size={20} />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Filter Popover */}
      <FilterPopover
        isOpen={isFilterOpen}
        onClose={() => setIsFilterOpen(false)}
        onApply={handleFilterApply}
        initialFilters={{
          status: filterStatus,
        }}
      />

      {/* Date Filter Popover */}
      <DateFilterPopover
        isOpen={isDateFilterOpen}
        onClose={() => setIsDateFilterOpen(false)}
        onApply={handleDateFilterApply}
        initialStartDate={startDate}
        initialEndDate={endDate}
      />

      {/* Shipment Status Modal */}
      {selectedShipment && (
        <ShipmentStatusModal
          isOpen={statusModalOpen}
          onClose={() => {
            setStatusModalOpen(false);
            setSelectedShipment(null);
          }}
          shipmentId={selectedShipment.id}
          shipmentNumber={selectedShipment.shipmentNumber}
        />
      )}
    </div>
  );
}
