// monorepo/web/frontend/src/pages/Admin/Dashboard/Page.jsx
import React, { useState, useEffect, useMemo, useCallback } from "react";
import { Link, useNavigate } from "react-router";
import {
  useDashboardManager,
  useAuthManager,
  useBulletinManager,
  useFacilitatorAwayLogManager,
} from "../../../services/Services";
import {
  Card,
  Button,
  Alert,
  Loading,
  Modal,
  useUIXTheme,
  Badge,
} from "../../../components/UIX";
import {
  ChartBarIcon,
  NewspaperIcon,
  UserIcon,
  WrenchScrewdriverIcon,
  ClipboardDocumentListIcon,
  TrashIcon,
  ExclamationTriangleIcon,
  ArrowRightIcon,
  CalendarDaysIcon,
  CalendarIcon,
  ClockIcon,
  ShieldExclamationIcon,
  ArrowTrendingUpIcon,
  Squares2X2Icon,
  ChevronRightIcon,
} from "@heroicons/react/24/outline";
import { formatDateForDisplay } from "../../../services/Helpers/DateFormatter";

// Constants for facilitator away log reasons
const REASON_MAP = {
  1: "Other",
  2: "Going on vacation",
  3: "Personal reasons",
  4: "Commercial insurance expired",
  5: "Police check expired",
  6: "Auto Insurance Expired",
  7: "WSIB Expired",
  8: "Dues Date Expired",
};

const REASON_COMMERCIAL_INSURANCE_EXPIRED = 4;
const REASON_POLICE_CHECK_EXPIRED = 5;

