// File Path: monorepo/web/frontend/src/pages/Admin/Setting/Bulletin/Detail/Page.jsx

import React, { useState, useEffect, useMemo, useCallback, memo } from "react";
import { Link, useNavigate, useParams, useLocation } from "react-router";
import { useBulletinManager } from "../../../../../services/Services";
import {
  Breadcrumb,
  Alert,
  Button,
  BackToListButton,
  EditButton,
  DeleteButton,
  DetailPageIcon,
  DetailCard,
  SystemInfo,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  NewspaperIcon,
  TrashIcon,
  PencilSquareIcon,
  ExclamationTriangleIcon,
  Cog6ToothIcon,
  ClipboardDocumentIcon,
  InformationCircleIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  ClockIcon,
  UserIcon,
  GlobeAltIcon,
  CalendarIcon,
  HomeIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";

function SettingBulletinDetailPage() {
  return (
    <UIXThemeProvider>
      <SettingBulletinDetailPageContent />
    </UIXThemeProvider>
  );
}

const SettingBulletinDetailPageContent = memo(
  function SettingBulletinDetailPageContent() {
    const { getThemeClasses } = useUIXTheme();
    const { id } = useParams();
    const bulletinManager = useBulletinManager();
    const navigate = useNavigate();
    const location = useLocation();

    // State management
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const [successMessage, setSuccessMessage] = useState("");
    const [bulletin, setBulletin] = useState(null);

    // Memoize theme classes
    const themeClasses = useMemo(
      () => ({
        bgGradientPrimary: getThemeClasses("bg-gradient-primary"),
        loadingSpinner: getThemeClasses("loading-spinner"),
        badgeActiveBg: getThemeClasses("badge-active-bg"),
        badgeActiveText: getThemeClasses("badge-active-text"),
        badgeInactiveBg: getThemeClasses("badge-inactive-bg"),
        badgeInactiveText: getThemeClasses("badge-inactive-text"),
        textMuted: getThemeClasses("text-muted"),
        errorText: getThemeClasses("text-error"),
        errorBg: getThemeClasses("bg-error-light"),
        errorBorder: getThemeClasses("border-error"),
      }),
      [getThemeClasses],
    );

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

    // Load bulletin details
    const loadBulletin = useCallback(async () => {
      if (!id || typeof id !== "string" || id.trim() === "") {
        setError("Invalid bulletin ID");
        setIsLoading(false);
        return;
      }

      try {
        setIsLoading(true);
        setError(null);

        const bulletinData = await bulletinManager.getBulletinDetail(
          id,
          onUnauthorized,
        );

        setBulletin(bulletinData);

        if (import.meta.env.DEV) {
        console.log(
          "BulletinDetailPage: Bulletin detail fetched successfully:",
          {
            id: bulletinData.id,
            text: bulletinData.text,
          },
        );
        }
      } catch (error) {
        if (import.meta.env.DEV) {
        console.error(
          "BulletinDetailPage: Failed to fetch bulletin detail:",
          error,
        );
        }
        setError(error.message || "Failed to load bulletin details");
      } finally {
        setIsLoading(false);
      }
    }, [id, bulletinManager, onUnauthorized]);

    // Effects
    useEffect(() => {
      window.scrollTo(0, 0);
      loadBulletin();
    }, [loadBulletin]);

    // Clear success message after 3 seconds
    useEffect(() => {
      if (successMessage) {
        const timer = setTimeout(() => setSuccessMessage(""), 3000);
        return () => clearTimeout(timer);
      }
    }, [successMessage]);

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

    // Loading state
    if (isLoading && !bulletin) {
      return (
        <div
          className={`min-h-screen ${themeClasses.bgGradientPrimary} flex items-center justify-center`}
        >
          <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 ${themeClasses.textMuted}`}>
              Loading bulletin details...
            </p>
          </div>
        </div>
      );
    }

    // Error state
    if (error && !bulletin) {
      return (
        <div className={`min-h-screen ${themeClasses.bgGradientPrimary} p-8`}>
          <div className="max-w-2xl mx-auto">
            <div
              className={`${themeClasses.errorBg} border ${themeClasses.errorBorder} ${themeClasses.errorText} px-4 py-3 rounded-lg mb-4`}
            >
              <div className="flex items-center">
                <ExclamationTriangleIcon className="w-5 h-5 mr-2" />
                {error}
              </div>
            </div>
            <Link
              to="/admin/settings/bulletins"
              className={`inline-flex items-center ${themeClasses.errorText}`}
            >
              <ArrowLeftIcon className="w-4 h-4 mr-2" />
              Back to Bulletins
            </Link>
          </div>
        </div>
      );
    }

    return (
      <div className={`min-h-screen ${themeClasses.bgGradientPrimary}`}>
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
          {/* Breadcrumb */}
          <Breadcrumb
            items={[
              {
                label: "Dashboard",
                to: "/admin/dashboard",
                icon: HomeIcon,
              },
              {
                label: "Settings",
                to: "/admin/settings",
                icon: Cog6ToothIcon,
              },
              {
                label: "Bulletins",
                to: "/admin/settings/bulletins",
                icon: NewspaperIcon,
              },
              {
                label: bulletin?.text || "Details",
                icon: ClipboardDocumentIcon,
                isActive: true,
              },
            ]}
          />

          {/* Success/Error Messages */}
          {successMessage && (
            <Alert
              type="success"
              message={successMessage}
              onClose={() => setSuccessMessage("")}
              className="mb-6"
            />
          )}

          {error && (
            <Alert
              type="error"
              message={error}
              onClose={() => setError(null)}
              className="mb-6"
            />
          )}

          {/* Header Section - Enhanced with title and action buttons */}
          <div className="mb-8 sm:mb-10 max-w-4xl mx-auto">
            <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-center justify-center lg:justify-start">
                  <div className="flex items-start">
                    <DetailPageIcon icon={NewspaperIcon} />
                    <div className="text-center lg:text-left">
                      <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-gray-800 leading-tight">
                        {bulletin.text}
                      </h1>
                      {bulletin.status && (
                        <div className="mt-2">
                          <span
                            className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                              bulletin.status === 1
                                ? `${themeClasses.badgeActiveBg} ${themeClasses.badgeActiveText}`
                                : `${themeClasses.badgeInactiveBg} ${themeClasses.badgeInactiveText}`
                            }`}
                          >
                            {bulletin.status === 1 ? "Active" : "Inactive"}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
              <div className="flex-shrink-0 flex space-x-3">
                <BackToListButton
                  onClick={() => navigate("/admin/settings/bulletins")}
                />
                <EditButton
                  onClick={() =>
                    navigate(`/admin/settings/bulletin/${id}/update`)
                  }
                />
                <DeleteButton
                  onClick={() =>
                    navigate(`/admin/settings/bulletin/${id}/delete`)
                  }
                />
              </div>
            </div>
          </div>

          {/* Main Content Layout - Centered */}
          <DetailCard title="Bulletin Information" icon={InformationCircleIcon}>
            {/* Single Column Layout */}
            <div className="space-y-6">
              {/* Text Field */}
              <div>
                <label className="block text-base sm:text-lg font-semibold text-gray-700 mb-3 flex items-center">
                  Text <span className="text-red-500">*</span>
                </label>
                <div className="p-5 bg-gray-50 rounded-xl border border-gray-200">
                  <p className="text-lg font-semibold text-gray-900">
                    {bulletin.text}
                  </p>
                </div>
              </div>

              {/* System Information */}
              <SystemInfo
                createdAt={bulletin.createdAt}
                createdByUserName={bulletin.createdByUserName}
                createdFromIpAddress={bulletin.createdFromIpAddress}
                modifiedAt={bulletin.modifiedAt}
                modifiedByUserName={bulletin.modifiedByUserName}
                modifiedFromIpAddress={bulletin.modifiedFromIpAddress}
              />
            </div>
          </DetailCard>
        </div>
      </div>
    );
  },
);
SettingBulletinDetailPageContent.displayName =
  "SettingBulletinDetailPageContent";

export default SettingBulletinDetailPage;
