import { useLocalizedName } from "@/shared/common/localizedName";
import { useMessage } from "@/user-management/web-Management/hooks/useMessage";
import { useTheme } from "@/user-management/web-Management/hooks/useTheme";
import { useTenantConfig } from "@/layout/components/TenantConfig";
import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";

const OfficeHeadMessage = () => {
  const [isMobile, setIsMobile] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [showReadMore, setShowReadMore] = useState(false);
  const [messageRef, setMessageRef] = useState<HTMLDivElement | null>(null);
  const { t } = useTranslation();

  const baseParams = {
    isActive: true,
  };
  const { items } = useMessage(baseParams);
  const localizedName = useLocalizedName();
  const { items: theme } = useTheme();
  const { config: tenantConfig } = useTenantConfig();
  const officeHead = items?.find((i) => i.staffType === "office_head");

  const isPersonPhoto = !!officeHead?.presigned;
  const imageSrc = officeHead?.presigned || tenantConfig.logo || "";
  const displayName =
    localizedName(officeHead?.employee?.name) || tenantConfig.organizationName;
  const displayPosition = localizedName(
    officeHead?.employee?.employeePositions?.[0]?.position?.name
  ) || "";

  useEffect(() => {
    const checkScreenSize = () => {
      setIsMobile(window.innerWidth < 768);
    };
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
    return () => {
      window.removeEventListener("resize", checkScreenSize);
    };
  }, []);

  // Check if content overflows after render
  useEffect(() => {
    if (messageRef) {
      const isOverflowing = messageRef.scrollHeight > messageRef.clientHeight;
      setShowReadMore(isOverflowing);
    }
  }, [messageRef, officeHead]);

  const getMessageContent = () => {
    return (
      localizedName(officeHead?.messageContent) ||
      tenantConfig.welcomeMessage ||
      t("msg.waitingMsg")
    );
  };

  const renderMessagePreview = () => {
    const message = getMessageContent();
    return message.split("\n\n").map((paragraph, index) => (
      <p key={index} className="text-gray-700 text-lg leading-relaxed mb-4">
        {paragraph}
      </p>
    ));
  };

  const renderFullMessage = () => {
    const message = getMessageContent();
    return message.split("\n\n").map((paragraph, index) => (
      <p key={index} className="text-gray-700 text-lg leading-relaxed mb-4">
        {paragraph}
      </p>
    ));
  };

  function lightenColor(color: string, percent: number) {
    const R = parseInt(color.substring(1, 3), 16);
    const G = parseInt(color.substring(3, 5), 16);
    const B = parseInt(color.substring(5, 7), 16);
    const newR = Math.min(255, R + Math.round((255 - R) * (percent / 100)));
    const newG = Math.min(255, G + Math.round((255 - G) * (percent / 100)));
    const newB = Math.min(255, B + Math.round((255 - B) * (percent / 100)));
    return `#${newR.toString(16).padStart(2, "0")}${newG
      .toString(16)
      .padStart(2, "0")}${newB.toString(16).padStart(2, "0")}`;
  }

  return (
    <>
      <div
        className="min-h-screen flex items-center justify-center pt-1 pb-4 px-4 md:pt-1 md:pb-10 md:px-10"
        style={{
          background: `linear-gradient(
            to bottom,
            ${lightenColor(
              theme?.find((i) => i.type === "PRIMARY_COLOR")?.value ||
                tenantConfig.primaryColor,
              30,
            )},
            ${lightenColor(
              theme?.find((i) => i.type === "SECONDARY_COLOR")?.value ||
                tenantConfig.secondaryColor ||
                tenantConfig.primaryColor,
              55,
            )}
          )`,
        }}
      >
        <div className="max-w-6xl w-full">
          <div className="text-center mb-12">
            <h1 className="text-4xl md:text-5xl font-bold text-gray-800 mb-4">
              {t("officeHead.title")}
            </h1>
            <div className="w-24 h-1 bg-indigo-600 mx-auto"></div>
          </div>

          <div className="bg-white rounded-2xl shadow-xl overflow-hidden transition-all duration-300 hover:shadow-2xl">
            <div className="flex flex-col md:flex-row">
              {/* Image / Logo Section */}
              <div className="md:w-2/5 relative">
                <img
                  src={imageSrc}
                  alt={displayName}
                  className={`w-full h-64 md:h-full transition-opacity duration-500 ${
                    isPersonPhoto
                      ? "object-cover"
                      : "object-contain bg-white p-6"
                  }`}
                />

                {/* Name and Position Overlay */}
                <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-transparent flex items-end p-6 md:p-8">
                  <div>
                    <h2 className="text-2xl md:text-3xl font-bold text-white mb-2">
                      {displayName}
                    </h2>
                    {displayPosition && (
                      <p className="text-gray-200 text-lg">{displayPosition}</p>
                    )}
                  </div>
                </div>

                {/* Decorative Element */}
                <div className="absolute top-6 right-6 bg-white text-indigo-600 rounded-full p-2 shadow-lg">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className="h-6 w-6"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                </div>
              </div>

              {/* Message Section */}
              <div className="md:w-3/5 p-6 md:p-8 flex flex-col justify-center min-h-[470px]">
                <div className="mb-6">
                  <div className="flex items-center mb-6">
                    <div className="w-10 h-1 bg-indigo-600 mr-3"></div>
                    <h3 className="text-lg font-semibold text-indigo-600 uppercase tracking-wide">
                      {localizedName(officeHead?.messageTitle) ||
                        t("officeHead.subtitle")}
                    </h3>
                  </div>

                  {/* Message content with fixed height */}
                  <div
                    ref={setMessageRef}
                    className="max-h-64 overflow-hidden relative"
                  >
                    {renderMessagePreview()}
                    {/* Gradient overlay to fade out text */}
                    {showReadMore && (
                      <div className="absolute bottom-0 left-0 right-0 h-12 bg-gradient-to-t from-white to-transparent"></div>
                    )}
                  </div>

                  {/* Read More Button */}
                  {showReadMore && (
                    <div className="text-center mt-4">
                      <button
                        onClick={() => setIsModalOpen(true)}
                        className="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200"
                        style={{
                          background: `linear-gradient(
                            to bottom,
                            ${lightenColor(
                              theme?.find((i) => i.type === "PRIMARY_COLOR")
                                ?.value || tenantConfig.primaryColor,
                              15,
                            )},
                            ${lightenColor(
                              theme?.find((i) => i.type === "SECONDARY_COLOR")
                                ?.value ||
                                tenantConfig.secondaryColor ||
                                tenantConfig.primaryColor,
                              30,
                            )}
                          )`,
                        }}
                      >
                        {t("newssection.readMore") || "Read Full Message"}
                        <svg
                          className="ml-2 -mr-1 h-5 w-5"
                          xmlns="http://www.w3.org/2000/svg"
                          viewBox="0 0 20 20"
                          fill="currentColor"
                        >
                          <path
                            fillRule="evenodd"
                            d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v3.586L7.707 9.293a1 1 0 10-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 10.586V7z"
                            clipRule="evenodd"
                          />
                        </svg>
                      </button>
                    </div>
                  )}
                </div>

                {/* Signature Section */}
                <div className="mt-8 pt-6 border-t border-gray-200">
                  <div className="flex flex-col">
                    <p className="text-gray-800 font-semibold text-xl">
                      {displayName}
                    </p>
                    {displayPosition && (
                      <p className="text-gray-600">{displayPosition}</p>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Modal for full message */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200 flex-shrink-0">
              <div className="flex items-center">
                <div className="w-8 h-1 bg-indigo-600 mr-3"></div>
                <h3 className="text-xl font-semibold text-indigo-600 uppercase tracking-wide">
                  {localizedName(officeHead?.messageTitle) ||
                    t("officeHead.subtitle")}
                </h3>
              </div>
              <button
                onClick={() => setIsModalOpen(false)}
                className="text-gray-400 hover:text-gray-600 transition-colors duration-200 p-1 rounded-full hover:bg-gray-100"
              >
                <svg
                  className="w-6 h-6"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>
            </div>

            {/* Modal Content */}
            <div className="p-6 overflow-y-auto custom-scrollbar flex-1">
              <div className="prose prose-lg max-w-none">
                {renderFullMessage()}
              </div>
            </div>

            {/* Modal Footer - Fixed layout to prevent cutting */}
            <div className="border-t border-gray-200 bg-gray-50 flex-shrink-0">
              <div className="p-6">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                  <div className="flex-1 min-w-0">
                    {" "}
                    {/* Added min-w-0 to prevent text overflow */}
                    <p className="text-gray-800 font-semibold text-lg truncate">
                      {localizedName(officeHead?.employee?.name)}
                    </p>
                    <p className="text-gray-600 text-sm truncate">
                      {localizedName(
                        officeHead?.employee?.employeePositions?.[0]?.position
                          ?.name
                      ) || t("officeHead.defaultPosition")}
                    </p>
                  </div>
                  <button
                    onClick={() => setIsModalOpen(false)}
                    className="px-6 py-2 border border-gray-300 text-base font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200 flex-shrink-0"
                  >
                    {t("preview.close") || "Close"}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default OfficeHeadMessage;
