// File Path: monorepo/web/frontend/src/pages/Admin/Setting/Specialization/Detail/Page.jsx
import React, { useState, useEffect, useMemo, memo } from "react";
import { Link, useNavigate, useParams, useLocation } from "react-router";
import { useSpecializationManager } from "../../../../../services/Services";
import {
  UIXThemeProvider,
  Breadcrumb,
  Alert,
  Button,
  InfoField,
  SystemInfo,
  BackToListButton,
  EditButton,
  DeleteButton,
  DetailPageIcon,
  DetailCard,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  StarIcon,
  ChevronRightIcon,
  XMarkIcon,
  TrashIcon,
  PencilSquareIcon,
  ExclamationTriangleIcon,
  Cog6ToothIcon,
  ChartBarIcon,
  ClipboardDocumentIcon,
  InformationCircleIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  ClockIcon,
  UserIcon,
  GlobeAltIcon,
  DocumentTextIcon,
  TagIcon,
  HashtagIcon,
  CalendarIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";

function SettingSpecializationDetailPage() {
  return (
    <UIXThemeProvider>
      <SettingSpecializationDetailPageContent />
    </UIXThemeProvider>
  );
}

const SettingSpecializationDetailPageContent = memo(
  function SettingSpecializationDetailPageContent() {
    const { getThemeClasses } = useUIXTheme();
    const navigate = useNavigate();
    const { id } = useParams();
    const location = useLocation();
    const specializationManager = useSpecializationManager();

    // Memoize theme classes
    const themeClasses = useMemo(
      () => ({
        badgeActiveBg: getThemeClasses("badge-active-bg"),
        badgeActiveText: getThemeClasses("badge-active-text"),
        badgeInactiveBg: getThemeClasses("badge-inactive-bg"),
        badgeInactiveText: getThemeClasses("badge-inactive-text"),
        textPrimary: getThemeClasses("text-primary"),
        textError: getThemeClasses("text-error"),
      }),
      [getThemeClasses],
    );

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

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

    // Fetch specialization details
    const fetchSpecializationDetail = async () => {
      try {
        setIsLoading(true);
        setError(null);

        const specializationData =
          await specializationManager.getSpecializationDetail(
            id,
            onUnauthorized,
          );

        setSpecialization(specializationData);

        if (import.meta.env.DEV) {
        console.log(
          "SpecializationDetailPage: Specialization detail fetched successfully:",
          {
            id: specializationData.id,
            name: specializationData.name,
          },
        );
        }
      } catch (err) {
        if (import.meta.env.DEV) {
        console.error(
          "SpecializationDetailPage: Failed to fetch specialization detail:",
          err,
        );
        }
        setError(err.message || "Failed to load specialization details");
      } finally {
        setIsLoading(false);
      }
    };

    // Load data on component mount
    useEffect(() => {
      // Explicitly scroll to top when component mounts
      window.scrollTo(0, 0);

      if (id && typeof id === "string" && id.trim() !== "") {
        fetchSpecializationDetail();
      } else {
        setError("Invalid specialization ID");
        setIsLoading(false);
      }
    }, [id]);

    // 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]);

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

    // Loading state
    if (isLoading && !specialization) {
      return (
        <div
          className={`min-h-screen ${getThemeClasses("bg-primary")} flex items-center justify-center`}
        >
          <div className="text-center">
            <div
              className={`animate-spin rounded-full h-12 w-12 border-b-2 ${getThemeClasses("loading-spinner")} mx-auto`}
            ></div>
            <p className={`mt-4 ${getThemeClasses("text-secondary")}`}>
              Loading specialization details...
            </p>
          </div>
        </div>
      );
    }

    // Error state
    if (error && !specialization) {
      return (
        <div className={`min-h-screen ${getThemeClasses("bg-primary")} p-8`}>
          <div className="max-w-2xl mx-auto">
            <div
              className={`${getThemeClasses("bg-error")} ${getThemeClasses("border-error")} ${themeClasses.textError} px-4 py-3 rounded-lg mb-4`}
            >
              {error}
            </div>
            <Link
              to="/admin/settings/specializations"
              className={`inline-flex items-center ${themeClasses.textError} ${getThemeClasses("hover:text-error-dark")}`}
            >
              <ArrowLeftIcon className="w-4 h-4 mr-2" />
              Back to Specializations
            </Link>
          </div>
        </div>
      );
    }

    return (
      <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")}`}>
        <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: "Specializations",
                to: "/admin/settings/specializations",
                icon: StarIcon,
              },
              {
                label: specialization?.name || "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={StarIcon} />
                    <div className="text-center lg:text-left">
                      <h1
                        className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${themeClasses.textPrimary} leading-tight`}
                      >
                        {specialization.name}
                      </h1>
                      <div className="mt-2">
                        <span
                          className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                            specialization.status === 1
                              ? `${themeClasses.badgeActiveBg} ${themeClasses.badgeActiveText}`
                              : `${themeClasses.badgeInactiveBg} ${themeClasses.badgeInactiveText}`
                          }`}
                        >
                          {specialization.status === 1 ? "Active" : "Inactive"}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="flex-shrink-0 flex space-x-3">
                <BackToListButton
                  onClick={() => navigate("/admin/settings/specializations")}
                />
                <EditButton
                  onClick={() =>
                    navigate(`/admin/settings/specialization/${id}/update`)
                  }
                />
                <DeleteButton
                  onClick={() =>
                    navigate(`/admin/settings/specialization/${id}/delete`)
                  }
                />
              </div>
            </div>
          </div>

          {/* Main Content Layout - Centered */}
          <DetailCard
            title="Specialization Details"
            icon={InformationCircleIcon}
          >
            {/* Single Column Layout */}
            <div className="space-y-6">
              {/* Name Field */}
              <InfoField
                label="Specialization Name"
                value={specialization.name}
                icon={TagIcon}
              />

              {/* Description Field */}
              <InfoField
                label="Description"
                value={specialization.description || "No description provided"}
                icon={DocumentTextIcon}
              />

              {/* Status Field */}
              <InfoField
                label="Status"
                value={specialization.status === 1 ? "Active" : "Inactive"}
                icon={CheckCircleIcon}
              />

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

SettingSpecializationDetailPageContent.displayName =
  "SettingSpecializationDetailPageContent";

export default SettingSpecializationDetailPage;
