// File Path: monorepo/web/frontend/src/pages/Admin/Setting/HowHearAboutUsItem/Detail/Page.jsx
import React, { useState, useEffect } from "react";
import { Link, useNavigate, useParams, useLocation } from "react-router";
import { useHowHearAboutUsItemManager } from "../../../../../services/Services";
import Breadcrumb from "../../../../../components/UIX/Breadcrumb/Breadcrumb";
import {
  MegaphoneIcon,
  XMarkIcon,
  TrashIcon,
  PencilSquareIcon,
  ExclamationTriangleIcon,
  Cog6ToothIcon,
  ClipboardDocumentIcon,
  InformationCircleIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  ClockIcon,
  UserIcon,
  CalendarIcon,
  UserGroupIcon,
  UsersIcon,
  BriefcaseIcon,
  LockClosedIcon,
  HashtagIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";
import {
  BackToListButton,
  EditButton,
  DeleteButton,
  DetailPageIcon,
  DetailCard,
  SystemInfo,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../services/Helpers/DateFormatter";

function SettingHowHearAboutUsItemDetailPage() {
  return (
    <UIXThemeProvider>
      <SettingHowHearAboutUsItemDetailPageContent />
    </UIXThemeProvider>
  );
}

function SettingHowHearAboutUsItemDetailPageContent() {
  const { getThemeClasses } = useUIXTheme();
  const navigate = useNavigate();
  const { id } = useParams();
  const location = useLocation();
  const howHearAboutUsItemManager = useHowHearAboutUsItemManager();

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

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

  // Fetch how hear about us item details
  const fetchData = async () => {
    try {
      setIsLoading(true);
      setError(null);

      const result = await howHearAboutUsItemManager.getDetail(
        id,
        onUnauthorized,
        true, // Force refresh
      );

      setData(result);
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error("Failed to fetch How Hear About Us Item:", err);
      setError(err.message || "Failed to load data");
      }
    } finally {
      setIsLoading(false);
    }
  };

  // Get status badge
  const getStatusBadge = (status) => {
    const isActive = status === 1;
    return (
      <span
        className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
          isActive ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-800"
        }`}
      >
        {isActive ? "Active" : "Inactive"}
      </span>
    );
  };

  // Load data on component mount
  useEffect(() => {
    // Explicitly scroll to top when component mounts
    window.scrollTo(0, 0);
    if (id) {
      fetchData();
    } else {
      setError("Invalid item 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]);

  // Auto-clear error messages
  useEffect(() => {
    if (error) {
      const timer = setTimeout(() => setError(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [error]);

  // Loading state
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 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 text-gray-600">Loading item details...</p>
        </div>
      </div>
    );
  }

  // Error state (no data)
  if (error && !data) {
    return (
      <div className="min-h-screen bg-gray-50 p-8">
        <div className="max-w-2xl mx-auto">
          <div className="bg-red-50 border border-red-200 text-red-800 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/how-hear-about-us-items"
            className={`inline-flex items-center ${getThemeClasses("text-primary")} hover:${getThemeClasses("text-primary-dark")}`}
          >
            <ArrowLeftIcon className="w-4 h-4 mr-2" />
            Back to How Hear About Us Items
          </Link>
        </div>
      </div>
    );
  }

  // Not found state
  if (!data) {
    return (
      <div className="min-h-screen bg-gray-50 p-8">
        <div className="max-w-2xl mx-auto">
          <div className="bg-amber-50 border border-amber-200 text-amber-800 px-4 py-3 rounded-lg mb-4">
            <div className="flex items-center">
              <ExclamationTriangleIcon className="w-5 h-5 mr-2" />
              How Hear About Us Item not found
            </div>
          </div>
          <Link
            to="/admin/settings/how-hear-about-us-items"
            className={`inline-flex items-center ${getThemeClasses("text-primary")} hover:${getThemeClasses("text-primary-dark")}`}
          >
            <ArrowLeftIcon className="w-4 h-4 mr-2" />
            Back to How Hear About Us Items
          </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: "How Hear About Us Items",
              to: "/admin/settings/how-hear-about-us-items",
              icon: MegaphoneIcon,
            },
            {
              label: data?.text || "Detail",
              icon: ClipboardDocumentIcon,
              isActive: true,
            },
          ]}
        />

        {/* Success/Error Messages */}
        {successMessage && (
          <div className="mb-6 bg-green-50 border border-green-200 text-green-800 px-4 py-3 rounded-lg flex items-center justify-between">
            <span className="flex items-center">
              <CheckCircleIcon className="w-5 h-5 mr-2" />
              {successMessage}
            </span>
            <button
              onClick={() => setSuccessMessage("")}
              className="text-green-600 hover:text-green-800"
            >
              <XMarkIcon className="w-5 h-5" />
            </button>
          </div>
        )}

        {error && (
          <div className="mb-6 bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg flex items-center justify-between">
            <span className="flex items-center">
              <ExclamationTriangleIcon className="w-5 h-5 mr-2" />
              {error}
            </span>
            <button
              onClick={() => setError(null)}
              className="text-red-600 hover:text-red-800"
            >
              <XMarkIcon className="w-5 h-5" />
            </button>
          </div>
        )}

        {/* 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={ClipboardDocumentIcon} />
                  <div className="text-center lg:text-left">
                    <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-gray-800 leading-tight">
                      {data.text}
                    </h1>
                    {data.text === "Other" && (
                      <div className="mt-2 inline-flex items-center px-3 py-1 text-sm font-medium text-amber-800 bg-amber-100 rounded-lg">
                        <LockClosedIcon className="w-4 h-4 mr-1" />
                        System Protected
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
            <div className="flex-shrink-0 flex space-x-3">
              <BackToListButton
                onClick={() =>
                  navigate("/admin/settings/how-hear-about-us-items")
                }
              />
              {data.text !== "Other" && (
                <>
                  <EditButton
                    onClick={() =>
                      navigate(
                        `/admin/settings/how-hear-about-us-item/${id}/update`,
                      )
                    }
                  />
                  <DeleteButton
                    onClick={() =>
                      navigate(
                        `/admin/settings/how-hear-about-us-item/${id}/delete`,
                      )
                    }
                  />
                </>
              )}
            </div>
          </div>
        </div>

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

            {/* Sort Number Field */}
            <div>
              <div className="block text-base sm:text-lg font-semibold text-gray-700 mb-3 flex items-center">
                Sort Number <span className="text-red-500">*</span>
              </div>
              <div className="p-5 bg-gray-50 rounded-xl border border-gray-200">
                <p className="text-lg font-medium text-gray-900 flex items-center">
                  <HashtagIcon className="w-5 h-5 mr-2 text-gray-500" />
                  {data.sortNumber ?? "N/A"}
                </p>
              </div>
              <p className="mt-1 text-xs text-gray-500">
                Lower numbers appear first in lists
              </p>
            </div>

            {/* Role Configuration */}
            <div>
              <div className="block text-base sm:text-lg font-semibold text-gray-700 mb-3 flex items-center">
                Role Configuration <span className="text-red-500">*</span>
              </div>
              <p className="text-sm text-gray-500 mb-3">
                Which user roles can use this option
              </p>
              <div className="space-y-3">
                {/* Facilitator Checkbox */}
                <div
                  className={`p-3 rounded-lg border-2 ${
                    data.isForFacilitator
                      ? "bg-green-50 border-green-500"
                      : "bg-white border-gray-200"
                  }`}
                >
                  <div className="flex items-start">
                    <div
                      className={`mt-1 w-4 h-4 rounded ${data.isForFacilitator ? "bg-green-500" : "bg-gray-300"} flex items-center justify-center`}
                    >
                      {data.isForFacilitator && (
                        <span className="text-white text-xs">✓</span>
                      )}
                    </div>
                    <div className="ml-3">
                      <div className="flex items-center">
                        <BriefcaseIcon className="w-4 h-4 mr-2 text-red-500" />
                        <span className="text-sm font-medium text-gray-900">
                          For Facilitators
                        </span>
                      </div>
                      <p className="text-xs text-gray-500 mt-1">
                        Facilitators can select this option when registering
                      </p>
                    </div>
                  </div>
                </div>

                {/* Customer Checkbox */}
                <div
                  className={`p-3 rounded-lg border-2 ${
                    data.isForCustomer
                      ? "bg-green-50 border-green-500"
                      : "bg-white border-gray-200"
                  }`}
                >
                  <div className="flex items-start">
                    <div
                      className={`mt-1 w-4 h-4 rounded ${data.isForCustomer ? "bg-green-500" : "bg-gray-300"} flex items-center justify-center`}
                    >
                      {data.isForCustomer && (
                        <span className="text-white text-xs">✓</span>
                      )}
                    </div>
                    <div className="ml-3">
                      <div className="flex items-center">
                        <UsersIcon className="w-4 h-4 mr-2 text-red-500" />
                        <span className="text-sm font-medium text-gray-900">
                          For Customers
                        </span>
                      </div>
                      <p className="text-xs text-gray-500 mt-1">
                        Customers can select this option when registering
                      </p>
                    </div>
                  </div>
                </div>

                {/* Staff Checkbox */}
                <div
                  className={`p-3 rounded-lg border-2 ${
                    data.isForStaff
                      ? "bg-green-50 border-green-500"
                      : "bg-white border-gray-200"
                  }`}
                >
                  <div className="flex items-start">
                    <div
                      className={`mt-1 w-4 h-4 rounded ${data.isForStaff ? "bg-green-500" : "bg-gray-300"} flex items-center justify-center`}
                    >
                      {data.isForStaff && (
                        <span className="text-white text-xs">✓</span>
                      )}
                    </div>
                    <div className="ml-3">
                      <div className="flex items-center">
                        <UserGroupIcon className="w-4 h-4 mr-2 text-red-500" />
                        <span className="text-sm font-medium text-gray-900">
                          For Staff
                        </span>
                      </div>
                      <p className="text-xs text-gray-500 mt-1">
                        Staff can select this option when creating records
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* System Protected Warning */}
            {data.text === "Other" && (
              <div className="p-4 bg-amber-50 border border-amber-200 rounded-lg">
                <p className="text-sm text-amber-800 flex items-start">
                  <LockClosedIcon className="w-4 h-4 mr-2 flex-shrink-0 mt-0.5" />
                  <span>
                    <strong>System Protected:</strong> This is a
                    system-protected item and cannot be edited or deleted.
                  </span>
                </p>
              </div>
            )}

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

export default SettingHowHearAboutUsItemDetailPage;
