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

import React, { useState, useEffect, useCallback, useMemo, memo } from "react";
import { Link, useNavigate } from "react-router";
import { useAuthManager, useAccountManager } from "../../../services/Services";
import {
  Breadcrumb,
  PageHeader,
  Alert,
  Button,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../components/UIX";
import {
  HomeIcon,
  ChartBarIcon,
  BanknotesIcon,
  UserIcon,
  CreditCardIcon,
  XCircleIcon,
  ShieldCheckIcon,
  CalendarIcon,
  CakeIcon,
  WrenchIcon,
  UserGroupIcon,
  BuildingOfficeIcon,
  BriefcaseIcon,
  TagIcon,
  CalendarDaysIcon,
  GlobeAltIcon,
  EnvelopeIcon,
  DocumentTextIcon,
  ChevronRightIcon,
} from "@heroicons/react/24/outline";

// Move static theme configuration objects outside component
const THEME_GRADIENTS = {
  blue: "linear-gradient(135deg, #172554 0%, #1e3a8a 100%)",
  red: "linear-gradient(135deg, #7f1d1d 0%, #dc2626 100%)",
  purple: "linear-gradient(135deg, #581c87 0%, #7c3aed 100%)",
  green: "linear-gradient(135deg, #14532d 0%, #16a34a 100%)",
  charcoal: "linear-gradient(135deg, #0f172a 0%, #475569 100%)",
};

const THEME_HOVER_COLORS = {
  blue: "group-hover:text-blue-600",
  red: "group-hover:text-red-600",
  purple: "group-hover:text-purple-600",
  green: "group-hover:text-green-600",
  charcoal: "group-hover:text-slate-600",
};

const THEME_BUTTON_GRADIENTS = {
  blue: "bg-gradient-to-r from-gray-50 to-blue-50 hover:from-blue-50 hover:to-blue-100",
  red: "bg-gradient-to-r from-gray-50 to-red-50 hover:from-red-50 hover:to-red-100",
  purple:
    "bg-gradient-to-r from-gray-50 to-purple-50 hover:from-purple-50 hover:to-purple-100",
  green:
    "bg-gradient-to-r from-gray-50 to-green-50 hover:from-green-50 hover:to-green-100",
  charcoal:
    "bg-gradient-to-r from-gray-50 to-slate-50 hover:from-slate-50 hover:to-slate-100",
};

const THEME_BUTTON_TEXT_COLORS = {
  blue: "text-gray-700 hover:text-blue-950",
  red: "text-gray-700 hover:text-red-950",
  purple: "text-gray-700 hover:text-purple-950",
  green: "text-gray-700 hover:text-green-950",
  charcoal: "text-gray-700 hover:text-slate-950",
};

// Define all available reports with icons - moved outside component
const REPORTS = [
  {
    id: 1,
    title: "Due Service Fees",
    description: "List due service fees for facilitators.",
    path: "/admin/report/1",
    category: "Financial",
    icon: BanknotesIcon,
  },
  {
    id: 2,
    title: "Facilitator Jobs",
    description: "List jobs by Facilitator.",
    path: "/admin/report/2",
    category: "Facilitators",
    icon: UserIcon,
  },
  {
    id: 3,
    title: "Service Fees by Types",
    description: "List revenue by service fee types.",
    path: "/admin/report/3",
    category: "Financial",
    icon: CreditCardIcon,
  },
  {
    id: 4,
    title: "Cancelled Jobs",
    description: "List all cancelled jobs.",
    path: "/admin/report/4",
    category: "Orders",
    icon: XCircleIcon,
  },
  {
    id: 5,
    title: "Facilitator Insurance",
    description: "List insurance due dates.",
    path: "/admin/report/5",
    category: "Facilitators",
    icon: ShieldCheckIcon,
  },
  {
    id: 6,
    title: "Facilitator Police Check",
    description: "List police check due dates.",
    path: "/admin/report/6",
    category: "Facilitators",
    icon: ShieldCheckIcon,
  },
  {
    id: 7,
    title: "Facilitator Birthdays",
    description: "List facilitators by birthdate.",
    path: "/admin/report/7",
    category: "Facilitators",
    icon: CakeIcon,
  },
  {
    id: 8,
    title: "Facilitator Skill Set",
    description: "List facilitator skill sets.",
    path: "/admin/report/8",
    category: "Facilitators",
    icon: WrenchIcon,
  },
  {
    id: 9,
    title: "Client Addresses",
    description: "List client addresses.",
    path: "/admin/report/9",
    category: "Clients",
    icon: UserGroupIcon,
  },
  {
    id: 10,
    title: "Residential Jobs",
    description: "List all residential jobs.",
    path: "/admin/report/10",
    category: "Orders",
    icon: HomeIcon,
  },
  {
    id: 11,
    title: "Commercial Jobs",
    description: "List only commercial jobs.",
    path: "/admin/report/11",
    category: "Orders",
    icon: BuildingOfficeIcon,
  },
  {
    id: 12,
    title: "Skill Sets",
    description: "List of all skill sets.",
    path: "/admin/report/12",
    category: "System",
    icon: BriefcaseIcon,
  },
  {
    id: 13,
    title: "Leads by Skill",
    description: "List of jobs by skill set.",
    path: "/admin/report/13",
    category: "Orders",
    icon: TagIcon,
  },
  {
    id: 15,
    title: "Facilitator Expiry Dates",
    description: "List upcoming expiry dates.",
    path: "/admin/report/15",
    category: "Facilitators",
    icon: CalendarDaysIcon,
  },
  {
    id: 16,
    title: "How Users Find Us (long)",
    description: "List how users discovered us.",
    path: "/admin/report/16",
    category: "Marketing",
    icon: GlobeAltIcon,
  },
  {
    id: 17,
    title: "How Users Find Us (short)",
    description: "List how users discovered us and referral sources.",
    path: "/admin/report/17",
    category: "Marketing",
    icon: GlobeAltIcon,
  },
  {
    id: 19,
    title: "Job Tags by Assignment Dates",
    description: "List jobs by tags using assignment dates as a filter.",
    path: "/admin/report/19",
    category: "Orders",
    icon: CalendarIcon,
  },
  {
    id: 22,
    title: "Job Tags by Completion Dates",
    description: "List jobs by tags using completion dates as a filter.",
    path: "/admin/report/22",
    category: "Orders",
    icon: CalendarIcon,
  },
  {
    id: 20,
    title: "Payments",
    description: "List all payments and related information.",
    path: "/admin/report/20",
    category: "Financial",
    icon: CreditCardIcon,
  },
  {
    id: 21,
    title: "Marketing Emails",
    description: "List all emails of consenting user's email addresses.",
    path: "/admin/report/21",
    category: "Marketing",
    icon: EnvelopeIcon,
  },
];

const BREADCRUMB_ITEMS = [
  {
    label: "Dashboard",
    to: "/admin/dashboard",
    icon: HomeIcon,
  },
  {
    label: "Reports",
    icon: ChartBarIcon,
    isActive: true,
  },
];

function AdminReportPage() {
  return (
    <UIXThemeProvider>
      <AdminReportPageContent />
    </UIXThemeProvider>
  );
}

const AdminReportPageContent = memo(function AdminReportPageContent() {
  const authManager = useAuthManager();
  const accountManager = useAccountManager();
  const navigate = useNavigate();
  const { getThemeClasses, currentTheme } = useUIXTheme();

  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentUser, setCurrentUser] = useState(null);

  // Memoize theme classes
  const themeClasses = useMemo(
    () => ({
      bgGradientPrimary: getThemeClasses("bg-gradient-primary"),
      loadingSpinner: getThemeClasses("loading-spinner"),
    }),
    [getThemeClasses],
  );

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

  useEffect(() => {
    let mounted = true;

    const checkAuth = async () => {
      try {
        setIsLoading(true);

        if (!authManager.isAuthenticated()) {
          navigate("/login?unauthorized=true");
          return;
        }

        const profile = await accountManager.getAccountDetail(onUnauthorized);

        if (mounted) {
          setCurrentUser(profile);
        }
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error("Error checking authentication:", err);
        }
        if (mounted) {
          setError("Failed to load user information. Please try again.");
        }
      } finally {
        if (mounted) {
          setIsLoading(false);
        }
      }
    };

    window.scrollTo(0, 0);
    checkAuth();

    return () => {
      mounted = false;
    };
  }, [authManager, accountManager, navigate, onUnauthorized]);

  // Memoize report cards
  const reportCards = useMemo(() => {
    return REPORTS.map((report) => {
      const IconComponent = report.icon;
      return (
        <div
          key={report.id}
          className={`group ${getThemeClasses("bg-card")} rounded-2xl shadow-lg border ${getThemeClasses("card-border")} overflow-hidden hover:shadow-xl hover:-translate-y-1 transition-all duration-300 flex flex-col`}
        >
          {/* Icon Header with theme-aware gradient */}
          <div
            className="p-6 text-white flex justify-center relative overflow-hidden"
            style={{ background: THEME_GRADIENTS[currentTheme] }}
          >
            <div className="absolute inset-0 bg-white opacity-10 transform -skew-y-6 translate-y-12"></div>
            <IconComponent className="w-12 h-12 relative z-10 group-hover:scale-110 transition-transform duration-300" />
          </div>

          {/* Content */}
          <div className="p-5 flex-grow flex flex-col">
            <div className="mb-2">
              <span className={`inline-block px-2 py-1 text-xs font-medium ${getThemeClasses("bg-badge")} ${getThemeClasses("text-badge")} rounded`}>
                {report.category}
              </span>
            </div>
            <h3
              className={`text-lg font-bold ${getThemeClasses("text-primary")} mb-2 transition-colors duration-200 ${THEME_HOVER_COLORS[currentTheme]}`}
            >
              {report.title}
            </h3>
            <p className={`text-sm ${getThemeClasses("text-secondary")} line-clamp-2 mb-4 flex-grow`}>
              {report.description}
            </p>
          </div>

          {/* Footer Button */}
          <div className={`border-t ${getThemeClasses("border-color")}`}>
            <Link
              to={report.path}
              className={`w-full p-4 ${THEME_BUTTON_GRADIENTS[currentTheme]} flex items-center justify-between ${THEME_BUTTON_TEXT_COLORS[currentTheme]} transition-all duration-200 font-medium`}
            >
              <span>View Report</span>
              <ChevronRightIcon className="w-5 h-5 group-hover:translate-x-1 transition-transform duration-200" />
            </Link>
          </div>
        </div>
      );
    });
  }, [currentTheme, getThemeClasses]);

  if (isLoading) {
    return (
      <div
        className={`min-h-screen bg-gradient-to-br from-gray-50 via-white ${themeClasses.bgGradientPrimary} flex items-center justify-center px-4`}
      >
        <div className="text-center">
          <div
            className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.loadingSpinner} mx-auto`}
          ></div>
          <p className={`mt-4 text-sm sm:text-base ${getThemeClasses("text-secondary")}`}>
            Loading Reports...
          </p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Alert type="error" message={error} className="mb-4" />
        <Button onClick={() => navigate("/admin/dashboard")}>
          Back to Dashboard
        </Button>
      </div>
    );
  }

  return (
    <div
      className={`min-h-screen bg-gradient-to-br from-gray-50 via-white ${themeClasses.bgGradientPrimary}`}
    >
      {/* 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">
        {/* Breadcrumb */}
        <Breadcrumb items={BREADCRUMB_ITEMS} />

        {/* Page Header Card */}
        <div className={`mb-8 ${getThemeClasses("bg-card")} shadow-xl rounded-2xl overflow-hidden border ${getThemeClasses("card-border")}`}>
          <div className="p-6 sm:p-8">
            <PageHeader
              icon={ChartBarIcon}
              title="Reports"
              subtitle="Access and generate reports."
            />
          </div>
        </div>

        {/* Reports Grid Container */}
        <div className={`${getThemeClasses("bg-card")} shadow-xl rounded-2xl overflow-hidden border ${getThemeClasses("card-border")} hover:shadow-2xl transition-shadow duration-300`}>
          <div className="p-6 sm:p-8">
            {reportCards.length > 0 ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                {reportCards}
              </div>
            ) : (
              <div className="text-center py-12">
                <DocumentTextIcon className={`mx-auto h-12 w-12 ${getThemeClasses("text-secondary")}`} />
                <h3 className={`mt-2 text-sm font-medium ${getThemeClasses("text-primary")}`}>
                  No reports available
                </h3>
                <p className={`mt-1 text-sm ${getThemeClasses("text-secondary")}`}>
                  There are currently no reports configured in the system.
                </p>
              </div>
            )}
          </div>
        </div>

      </div>
    </div>
  );
});

AdminReportPageContent.displayName = "AdminReportPageContent";

export default AdminReportPage;
