// File Path: monorepo/web/frontend/src/pages/Admin/Setting/SkillCategory/Detail/Page.jsx
import React, { useState, useEffect, useMemo, memo } from "react";
import { Link, useNavigate, useParams, useLocation } from "react-router";
import { useSkillCategoryManager } from "../../../../../services/Services";
import {
  UIXThemeProvider,
  Breadcrumb,
  Alert,
  Button,
  InfoField,
  SystemInfo,
  BackToListButton,
  EditButton,
  DeleteButton,
  DetailPageIcon,
  DetailCard,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  AcademicCapIcon,
  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 SettingSkillCategoryDetailPage() {
  return (
    <UIXThemeProvider>
      <SettingSkillCategoryDetailPageContent />
    </UIXThemeProvider>
  );
}

const SettingSkillCategoryDetailPageContent = memo(
  function SettingSkillCategoryDetailPageContent() {
    const { getThemeClasses } = useUIXTheme();
    const navigate = useNavigate();
    const { id } = useParams();
    const location = useLocation();
    const skillCategoryManager = useSkillCategoryManager();

    // 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"),
      }),
      [getThemeClasses],
    );

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

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

    // Fetch skill category details using real API
    const fetchSkillCategoryDetail = async () => {
      try {
        setIsLoading(true);
        setError(null);

        if (import.meta.env.DEV) {
        console.log(
          "SkillCategoryDetailPage: Fetching skill category detail for ID:",
          id,
        );
        }

        // Call the API via SkillCategoryManager
        const data = await skillCategoryManager.getSkillCategoryDetail(
          id,
          onUnauthorized,
        );

        if (import.meta.env.DEV) {
        console.log("SkillCategoryDetailPage: API response:", data);

        if (data && data.id) {
          setSkillCategory(data);
        }
          if (import.meta.env.DEV) {
          console.log(
            "SkillCategoryDetailPage: Skill category detail loaded successfully",
          );
          }
        } else {
          if (import.meta.env.DEV) {
          console.warn(
            "SkillCategoryDetailPage: Invalid response structure:",
            data,
          );
          }
          setError("Skill category not found");
        }
      } catch (err) {
        if (import.meta.env.DEV) {
        console.error(
          "SkillCategoryDetailPage: Failed to fetch skill category detail:",
          err,
        );
        }
        setError(err.message || "Failed to load skill category details");
      } finally {
        setIsLoading(false);
      }
    };

    // Load data on component mount
    useEffect(() => {
      window.scrollTo(0, 0);

      if (id && typeof id === "string" && id.trim() !== "") {
        fetchSkillCategoryDetail();
      } else {
        setError("Invalid skill category 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 && !skillCategory) {
      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 skill category details...
            </p>
          </div>
        </div>
      );
    }

    // Error state
    if (error && !skillCategory) {
      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")} ${getThemeClasses("text-error")} px-4 py-3 rounded-lg mb-4`}
            >
              {error}
            </div>
            <Link
              to="/admin/settings/skill-categories"
              className={`inline-flex items-center ${getThemeClasses("text-primary")} ${getThemeClasses("hover:text-primary-dark")}`}
            >
              <ArrowLeftIcon className="w-4 h-4 mr-2" />
              Back to Skill Categories
            </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: "Skill Categories",
                to: "/admin/settings/skill-categories",
                icon: AcademicCapIcon,
              },
              {
                label: skillCategory?.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={AcademicCapIcon} />
                    <div className="text-center lg:text-left">
                      <h1
                        className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${themeClasses.textPrimary} leading-tight`}
                      >
                        {skillCategory?.name || "Skill Category Details"}
                      </h1>
                      <div className="mt-2">
                        <span
                          className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                            skillCategory?.status === 1
                              ? `${themeClasses.badgeActiveBg} ${themeClasses.badgeActiveText}`
                              : `${themeClasses.badgeInactiveBg} ${themeClasses.badgeInactiveText}`
                          }`}
                        >
                          {skillCategory?.status === 1 ? "Active" : "Inactive"}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="flex-shrink-0 flex space-x-3">
                <BackToListButton
                  onClick={() => navigate("/admin/settings/skill-categories")}
                />
                <EditButton
                  onClick={() =>
                    navigate(`/admin/settings/skill-category/${id}/update`)
                  }
                />
                <DeleteButton
                  onClick={() =>
                    navigate(`/admin/settings/skill-category/${id}/delete`)
                  }
                />
              </div>
            </div>
          </div>

          {/* Main Content Layout - Centered */}
          <DetailCard
            title="Skill Category Details"
            icon={InformationCircleIcon}
          >
            {/* Single Column Layout */}
            <div className="space-y-6">
              {/* Name Field */}
              <InfoField
                label="Skill Category Name"
                value={skillCategory?.name || "Not available"}
                icon={TagIcon}
              />

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

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

              {/* System Information */}
              <SystemInfo
                createdAt={skillCategory?.createdAt}
                createdByUserName={skillCategory?.createdByUserName}
                createdFromIpAddress={skillCategory?.createdFromIpAddress}
                modifiedAt={skillCategory?.modifiedAt}
                modifiedByUserName={skillCategory?.modifiedByUserName}
                modifiedFromIpAddress={skillCategory?.modifiedFromIpAddress}
              />
            </div>
          </DetailCard>

          {/* Action Buttons */}
          <div className="max-w-4xl mx-auto mt-8">
            <div className="bg-white shadow-xl rounded-2xl p-6">
              <div className="flex flex-col sm:flex-row sm:justify-center sm:space-x-4 space-y-3 sm:space-y-0">
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => navigate("/admin/settings/skill-categories")}
                  icon={ArrowLeftIcon}
                >
                  Back to List
                </Button>
                <Button
                  type="button"
                  variant="primary"
                  onClick={() =>
                    navigate(`/admin/settings/skill-category/${id}/update`)
                  }
                  icon={PencilSquareIcon}
                >
                  Edit Skill Category
                </Button>
                <Button
                  type="button"
                  variant="danger"
                  onClick={() =>
                    navigate(`/admin/settings/skill-category/${id}/delete`)
                  }
                  icon={TrashIcon}
                >
                  Delete Skill Category
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  },
);

SettingSkillCategoryDetailPageContent.displayName =
  "SettingSkillCategoryDetailPageContent";

export default SettingSkillCategoryDetailPage;
