// File Path: monorepo/web/frontend/src/pages/Admin/Division/List/Page.jsx

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate, useLocation } from "react-router";
import {
  useDivisionManager,
  useAuthManager
} from "../../../../services/Services";
import {
  BuildingOffice2Icon,
  PlusIcon,
  ArrowLeftIcon,
  HomeIcon,
  EnvelopeIcon,
  MapPinIcon,
  Squares2X2Icon,
  TableCellsIcon,
  MagnifyingGlassIcon,
} from "@heroicons/react/24/outline";
import {
  DataList,
  Breadcrumb,
  Button,
  useUIXTheme,
  DetailPageIcon,
  ViewButton,
  UIXThemeProvider,
  Badge,
  SearchFilter,
} from "../../../../components/UIX";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  DIVISION_TYPE_LABELS,
} from "../../../../constants/Division";

// Division status filter options
const DIVISION_STATUS_FILTER_OPTIONS = [
  { value: "0", label: "All Status" },
  { value: "1", label: "Active" },
  { value: "2", label: "Archived" },
];

// Division type filter options
const DIVISION_TYPE_FILTER_OPTIONS = [
  { value: "0", label: "All Types" },
  { value: "educational", label: "Educational" },
  { value: "corporate", label: "Corporate" },
  { value: "non-profit", label: "Non-Profit" },
  { value: "government", label: "Government" },
];

// Division sort options
const DIVISION_SORT_OPTIONS = [
  { value: "name,ASC", label: "Name (A-Z)" },
  { value: "name,DESC", label: "Name (Z-A)" },
  { value: "created_at,DESC", label: "Recently Created" },
  { value: "created_at,ASC", label: "Oldest Created" },
];


const VIEW_TYPE_TABULAR = "tabular";
const VIEW_TYPE_GRID = "grid";

function AdminDivisionListPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const divisionManager = useDivisionManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

  // Component state
  const [divisionList, setDivisionList] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [successMessage, setSuccessMessage] = useState("");

  // Pagination state (cursor-based)
  const [pageSize, setPageSize] = useState(25);
  const [previousCursors, setPreviousCursors] = useState([]);
  const [currentCursor, setCurrentCursor] = useState("");
  const [nextCursor, setNextCursor] = useState("");
  const [viewType, setViewType] = useState(VIEW_TYPE_GRID);

  // Filter state
  const [sortBy, setSortBy] = useState("name");
  const [sortOrder, setSortOrder] = useState("ASC");
  const [status, setStatus] = useState("1"); // Default to active
  const [type, setType] = useState("0"); // All types
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");

  // Force refresh counter
  const [refreshCounter, setRefreshCounter] = useState(0);

  // Handle unauthorized access
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Fetch divisions using the manager
  const fetchDivisionList = useCallback(
    (forceRefresh = false) => {
      if (!authManager.isAuthenticated()) {
        navigate("/login");
        return;
      }

      setIsLoading(true);
      setErrors({});

      // Build params object for the API
      const params = {};
      params.limit = pageSize;

      // Add cursor for pagination
      if (currentCursor) {
        params.cursor = currentCursor;
      }

      // Add sorting
      if (sortBy && sortOrder) {
        params.sortBy = sortBy;
        params.sortOrder = sortOrder;
      }

      // Add filters
      if (status !== "0") {
        params.status = parseInt(status);
      }

      if (type !== "0") {
        params.type = type;
      }

      if (searchQuery && searchQuery.trim()) {
        params.search = searchQuery.trim();
      }

      // Use the manager to fetch divisions
      divisionManager.getDivisionsWithCallbacks(
        params,
        onFetchSuccess,
        onFetchError,
        onFetchDone,
        onUnauthorized,
        forceRefresh,
      );
    },
    [currentCursor, pageSize, sortBy, sortOrder, status, type, searchQuery],
  );

  const onFetchSuccess = (response) => {
    setDivisionList(response);

    // Update pagination state
    if (response.hasNextPage) {
      setNextCursor(response.nextCursor);
    } else {
      setNextCursor("");
    }
  };

  const onFetchError = (error) => {
    setErrors(error);
  };

  const onFetchDone = () => {
    setIsLoading(false);
  };

  // Pagination handlers
  const handlePageChange = (direction) => {
    if (direction === "next" && nextCursor) {
      const newPreviousCursors = [...previousCursors];
      newPreviousCursors.push(currentCursor);
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(nextCursor);
    } else if (direction === "previous" && previousCursors.length > 0) {
      const newPreviousCursors = [...previousCursors];
      const previousCursor = newPreviousCursors.pop();
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(previousCursor);
    }
  };

  // Search handler
  const handleSearch = () => {
    setSearchQuery(tempSearchQuery);
    // Reset pagination when search changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
    setRefreshCounter((prev) => prev + 1);
  };

  // Filter change handlers
  const handleSortChange = (value) => {
    const [field, order] = value.split(",");
    setSortBy(field);
    setSortOrder(order);
    // Reset pagination when sort changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
    setRefreshCounter((prev) => prev + 1);
  };

  const handleStatusChange = (value) => {
    setStatus(value);
    // Reset pagination when status changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
    setRefreshCounter((prev) => prev + 1);
  };

  const handleTypeChange = (value) => {
    setType(value);
    // Reset pagination when type changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
    setRefreshCounter((prev) => prev + 1);
  };

  const handlePageSizeChange = (value) => {
    setPageSize(value);
    // Reset pagination when page size changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
    setRefreshCounter((prev) => prev + 1);
  };

  // Clear filters
  const handleClearFilters = () => {
    setSortBy("name");
    setSortOrder("ASC");
    setStatus("1");
    setType("0");
    setSearchQuery("");
    setTempSearchQuery("");
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
    setRefreshCounter((prev) => prev + 1);
  };

  // Get badge component for division type
  const getTypeBadge = (divisionType) => {
    // Map division types to badge variants
    const variantMap = {
      educational: "primary",
      corporate: "secondary",
      "non-profit": "info",
      government: "warning",
    };
    const variant = variantMap[divisionType] || "default";

    return (
      <Badge variant={variant} size="sm">
        {DIVISION_TYPE_LABELS[divisionType] || "Unknown"}
      </Badge>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Name",
      accessor: "name",
      type: "link",
      linkPath: "/admin/division/:id",
      render: (value, division) => {
        const displayName = division.divisionName || division.name;
        return displayName;
      }
    },
    {
      header: "Type",
      accessor: "divisionType",
      render: (type, division) => getTypeBadge(type || division.type)
    },
    {
      header: "Contact Name",
      accessor: "contacts",
      render: (contacts) => {
        if (!contacts || !Array.isArray(contacts) || contacts.length === 0) {
          return "-";
        }
        // Look for primary contact first, otherwise use first contact
        const primaryContact = contacts.find(contact => contact.isPrimary);
        const contact = primaryContact || contacts[0];
        const contactName = `${contact.firstName || ''} ${contact.lastName || ''}`.trim();
        return contactName || "-";
      }
    },
    {
      header: "Actions",
      align: "right",
      render: (value, division) => (
        <ViewButton
          to={`/admin/division/${division.id}`}
          text="View Division"
        />
      )
    }
  ];

  // Search filter configuration
  const searchFilterConfig = {
    searchTerm: searchQuery,
    tempSearchTerm: tempSearchQuery,
    onSearchTermChange: setTempSearchQuery,
    onSearch: handleSearch,
    searchPlaceholder: "Search divisions by name, email, or location...",
    statusOptions: DIVISION_STATUS_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: DIVISION_TYPE_FILTER_OPTIONS.map(opt => ({
      value: opt.value === "" ? "0" : opt.value,
      label: opt.label
    })),
    typeFilter: type,
    onTypeFilterChange: handleTypeChange,
    sortOptions: DIVISION_SORT_OPTIONS,
    sortValue: `${sortBy},${sortOrder}`,
    onSortChange: handleSortChange,
    pageSizeOptions: PAGE_SIZE_OPTIONS.map(opt => ({
      value: opt.value,
      label: opt.label
    })),
    pageSize,
    onPageSizeChange: handlePageSizeChange,
    onClearFilters: handleClearFilters,
    onRefresh: () => fetchDivisionList(true)
  };

  // Pagination configuration (cursor-based)
  const paginationConfig = {
    currentPage: previousCursors.length + 1,
    totalCount: divisionList?.count || 0,
    hasNextPage: !!nextCursor,
    onPageChange: (direction) => {
      if (direction > previousCursors.length + 1) {
        handlePageChange("next");
      } else {
        handlePageChange("previous");
      }
    }
  };

  // Empty state configuration
  const emptyStateConfig = {
    icon: BuildingOffice2Icon,
    title: "No Divisions Found",
    description: searchQuery || status !== "1" || type !== "0"
      ? "No divisions match your current filters. Try adjusting your search criteria."
      : "No divisions have been added yet.",
    actionLabel: "Add Division",
    onActionClick: () => navigate("/admin/divisions/add/step-1-search"),
    isCreateAction: true
  };

  // Initial load effect
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    setIsLoading(true);
    setErrors({});

    // Build params object for the API
    const params = {};
    params.limit = pageSize;

    // Add sorting
    if (sortBy && sortOrder) {
      const [sortField, sortOrder2] = `${sortBy},${sortOrder}`.split(",");
      params.sortBy = sortField;
      params.sortOrder = sortOrder2;
    }

    // Add filters
    if (status !== "0") {
      params.status = parseInt(status);
    }

    if (type !== "0") {
      params.type = type;
    }

    // Use the manager to fetch divisions with force refresh flag
    divisionManager.getDivisionsWithCallbacks(
      params,
      onFetchSuccess,
      onFetchError,
      onFetchDone,
      onUnauthorized,
      true,
    );
  }, []);

  // Effect for filter changes and pagination
  useEffect(() => {
    if (refreshCounter > 0 || currentCursor) {
      setIsLoading(true);
      setErrors({});

      // Build params object for the API
      const params = {};
      params.limit = pageSize;

      // Add cursor for pagination
      if (currentCursor) {
        params.cursor = currentCursor;
      }

      // Add sorting
      if (sortBy && sortOrder) {
        const [sortField, sortOrder2] = `${sortBy},${sortOrder}`.split(",");
        params.sortBy = sortField;
        params.sortOrder = sortOrder2;
      }

      // Add filters
      if (status !== "0") {
        params.status = parseInt(status);
      }

      if (type !== "0") {
        params.type = type;
      }

      if (searchQuery && searchQuery.trim()) {
        params.search = searchQuery.trim();
      }

      // Use the manager to fetch divisions with force refresh flag
      divisionManager.getDivisionsWithCallbacks(
        params,
        onFetchSuccess,
        onFetchError,
        onFetchDone,
        onUnauthorized,
        true,
      );
    }
  }, [
    currentCursor,
    pageSize,
    sortBy,
    sortOrder,
    status,
    type,
    searchQuery,
    refreshCounter,
  ]);

  // Handle success message from navigation state
  useEffect(() => {
    if (location.state?.successMessage) {
      setSuccessMessage(location.state.successMessage);
      window.history.replaceState({}, document.title);
      setTimeout(() => setSuccessMessage(""), 3000);
    }
  }, [location]);

  return (
    <UIXThemeProvider>
      <>
        {/* Breadcrumb */}
        <Breadcrumb items={[
          {
            label: 'Dashboard',
            to: '/admin/dashboard',
            icon: HomeIcon
          },
          {
            label: 'Divisions',
            icon: BuildingOffice2Icon,
            isActive: true
          }
        ]} />

        {/* Conditional Rendering: DataList for table view, Custom Grid for card view */}
      {viewType === VIEW_TYPE_TABULAR ? (
        <DataList
          data={divisionList?.results || []}
          columns={columns}
          isLoading={isLoading}
          errors={errors}
          successMessage={successMessage}
          onSuccessMessageClose={() => setSuccessMessage("")}
          searchFilter={searchFilterConfig}
          pagination={paginationConfig}
          emptyState={emptyStateConfig}
          header={{
            icon: BuildingOffice2Icon,
            title: "Division Management",
            showHeader: true,
            subtitle: "Manage your organization's divisions and their information",
            decorativeIcon: <DetailPageIcon icon={BuildingOffice2Icon} />,
            actions: [
              <div key="view-toggle" className="flex items-center gap-1">
                <Button
                  variant={viewType === VIEW_TYPE_TABULAR ? "primary" : "ghost"}
                  onClick={() => setViewType(VIEW_TYPE_TABULAR)}
                  size="sm"
                >
                  <TableCellsIcon className="w-5 h-5" />
                </Button>
                <Button
                  variant={viewType === VIEW_TYPE_GRID ? "primary" : "ghost"}
                  onClick={() => setViewType(VIEW_TYPE_GRID)}
                  size="sm"
                >
                  <Squares2X2Icon className="w-5 h-5" />
                </Button>
              </div>,
              <Button
                key="search"
                variant="secondary"
                size="md"
                onClick={() => navigate("/admin/divisions/search")}
                icon={MagnifyingGlassIcon}
              >
                Advanced Search
              </Button>,
              <Button
                key="add"
                variant="success"
                size="lg"
                onClick={() => navigate("/admin/divisions/add/step-1-search")}
                icon={PlusIcon}
              >
                Add Division
              </Button>
            ]
          }}
        />
      ) : (
        /* Standalone Grid View - Exactly matching DataList structure */
        <div className={`min-h-screen ${getThemeClasses('bg-gradient-primary')}`}>
          {/* Decorative background elements */}
          <div className="fixed inset-0 overflow-hidden pointer-events-none">
            <div className="absolute -top-40 -right-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob"></div>
            <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-yellow-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000"></div>
            <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000"></div>
          </div>

          <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
            {/* Success Message */}
            {successMessage && (
              <div className={`mb-6 sm:mb-8 p-4 ${getThemeClasses('success-bg')} border ${getThemeClasses('success-border')} rounded-lg flex items-center`}>
                <span className={`text-sm ${getThemeClasses('success-text')}`}>{successMessage}</span>
                <button
                  onClick={() => setSuccessMessage("")}
                  className={`ml-auto ${getThemeClasses('success-text')} hover:opacity-75`}
                >
                  ×
                </button>
              </div>
            )}

            {/* Main Content Layout - Centered */}
            <div className="max-w-7xl mx-auto">
              <div className="bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100 hover:shadow-2xl transition-shadow duration-300">

                {/* Header Section - Inside the white card */}
                <div className={`px-6 sm:px-8 py-6 border-b ${getThemeClasses('border-secondary')}`}>
                  <div className="flex flex-col space-y-4 lg:flex-row lg:items-start lg:justify-between lg:space-y-0">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start">
                        <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${getThemeClasses('bg-gradient-secondary')}`}>
                          <BuildingOffice2Icon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                        </div>
                        <div className="text-center lg:text-left">
                          <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses('text-primary')} leading-tight`}>
                            Division Management
                          </h1>
                        </div>
                      </div>
                    </div>
                    <div className="flex-shrink-0 flex items-center gap-3">
                      <div className="flex items-center gap-1">
                        <Button
                          variant={viewType === VIEW_TYPE_TABULAR ? "primary" : "ghost"}
                          onClick={() => setViewType(VIEW_TYPE_TABULAR)}
                          size="sm"
                        >
                          <TableCellsIcon className="w-5 h-5" />
                        </Button>
                        <Button
                          variant={viewType === VIEW_TYPE_GRID ? "primary" : "ghost"}
                          onClick={() => setViewType(VIEW_TYPE_GRID)}
                          size="sm"
                        >
                          <Squares2X2Icon className="w-5 h-5" />
                        </Button>
                      </div>
                      <Button
                        variant="secondary"
                        size="md"
                        onClick={() => navigate("/admin/divisions/search")}
                        icon={MagnifyingGlassIcon}
                      >
                        Advanced Search
                      </Button>
                      <Button
                        variant="success"
                        size="lg"
                        onClick={() => navigate("/admin/divisions/add/step-1-search")}
                        icon={PlusIcon}
                      >
                        Add Division
                      </Button>
                    </div>
                  </div>
                </div>

                {/* Search Filter Component */}
                <SearchFilter
                  searchTerm={searchQuery}
                  tempSearchTerm={tempSearchQuery}
                  onSearchTermChange={setTempSearchQuery}
                  onSearch={handleSearch}
                  searchPlaceholder={searchFilterConfig.searchPlaceholder}
                  statusOptions={searchFilterConfig.statusOptions}
                  statusFilter={status}
                  onStatusFilterChange={handleStatusChange}
                  typeOptions={searchFilterConfig.typeOptions}
                  typeFilter={type}
                  onTypeFilterChange={handleTypeChange}
                  sortOptions={searchFilterConfig.sortOptions}
                  sortValue={searchFilterConfig.sortValue}
                  onSortChange={handleSortChange}
                  pageSizeOptions={searchFilterConfig.pageSizeOptions}
                  pageSize={pageSize}
                  onPageSizeChange={handlePageSizeChange}
                  onClearFilters={handleClearFilters}
                  onRefresh={searchFilterConfig.onRefresh}
                />

                {/* Grid Content Section */}
                <div className="p-6">
                  {isLoading ? (
                    <div className="flex items-center justify-center py-12">
                      <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${getThemeClasses('border-primary')}`}></div>
                      <span className={`ml-3 ${getThemeClasses('text-secondary')}`}>Loading...</span>
                    </div>
                  ) : divisionList?.results?.length > 0 ? (
                    <>
                      {/* Results count */}
                      <div className={`mb-6 text-sm ${getThemeClasses('text-secondary')}`}>
                        Showing <strong>{divisionList.results.length}</strong> divisions
                        {divisionList.count > 0 && ` of ${divisionList.count} total`}
                        {searchQuery && ` (filtered by "${searchQuery}")`}
                      </div>

                      {/* Grid View */}
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        {divisionList.results.map((division) => {
                          // Get contact email from division
                          let contactEmail = division.contactEmail;
                          if (!contactEmail && division.contacts && Array.isArray(division.contacts) && division.contacts.length > 0) {
                            const primaryContact = division.contacts.find(contact => contact.isPrimary);
                            if (primaryContact && primaryContact.email) {
                              contactEmail = primaryContact.email;
                            } else if (division.contacts[0] && division.contacts[0].email) {
                              contactEmail = division.contacts[0].email;
                            }
                          }

                          return (
                            <div
                              key={division.id}
                              className={`bg-white border ${getThemeClasses('card-border')} rounded-lg shadow-sm hover:shadow-lg transition-shadow h-full flex flex-col`}
                            >
                              <div className="p-6 flex flex-col flex-grow">
                                <div className="mb-4">
                                  <h3 className={`text-lg font-semibold ${getThemeClasses('text-primary')} flex items-start`}>
                                    <BuildingOffice2Icon className={`w-5 h-5 mr-2 flex-shrink-0 mt-0.5 ${getThemeClasses('text-muted')}`} />
                                    <span className="line-clamp-2">
                                      {division.divisionName || division.name}
                                    </span>
                                  </h3>
                                  <div className="mt-2">
                                    {getTypeBadge(division.divisionType || division.type)}
                                  </div>
                                </div>

                                <div className="space-y-3 flex-grow">
                                  {contactEmail && (
                                    <div className="flex items-center text-sm">
                                      <EnvelopeIcon className={`w-4 h-4 mr-2 flex-shrink-0 ${getThemeClasses('text-muted')}`} />
                                      <span className={`truncate ${getThemeClasses('text-secondary')}`}>{contactEmail}</span>
                                    </div>
                                  )}

                                  {(division.city || division.region) && (
                                    <div className="flex items-center text-sm">
                                      <MapPinIcon className={`w-4 h-4 mr-2 flex-shrink-0 ${getThemeClasses('text-muted')}`} />
                                      <span className={`truncate ${getThemeClasses('text-secondary')}`}>
                                        {division.city && division.region
                                          ? `${division.city}, ${division.region}`
                                          : division.city || division.region
                                        }
                                      </span>
                                    </div>
                                  )}
                                </div>

                                <div className="mt-4 pt-4 border-t border-gray-100 mt-auto">
                                  <ViewButton
                                    to={`/admin/division/${division.id}`}
                                    text="View Details"
                                    size="sm"
                                    fullWidth
                                  />
                                </div>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </>
                  ) : (
                    /* Empty State */
                    <div className="text-center py-12">
                      <BuildingOffice2Icon className={`mx-auto h-12 w-12 ${getThemeClasses('text-muted')}`} />
                      <h3 className={`mt-2 text-sm font-medium ${getThemeClasses('text-primary')}`}>
                        {emptyStateConfig.title}
                      </h3>
                      <p className={`mt-1 text-sm ${getThemeClasses('text-secondary')}`}>
                        {emptyStateConfig.description}
                      </p>
                      <div className="mt-6">
                        <Button
                          variant="success"
                          size="lg"
                          onClick={emptyStateConfig.onActionClick}
                          icon={PlusIcon}
                        >
                          {emptyStateConfig.actionLabel}
                        </Button>
                      </div>
                    </div>
                  )}

                  {/* Pagination for Grid View */}
                  {divisionList?.results?.length > 0 && (
                    <div className="mt-8 flex justify-center">
                      <div className="flex items-center space-x-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handlePageChange("previous")}
                          disabled={previousCursors.length === 0}
                        >
                          Previous
                        </Button>
                        <span className={`px-3 py-1 text-sm ${getThemeClasses('text-secondary')}`}>
                          Page {previousCursors.length + 1}
                        </span>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handlePageChange("next")}
                          disabled={!nextCursor}
                        >
                          Next
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
      </>
    </UIXThemeProvider>
  );
}

export default AdminDivisionListPage;