function AdminDashboardPage() {
  const dashboardManager = useDashboardManager();
  const bulletinManager = useBulletinManager();
  const facilitatorAwayLogManager = useFacilitatorAwayLogManager();
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  const themeClasses = useMemo(() => ({
    bgGradientSecondary: getThemeClasses("bg-gradient-secondary"),
    bgGradientPrimary: getThemeClasses("bg-gradient-primary"),
    cardBorder: getThemeClasses("card-border"),
    bgCard: getThemeClasses("bg-card"),
    textPrimary: getThemeClasses("text-primary"),
    textSecondary: getThemeClasses("text-secondary"),
    textMuted: getThemeClasses("text-muted"),
    linkPrimary: getThemeClasses("link-primary"),
    accentText: getThemeClasses("breadcrumb-active"),
    textWarning: getThemeClasses("text-warning"),
    textOnGradient: getThemeClasses("text-on-gradient"),
    alertErrorBg: getThemeClasses("alert-error-bg"),
    alertErrorBorder: getThemeClasses("alert-error-border"),
    alertErrorText: getThemeClasses("alert-error-text"),
  }), [getThemeClasses]);

  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [dashboard, setDashboard] = useState({});

  // Modal states
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedBulletin, setSelectedBulletin] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Constants
  const MAX_BULLETINS_DISPLAY = 10;
  const MAX_AWAY_LOGS_DISPLAY = 10;

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

  // Fetch dashboard data (includes bulletins and facilitator away logs)
  const fetchDashboard = useCallback(async () => {
    setErrors({});
    setFetching(true);

    try {
      const dashboardData = await dashboardManager.getDashboard(onUnauthorized);
      setDashboard(dashboardData);

      if (import.meta.env.DEV) {
        console.log("AdminDashboard: Dashboard data loaded successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminDashboard: Failed to fetch dashboard:", error);
      }
      setErrors({ fetch: error.message || "Failed to load dashboard data" });
    } finally {
      setFetching(false);
    }
  }, [dashboardManager, onUnauthorized]);

  // Refresh only bulletins after create/delete operations
  const refreshDashboard = useCallback(async () => {
    try {
      // Force refresh to get updated data
      const dashboardData = await dashboardManager.getDashboard(
        onUnauthorized,
        true,
      );
      setDashboard(dashboardData);

      if (import.meta.env.DEV) {
        console.log("AdminDashboard: Dashboard refreshed successfully");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("AdminDashboard: Failed to refresh dashboard:", error);
      }
    }
  }, [dashboardManager, onUnauthorized]);

  const handleDeleteBulletin = useCallback(async () => {
    if (!selectedBulletin) return;

    setIsSubmitting(true);
    setErrors({});

    try {
      // Delete the bulletin using bulletinManager
      await bulletinManager.deleteBulletin(selectedBulletin.id, onUnauthorized);

      if (import.meta.env.DEV) {
        console.log("Bulletin deleted successfully:", selectedBulletin.id);
      }

      // Close modal and clear selection
      setShowDeleteModal(false);
      setSelectedBulletin(null);

      // Refresh dashboard to get updated bulletins list
      await refreshDashboard();
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Failed to delete bulletin:", error);
      }
      setErrors({ delete: error.message || "Failed to delete bulletin" });
      // Still close the modal on error
      setShowDeleteModal(false);
      setSelectedBulletin(null);
    } finally {
      setIsSubmitting(false);
    }
  }, [selectedBulletin, bulletinManager, onUnauthorized, refreshDashboard]);

  // Get reason display with icon
  const getReasonDisplay = useCallback((awayLog) => {
    const hasExpiredDoc =
      awayLog.reason === REASON_COMMERCIAL_INSURANCE_EXPIRED ||
      awayLog.reason === REASON_POLICE_CHECK_EXPIRED;

    const reasonText =
      awayLog.reason === 1
        ? awayLog.reasonOther || "Other"
        : REASON_MAP[awayLog.reason] || "Unknown";

    return (
      <span className="flex items-center">
        {hasExpiredDoc && (
          <ShieldExclamationIcon className={`w-4 h-4 mr-1 ${themeClasses.textWarning} flex-shrink-0`} />
        )}
        <span className="truncate">{reasonText}</span>
      </span>
    );
  }, [themeClasses.textWarning]);

  // Extract data from dashboard response - MUST be before any conditional returns
  const bulletins = useMemo(() => dashboard.bulletins || [], [dashboard.bulletins]);
  const facilitatorAwayLogs = useMemo(() => dashboard.facilitatorAwayLogs || [], [dashboard.facilitatorAwayLogs]);

  // Limit display to maximum allowed
  const displayBulletins = useMemo(() => bulletins.slice(0, MAX_BULLETINS_DISPLAY), [bulletins, MAX_BULLETINS_DISPLAY]);
  const displayAwayLogs = useMemo(() => facilitatorAwayLogs.slice(0, MAX_AWAY_LOGS_DISPLAY), [facilitatorAwayLogs, MAX_AWAY_LOGS_DISPLAY]);

  // Format numbers with commas
  const formatNumber = useCallback((num) => {
    return new Intl.NumberFormat().format(num || 0);
  }, []);

  const statsCards = useMemo(() => [
    {
      title: "Events",
      count: dashboard.eventsCount || 0,
      icon: CalendarIcon,
      themeClass: themeClasses.bgGradientSecondary,
    },
    {
      title: "Event Contracts",
      count: dashboard.eventContractsCount || 0,
      icon: ClipboardDocumentListIcon,
      link: "/admin/event-contracts",
      linkText: "View Event Contracts",
      themeClass: themeClasses.bgGradientSecondary,
    },
    {
      title: "Event Orders",
      count: dashboard.eventOrdersCount || 0,
      icon: WrenchScrewdriverIcon,
      link: "/admin/event-orders",
      linkText: "View Event Orders",
      themeClass: themeClasses.bgGradientSecondary,
    },
    {
      title: "Facilitators",
      count: dashboard.facilitatorsCount || 0,
      icon: UserIcon,
      link: "/admin/facilitators",
      linkText: "View Facilitators",
      themeClass: themeClasses.bgGradientSecondary,
    },
  ], [dashboard, themeClasses.bgGradientSecondary]);

  const eventTypeCards = useMemo(() => [
    {
      title: "Offsite Events",
      count: dashboard.offsiteEventsCount || 0,
      icon: CalendarIcon,
      link: "/admin/events/field-trips",
      linkText: "View Offsite Events",
      themeClass: themeClasses.bgGradientSecondary,
    },
    {
      title: "Onsite Events",
      count: dashboard.onsiteEventsCount || 0,
      icon: CalendarIcon,
      link: "/admin/events/in-schools",
      linkText: "View Onsite Events",
      themeClass: themeClasses.bgGradientSecondary,
    },
    {
      title: "Conference Events",
      count: dashboard.conferenceEventsCount || 0,
      icon: CalendarIcon,
      link: "/admin/events/conferences",
      linkText: "View Conferences",
      themeClass: themeClasses.bgGradientSecondary,
    },
    {
      title: "Virtual Events",
      count: dashboard.virtualEventsCount || 0,
      icon: CalendarIcon,
      link: "/admin/events/virtuals",
      linkText: "View Virtual Events",
      themeClass: themeClasses.bgGradientSecondary,
    },
  ], [dashboard, themeClasses.bgGradientSecondary]);

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

    const initializeDashboard = async () => {
      if (!mounted) return;

      window.scrollTo(0, 0);

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

      await fetchDashboard();
    };

    initializeDashboard();

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

  return (
    <div className={`min-h-screen ${themeClasses.bgGradientPrimary}`}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {isFetching ? (
          <div className="flex items-center justify-center py-32">
            <Loading message="Loading Dashboard..." />
          </div>
        ) : (
          <>
        {/* Enhanced Page Header */}
        <div className="mb-12">
          <div className="flex items-center justify-between">
            <div>
              <h1 className={`text-4xl font-bold ${themeClasses.textPrimary} flex items-center`}>
                <div className={`w-12 h-12 ${themeClasses.bgGradientSecondary} rounded-xl flex items-center justify-center mr-4`}>
                  <ChartBarIcon className="w-7 h-7 text-white" />
                </div>
                Dashboard
              </h1>
            </div>
            <div className="hidden lg:flex items-center space-x-3">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => refreshDashboard()}
              >
                <ArrowTrendingUpIcon className="w-4 h-4 mr-2" />
                Refresh Data
              </Button>
            </div>
          </div>
        </div>

        {/* Error Alert */}
        {(errors.fetch || errors.delete) && (
          <Alert type="error" className="mb-8">
            {errors.fetch || errors.delete}
          </Alert>
        )}

        {/* Enhanced Statistics Cards - First Row */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          {statsCards.map((stat, index) => (
            <div
              key={stat.title}
              className={`group relative overflow-hidden ${stat.themeClass} rounded-2xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1`}
              style={{
                animation: `fadeInUp 0.6s ease-out ${index * 0.1}s both`,
              }}
            >
              <div className="relative p-6">
                <div className="flex items-start justify-between mb-6">
                  <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center shadow-lg">
                    <stat.icon className="w-6 h-6 text-white" />
                  </div>
                  <div className="text-right">
                    <div className="text-3xl font-bold text-white mb-1">
                      {formatNumber(stat.count)}
                    </div>
                    <div className="text-sm font-medium text-white/90">
                      {stat.title}
                    </div>
                  </div>
                </div>

                {stat.link && stat.linkText ? (
                  <Link
                    to={stat.link}
                    className="inline-flex items-center justify-center w-full px-4 py-3 bg-white/15 hover:bg-white/25 backdrop-blur-sm rounded-lg text-base font-bold text-white transition-all duration-200 border border-white/20 hover:border-white/40 group"
                  >
                    {stat.linkText}
                    <ChevronRightIcon className="w-5 h-5 ml-2 transition-transform group-hover:translate-x-1" />
                  </Link>
                ) : (
                  <div className="h-12"></div>
                )}
              </div>
            </div>
          ))}
        </div>

        {/* Event Type Cards - Second Row */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
          {eventTypeCards.map((stat, index) => (
            <div
              key={stat.title}
              className={`group relative overflow-hidden ${stat.themeClass} rounded-2xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1`}
              style={{
                animation: `fadeInUp 0.6s ease-out ${(index + 4) * 0.1}s both`,
              }}
            >
              <div className="relative p-6">
                <div className="flex items-start justify-between mb-6">
                  <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center shadow-lg">
                    <stat.icon className="w-6 h-6 text-white" />
                  </div>
                  <div className="text-right">
                    <div className="text-3xl font-bold text-white mb-1">
                      {formatNumber(stat.count)}
                    </div>
                    <div className="text-sm font-medium text-white/90">
                      {stat.title}
                    </div>
                  </div>
                </div>

                <Link
                  to={stat.link}
                  className="inline-flex items-center justify-center w-full px-4 py-3 bg-white/15 hover:bg-white/25 backdrop-blur-sm rounded-lg text-base font-bold text-white transition-all duration-200 border border-white/20 hover:border-white/40 group"
                >
                  {stat.linkText}
                  <ChevronRightIcon className="w-5 h-5 ml-2 transition-transform group-hover:translate-x-1" />
                </Link>
              </div>
            </div>
          ))}
        </div>

        {/* Two Column Layout for News and Away Logs */}
        <div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
          {/* Enhanced Office News Section */}
          <Card padding="p-0" className="overflow-hidden">
            <div className={`${themeClasses.bgGradientSecondary} px-8 py-6`}>
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-xl font-semibold text-white flex items-center">
                    <div className="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center mr-3">
                      <NewspaperIcon className="w-5 h-5 text-white" />
                    </div>
                    Office News
                  </h2>
                  {displayBulletins.length > 0 && (
                    <p className={`${themeClasses.textOnGradient} text-sm mt-1`}>
                      Latest {displayBulletins.length} announcements
                    </p>
                  )}
                </div>
                <div className="flex items-center space-x-3">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => refreshDashboard()}
                    className="text-white hover:bg-white/20 border border-white hover:border-white/80"
                  >
                    Refresh
                  </Button>
                  <Link to="/admin/settings/bulletin/create">
                    <Button
                      variant="secondary"
                      size="sm"
                      className="bg-white text-slate-700 hover:bg-slate-50 shadow-lg font-medium"
                    >
                      Add News
                    </Button>
                  </Link>
                </div>
              </div>
            </div>

            <div className="p-8">
              {displayBulletins.length > 0 ? (
                <>
                  <div className="space-y-4 max-h-96 overflow-y-auto">
                    {displayBulletins.map((bulletin, index) => (
                      <div
                        key={bulletin.id}
                        className={`group relative ${themeClasses.bgCard} rounded-xl p-6 hover:shadow-md transition-all duration-200 border ${themeClasses.cardBorder}`}
                        style={{
                          animation: `fadeInUp 0.4s ease-out ${index * 0.1}s both`,
                        }}
                      >
                        <div className="flex items-start justify-between">
                          <div className="flex-1 mr-4">
                            <div className="flex items-start mb-3">
                              <div className={`w-2 h-2 ${themeClasses.accentText} rounded-full mt-2 mr-3 flex-shrink-0`} style={{ backgroundColor: 'currentColor' }}></div>
                              <p className={`${themeClasses.textPrimary} leading-relaxed`}>
                                {bulletin.text}
                              </p>
                            </div>
                            {bulletin.createdAt && (
                              <div className={`flex items-center text-xs ${themeClasses.textMuted} ml-5`}>
                                <ClockIcon className="w-3 h-3 mr-1" />
                                {new Date(
                                  bulletin.createdAt,
                                ).toLocaleDateString("en-US", {
                                  month: "short",
                                  day: "numeric",
                                  year: "numeric",
                                  hour: "2-digit",
                                  minute: "2-digit",
                                })}
                              </div>
                            )}
                          </div>
                          <Button
                            variant="danger"
                            size="sm"
                            onClick={() => {
                              setSelectedBulletin(bulletin);
                              setShowDeleteModal(true);
                            }}
                            className="opacity-0 group-hover:opacity-100 transition-all duration-200 flex-shrink-0"
                          >
                            <TrashIcon className="w-4 h-4" />
                          </Button>
                        </div>
                      </div>
                    ))}
                  </div>

                  {bulletins.length > MAX_BULLETINS_DISPLAY && (
                    <div className={`mt-8 pt-6 border-t ${themeClasses.cardBorder}`}>
                      <Link
                        to="/admin/settings/bulletins"
                        className={`inline-flex items-center justify-center w-full px-4 py-3 ${themeClasses.bgCard} ${themeClasses.linkPrimary} font-medium rounded-xl transition-all duration-200 border ${themeClasses.cardBorder} hover:shadow-md`}
                      >
                        View All Bulletins ({bulletins.length} total)
                        <ArrowRightIcon className="w-4 h-4 ml-2" />
                      </Link>
                    </div>
                  )}
                </>
              ) : (
                <div className="text-center py-12">
                  <div className={`w-16 h-16 ${themeClasses.bgCard} rounded-2xl flex items-center justify-center mx-auto mb-4 border ${themeClasses.cardBorder}`}>
                    <NewspaperIcon className={`w-8 h-8 ${themeClasses.accentText}`} />
                  </div>
                  <p className={`${themeClasses.textSecondary} text-lg mb-2`}>No news yet</p>
                  <p className={`${themeClasses.textMuted} text-sm`}>
                    Click "Add News" to create your first bulletin.
                  </p>
                </div>
              )}
            </div>
          </Card>

          {/* Enhanced Facilitator Away List Section */}
          <Card padding="p-0" className="overflow-hidden">
            <div className={`${themeClasses.bgGradientSecondary} px-8 py-6`}>
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-xl font-semibold text-white flex items-center">
                    <div className="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center mr-3">
                      <CalendarDaysIcon className="w-5 h-5 text-white" />
                    </div>
                    Facilitator Away List
                  </h2>
                  {displayAwayLogs.length > 0 && (
                    <p className={`${themeClasses.textOnGradient} text-sm mt-1`}>
                      {displayAwayLogs.length} currently away
                    </p>
                  )}
                </div>
                <div className="flex items-center space-x-3">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => refreshDashboard()}
                    className="text-white hover:bg-white/20 border border-white hover:border-white/80"
                  >
                    Refresh
                  </Button>
                  <Button
                    variant="secondary"
                    size="sm"
                    onClick={() =>
                      navigate("/admin/settings/facilitator-away-log/create")
                    }
                    className="bg-white text-slate-700 hover:bg-slate-50 shadow-lg font-medium"
                  >
                    Add Entry
                  </Button>
                </div>
              </div>
            </div>

            <div className="p-8">
              {displayAwayLogs.length > 0 ? (
                <>
                  <div className="space-y-4 max-h-96 overflow-y-auto">
                    {displayAwayLogs.map((awayLog, index) => (
                      <div
                        key={awayLog.id}
                        className={`group ${themeClasses.bgCard} rounded-xl p-6 hover:shadow-md transition-all duration-200 cursor-pointer border ${themeClasses.cardBorder}`}
                        onClick={() =>
                          navigate(
                            `/admin/settings/facilitator-away-log/${awayLog.id}/detail`,
                          )
                        }
                        style={{
                          animation: `fadeInUp 0.4s ease-out ${index * 0.1}s both`,
                        }}
                      >
                        <div className="flex items-start justify-between">
                          <div className="flex-1">
                            <Link
                              to={`/admin/facilitator/${awayLog.facilitatorId}`}
                              className={`inline-flex items-center ${themeClasses.linkPrimary} font-semibold text-base mb-3 transition-colors`}
                              target="_blank"
                              rel="noopener noreferrer"
                              onClick={(e) => e.stopPropagation()}
                            >
                              <UserIcon className="w-4 h-4 mr-2" />
                              {awayLog.facilitatorName ||
                                `Facilitator #${awayLog.facilitatorId}`}
                            </Link>

                            <div className={`space-y-2 text-sm ${themeClasses.textSecondary}`}>
                              <div className="flex items-center">
                                <span className={`${themeClasses.textMuted} mr-2 font-medium`}>
                                  Reason:
                                </span>
                                {getReasonDisplay(awayLog)}
                              </div>

                              <div className="flex items-center justify-between">
                                <div className="flex items-center">
                                  <CalendarIcon className={`w-4 h-4 mr-2 ${themeClasses.textMuted}`} />
                                  <span>
                                    From:{" "}
                                    <span className="font-medium">
                                      {formatDateForDisplay(awayLog.startDate)}
                                    </span>
                                  </span>
                                </div>

                                {awayLog.untilFurtherNotice === 1 ? (
                                  <Badge variant="warning" size="sm" className="inline-flex items-center">
                                    <ClockIcon className="w-3 h-3 mr-1" />
                                    Until further notice
                                  </Badge>
                                ) : (
                                  <span className={themeClasses.textSecondary}>
                                    To:{" "}
                                    <span className="font-medium">
                                      {formatDateForDisplay(awayLog.untilDate)}
                                    </span>
                                  </span>
                                )}
                              </div>
                            </div>
                          </div>
                          <ChevronRightIcon className={`w-5 h-5 ${themeClasses.textMuted} transition-colors`} />
                        </div>
                      </div>
                    ))}
                  </div>

                  {facilitatorAwayLogs.length > MAX_AWAY_LOGS_DISPLAY && (
                    <div className={`mt-8 pt-6 border-t ${themeClasses.cardBorder}`}>
                      <Link
                        to="/admin/settings/facilitator-away-logs"
                        className={`inline-flex items-center justify-center w-full px-4 py-3 ${themeClasses.bgCard} ${themeClasses.linkPrimary} font-medium rounded-xl transition-all duration-200 border ${themeClasses.cardBorder} hover:shadow-md`}
                      >
                        View All Away Logs ({facilitatorAwayLogs.length} total)
                        <ArrowRightIcon className="w-4 h-4 ml-2" />
                      </Link>
                    </div>
                  )}
                </>
              ) : (
                <div className="text-center py-12">
                  <div className={`w-16 h-16 ${themeClasses.bgCard} rounded-2xl flex items-center justify-center mx-auto mb-4 border ${themeClasses.cardBorder}`}>
                    <CalendarDaysIcon className={`w-8 h-8 ${themeClasses.accentText}`} />
                  </div>
                  <p className={`${themeClasses.textSecondary} text-lg mb-2`}>
                    All facilitators available
                  </p>
                  <p className={`${themeClasses.textMuted} text-sm`}>
                    No facilitators are currently away.
                  </p>
                </div>
              )}
            </div>
          </Card>
        </div>

{/* Enhanced Quick Links Section - COMMENTED OUT */}
        {/* <Card padding="p-0" className="overflow-hidden mt-8">
          <div className={`${themeClasses.bgGradientSecondary} px-8 py-6`}>
            <h2 className="text-xl font-semibold text-white flex items-center">
              <div className="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center mr-3">
                <Squares2X2Icon className="w-5 h-5 text-white" />
              </div>
              Quick Actions
            </h2>
            <p className={`${themeClasses.textOnGradient} text-sm mt-1`}>
              Access frequently used features
            </p>
          </div>

          <div className="p-8">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <Link
                to="/admin/event-contract-history/my-event-contract-history"
                className={`group relative overflow-hidden ${themeClasses.bgCard} rounded-xl p-6 transition-all duration-300 transform hover:-translate-y-1 hover:shadow-lg border ${themeClasses.cardBorder}`}
              >
                <div className="relative">
                  <div className={`w-12 h-12 ${themeClasses.bgGradientSecondary} rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform`}>
                    <ClipboardDocumentListIcon className="w-6 h-6 text-white" />
                  </div>
                  <h3 className={`font-semibold ${themeClasses.textPrimary} mb-2 text-lg`}>
                    My Event Contract History
                  </h3>
                  <p className={`${themeClasses.textSecondary} text-sm leading-relaxed`}>
                    View your personal event contract history and track your
                    completed contracts.
                  </p>
                </div>
              </Link>

              <Link
                to="/admin/event-order-history/my-event-order-history"
                className={`group relative overflow-hidden ${themeClasses.bgCard} rounded-xl p-6 transition-all duration-300 transform hover:-translate-y-1 hover:shadow-lg border ${themeClasses.cardBorder}`}
              >
                <div className="relative">
                  <div className={`w-12 h-12 ${themeClasses.bgGradientSecondary} rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform`}>
                    <WrenchScrewdriverIcon className="w-6 h-6 text-white" />
                  </div>
                  <h3 className={`font-semibold ${themeClasses.textPrimary} mb-2 text-lg`}>
                    My Event Order History
                  </h3>
                  <p className={`${themeClasses.textSecondary} text-sm leading-relaxed`}>
                    View your personal event order history and track your
                    completed orders.
                  </p>
                </div>
              </Link>

              <Link
                to="/admin/event-contract-history/team-event-contract-history"
                className={`group relative overflow-hidden ${themeClasses.bgCard} rounded-xl p-6 transition-all duration-300 transform hover:-translate-y-1 hover:shadow-lg border ${themeClasses.cardBorder}`}
              >
                <div className="relative">
                  <div className={`w-12 h-12 ${themeClasses.bgGradientSecondary} rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform`}>
                    <ClipboardDocumentListIcon className="w-6 h-6 text-white" />
                  </div>
                  <h3 className={`font-semibold ${themeClasses.textPrimary} mb-2 text-lg`}>
                    Team Event Contract History
                  </h3>
                  <p className={`${themeClasses.textSecondary} text-sm leading-relaxed`}>
                    View the team's event contract history and monitor overall team
                    performance.
                  </p>
                </div>
              </Link>

              <Link
                to="/admin/event-order-history/team-event-order-history"
                className={`group relative overflow-hidden ${themeClasses.bgCard} rounded-xl p-6 transition-all duration-300 transform hover:-translate-y-1 hover:shadow-lg border ${themeClasses.cardBorder}`}
              >
                <div className="relative">
                  <div className={`w-12 h-12 ${themeClasses.bgGradientSecondary} rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform`}>
                    <WrenchScrewdriverIcon className="w-6 h-6 text-white" />
                  </div>
                  <h3 className={`font-semibold ${themeClasses.textPrimary} mb-2 text-lg`}>
                    Team Event Order History
                  </h3>
                  <p className={`${themeClasses.textSecondary} text-sm leading-relaxed`}>
                    View the team's event order history and monitor overall team
                    performance.
                  </p>
                </div>
              </Link>
            </div>
          </div>
        </Card> */}
      </>
        )}
      </div>

      {/* Enhanced Delete Confirmation Modal */}
      <Modal
        isOpen={showDeleteModal}
        onClose={() => {
          if (!isSubmitting) {
            setShowDeleteModal(false);
            setSelectedBulletin(null);
          }
        }}
        title="Delete Bulletin"
        size="md"
      >
        <div className="space-y-6">
          <div className={`p-4 rounded-lg border ${themeClasses.alertErrorBg} ${themeClasses.alertErrorBorder}`}>
            <div className="flex items-center mb-2">
              <ExclamationTriangleIcon className={`w-6 h-6 mr-2 ${themeClasses.alertErrorText}`} />
              <span className={`font-semibold ${themeClasses.alertErrorText}`}>
                Warning: This action cannot be undone
              </span>
            </div>
            <p className={`text-sm ${themeClasses.alertErrorText}`}>
              This bulletin will be permanently deleted from the system.
            </p>
          </div>

          <div>
            <p className={`${themeClasses.textPrimary} mb-4 font-medium`}>
              Are you sure you want to delete this bulletin?
            </p>

            {selectedBulletin && (
              <div className={`p-4 ${themeClasses.bgCard} rounded-lg border ${themeClasses.cardBorder}`}>
                <p className={`text-sm ${themeClasses.textPrimary} italic`}>
                  "{selectedBulletin.text}"
                </p>
                {selectedBulletin.createdAt && (
                  <p className={`text-xs ${themeClasses.textMuted} mt-2`}>
                    Created:{" "}
                    {new Date(selectedBulletin.createdAt).toLocaleDateString(
                      "en-US",
                      {
                        month: "long",
                        day: "numeric",
                        year: "numeric",
                        hour: "2-digit",
                        minute: "2-digit",
                      },
                    )}
                  </p>
                )}
              </div>
            )}
          </div>

          <div className={`flex justify-end space-x-3 pt-4 border-t ${themeClasses.cardBorder}`}>
            <Button
              variant="secondary"
              onClick={() => {
                if (!isSubmitting) {
                  setShowDeleteModal(false);
                  setSelectedBulletin(null);
                }
              }}
              disabled={isSubmitting}
              className="px-6 py-2"
            >
              Cancel
            </Button>
            <Button
              variant="danger"
              onClick={handleDeleteBulletin}
              disabled={isSubmitting}
              loading={isSubmitting}
              className="px-6 py-2 bg-gradient-to-r from-red-600 to-red-700 hover:from-red-700 hover:to-red-800"
            >
              {isSubmitting ? "Deleting..." : "Delete Bulletin"}
            </Button>
          </div>
        </div>
      </Modal>

      <style>{`
        @keyframes fadeInUp {
          from {
            opacity: 0;
            transform: translateY(20px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
      `}</style>
    </div>
  );
}

export default AdminDashboardPage;
