// File Path: monorepo/web/frontend/src/pages/Admin/Setting/HowHearAboutUsItem/Create/Page.jsx
import React, { useState, useEffect, useMemo, useCallback, memo } from "react";
import { Link, useNavigate } from "react-router";
import { useHowHearAboutUsItemManager } from "../../../../../services/Services";
import {
  Breadcrumb,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  MegaphoneIcon,
  ChevronRightIcon,
  XMarkIcon,
  PlusIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  Cog6ToothIcon,
  ChartBarIcon,
  DocumentCheckIcon,
  ExclamationCircleIcon,
  UserGroupIcon,
  UsersIcon,
  BriefcaseIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";

function SettingHowHearAboutUsItemCreatePage() {
  return (
    <UIXThemeProvider>
      <SettingHowHearAboutUsItemCreatePageContent />
    </UIXThemeProvider>
  );
}

const SettingHowHearAboutUsItemCreatePageContent = memo(
  function SettingHowHearAboutUsItemCreatePageContent() {
    const navigate = useNavigate();
    const howHearAboutUsItemManager = useHowHearAboutUsItemManager();
    const { getThemeClasses } = useUIXTheme();

    // Memoize theme classes
    const themeClasses = useMemo(
      () => ({
        bgGradientPrimary: getThemeClasses("bg-gradient-primary"),
        buttonPrimary: getThemeClasses("button-primary"),
        buttonPrimaryHover: getThemeClasses("button-primary-hover"),
        loadingSpinner: getThemeClasses("loading-spinner"),
      }),
      [getThemeClasses],
    );

    // Form state
    const [formData, setFormData] = useState({
      sortNumber: 1,
      text: "",
      isForFacilitator: true,
      isForCustomer: true,
      isForStaff: true,
    });

    // UI state
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState(null);
    const [validationErrors, setValidationErrors] = useState({});
    const [successMessage, setSuccessMessage] = useState("");

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

    // Handle form field changes
    const handleInputChange = useCallback(
      (e) => {
        const { name, value } = e.target;
        let processedValue = value;

        // Handle sortNumber as integer
        if (name === "sortNumber") {
          processedValue = parseInt(value) || 0;
        }

        setFormData((prev) => ({
          ...prev,
          [name]: processedValue,
        }));

        // Clear validation error for this field when user starts typing
        if (validationErrors[name]) {
          setValidationErrors((prev) => ({
            ...prev,
            [name]: null,
          }));
        }
      },
      [validationErrors],
    );

    // Handle checkbox changes
    const handleCheckboxChange = useCallback(
      (field) => {
        setFormData((prev) => ({
          ...prev,
          [field]: !prev[field],
        }));

        // Clear role validation error
        if (validationErrors.roles) {
          setValidationErrors((prev) => ({
            ...prev,
            roles: null,
          }));
        }
      },
      [validationErrors],
    );

    // Validate form data
    const validateForm = useCallback(() => {
      const errors = {};

      // Validate text (required, max length)
      if (!formData.text || !formData.text.trim()) {
        errors.text = "Text is required";
      } else if (formData.text.length > 255) {
        errors.text = "Text must be less than 255 characters";
      }

      // Validate sort number
      if (typeof formData.sortNumber !== "number" || formData.sortNumber < 0) {
        errors.sortNumber = "Sort number must be a positive number";
      }

      // Validate at least one role is selected
      if (
        !formData.isForFacilitator &&
        !formData.isForCustomer &&
        !formData.isForStaff
      ) {
        errors.roles = "At least one role must be selected";
      }

      return errors;
    }, [formData]);

    // Handle form submission
    const handleSubmit = useCallback(async () => {
      // Clear previous errors
      setError(null);
      setValidationErrors({});

      // Validate form
      const errors = validateForm();
      if (Object.keys(errors).length > 0) {
        setValidationErrors(errors);
        setError("Please correct the errors below");
        window.scrollTo(0, 0);
        return;
      }

      try {
        setIsSubmitting(true);

        // Prepare data for API
        const submitData = {
          sortNumber: formData.sortNumber,
          text: formData.text.trim(),
          isForFacilitator: formData.isForFacilitator,
          isForCustomer: formData.isForCustomer,
          isForStaff: formData.isForStaff,
        };

        if (import.meta.env.DEV) {
        console.log(
          "HowHearAboutUsItemCreatePage: Submitting item creation:",
          submitData,
        );
        }

        // Create how hear about us item
        const createdItem = await howHearAboutUsItemManager.create(
          submitData,
          onUnauthorized,
        );

        if (import.meta.env.DEV) {
        console.log("HowHearAboutUsItemCreatePage: Item created successfully");
        setSuccessMessage("How Hear About Us Item created successfully!");
        }

        // Navigate to detail page with success message
        setTimeout(() => {
          navigate(
            `/admin/settings/how-hear-about-us-item/${createdItem.id}/detail`,
            {
              state: {
                successMessage: "How Hear About Us Item created successfully",
              },
            },
          );
        }, 1500);
      } catch (err) {
        if (import.meta.env.DEV) {
        console.error(
          "HowHearAboutUsItemCreatePage: Failed to create item:",
          err,
        );
        }

        // Handle validation errors from API
        if (err.validationErrors) {
          setValidationErrors(err.validationErrors);
          setError("Please correct the errors below and try again.");
        } else if (err && typeof err === "object" && !err.message) {
          setValidationErrors(err);
          setError("Please correct the errors below");
        } else {
          setError(err.message || "Failed to create item");
        }
        window.scrollTo(0, 0);
      } finally {
        setIsSubmitting(false);
      }
    }, [
      formData,
      validateForm,
      howHearAboutUsItemManager,
      onUnauthorized,
      navigate,
    ]);

    // Handle cancel
    const handleCancel = useCallback(() => {
      if (
        formData.text ||
        formData.sortNumber !== 1 ||
        !formData.isForFacilitator ||
        !formData.isForCustomer ||
        !formData.isForStaff
      ) {
        if (
          window.confirm(
            "Are you sure you want to cancel? Your changes will be lost.",
          )
        ) {
          navigate("/admin/settings/how-hear-about-us-items");
        }
      } else {
        navigate("/admin/settings/how-hear-about-us-items");
      }
    }, [formData, navigate]);

    // Auto-clear success message
    useEffect(() => {
      if (successMessage) {
        const timer = setTimeout(() => setSuccessMessage(""), 5000);
        return () => clearTimeout(timer);
      }
    }, [successMessage]);

    return (
      <div className={`min-h-screen ${themeClasses.bgGradientPrimary}`}>
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          {/* 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: "Create",
                icon: PlusIcon,
                isActive: true,
              },
            ]}
          />

          {/* Header Section - Enhanced with title and back button */}
          <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-start">
                  <div
                    className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${themeClasses.buttonPrimary}`}
                  >
                    <PlusIcon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                  </div>
                  <div className="text-center lg:text-left">
                    <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-gray-800 leading-tight">
                      Create How Hear About Us Item
                    </h1>
                    <p className="mt-2 text-base sm:text-lg lg:text-xl text-gray-600 font-medium">
                      Add a new option for tracking how users discovered your
                      service
                    </p>
                  </div>
                </div>
              </div>
              <div className="flex-shrink-0">
                <Link
                  to="/admin/settings/how-hear-about-us-items"
                  className="inline-flex items-center px-5 py-3 border border-gray-200 rounded-xl shadow-sm text-sm sm:text-base font-medium text-gray-700 bg-white hover:bg-gray-50 hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-all duration-200"
                >
                  <ArrowLeftIcon className="h-4 w-4 sm:h-5 sm:w-5 mr-2" />
                  Back to List
                </Link>
              </div>
            </div>
          </div>

          {/* Success Message */}
          {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 Message */}
          {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">
                <ExclamationCircleIcon 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>
          )}

          {/* Main Content Card - Single centered layout */}
          <div className="bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100">
            <div className={`px-6 py-4 ${themeClasses.buttonPrimary}`}>
              <h2 className="text-base font-bold text-white uppercase tracking-wider flex items-center">
                <DocumentCheckIcon className="w-5 h-5 mr-2" />
                Item Information
              </h2>
            </div>

            <div className="p-6">
              <div className="space-y-6">
                {/* Sort Number Field */}
                <div>
                  <label
                    htmlFor="sortNumber"
                    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>
                  </label>
                  <input
                    type="number"
                    id="sortNumber"
                    name="sortNumber"
                    value={formData.sortNumber}
                    onChange={handleInputChange}
                    min="0"
                    placeholder="Enter sort number (e.g., 1, 2, 3...)"
                    disabled={isSubmitting}
                    className={`w-full px-5 py-4 border-2 border-gray-200 rounded-xl shadow-sm focus:outline-none focus:ring-4 focus:ring-red-500/20 focus:border-red-500 text-base sm:text-lg transition-all duration-200 placeholder-gray-400 ${
                      validationErrors.sortNumber
                        ? "border-red-500"
                        : "border-gray-300"
                    } ${isSubmitting ? "bg-gray-50 cursor-not-allowed" : ""}`}
                  />
                  {validationErrors.sortNumber && (
                    <p className="mt-1 text-sm text-red-600">
                      {validationErrors.sortNumber}
                    </p>
                  )}
                  <p className="mt-1 text-xs text-gray-500">
                    Lower numbers appear first in lists
                  </p>
                </div>

                {/* Text Field */}
                <div>
                  <label
                    htmlFor="text"
                    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>
                  <input
                    type="text"
                    id="text"
                    name="text"
                    value={formData.text}
                    onChange={handleInputChange}
                    maxLength={255}
                    placeholder="Enter the display text (e.g., 'Google Search', 'Referral from friend')"
                    disabled={isSubmitting}
                    className={`w-full px-5 py-4 border-2 border-gray-200 rounded-xl shadow-sm focus:outline-none focus:ring-4 focus:ring-red-500/20 focus:border-red-500 text-base sm:text-lg transition-all duration-200 placeholder-gray-400 ${
                      validationErrors.text
                        ? "border-red-500"
                        : "border-gray-300"
                    } ${isSubmitting ? "bg-gray-50 cursor-not-allowed" : ""}`}
                  />
                  {validationErrors.text && (
                    <p className="mt-1 text-sm text-red-600">
                      {validationErrors.text}
                    </p>
                  )}
                  <div className="mt-1 text-right">
                    <span
                      className={`text-xs ${
                        formData.text.length > 200
                          ? "text-amber-600"
                          : "text-gray-500"
                      }`}
                    >
                      {formData.text.length}/255 characters
                    </span>
                  </div>
                </div>

                {/* Role Configuration */}
                <div>
                  <label 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>
                  </label>
                  <p className="text-sm text-gray-500 mb-4">
                    Select which user roles can use this option
                  </p>
                  {validationErrors.roles && (
                    <p className="mb-3 text-sm text-red-600">
                      {validationErrors.roles}
                    </p>
                  )}

                  <div className="space-y-4">
                    {/* Facilitator Checkbox */}
                    <label
                      className={`flex items-start p-4 rounded-xl border-2 cursor-pointer transition-all duration-200 ${
                        formData.isForFacilitator
                          ? "bg-red-50 border-red-500 shadow-md"
                          : "bg-white border-gray-200 hover:border-gray-300 hover:shadow-sm"
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={formData.isForFacilitator}
                        onChange={() =>
                          handleCheckboxChange("isForFacilitator")
                        }
                        disabled={isSubmitting}
                        className="mt-1 w-5 h-5 text-red-600 bg-gray-100 border-gray-300 rounded focus:ring-red-500"
                      />
                      <div className="ml-4">
                        <div className="flex items-center">
                          <BriefcaseIcon className="w-5 h-5 mr-2 text-red-500" />
                          <span className="text-base font-medium text-gray-900">
                            For Facilitators
                          </span>
                        </div>
                        <p className="text-sm text-gray-500 mt-1">
                          Facilitators can select this option when registering
                        </p>
                      </div>
                    </label>

                    {/* Customer Checkbox */}
                    <label
                      className={`flex items-start p-4 rounded-xl border-2 cursor-pointer transition-all duration-200 ${
                        formData.isForCustomer
                          ? "bg-red-50 border-red-500 shadow-md"
                          : "bg-white border-gray-200 hover:border-gray-300 hover:shadow-sm"
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={formData.isForCustomer}
                        onChange={() => handleCheckboxChange("isForCustomer")}
                        disabled={isSubmitting}
                        className="mt-1 w-5 h-5 text-red-600 bg-gray-100 border-gray-300 rounded focus:ring-red-500"
                      />
                      <div className="ml-4">
                        <div className="flex items-center">
                          <UsersIcon className="w-5 h-5 mr-2 text-red-500" />
                          <span className="text-base font-medium text-gray-900">
                            For Customers
                          </span>
                        </div>
                        <p className="text-sm text-gray-500 mt-1">
                          Customers can select this option when registering
                        </p>
                      </div>
                    </label>

                    {/* Staff Checkbox */}
                    <label
                      className={`flex items-start p-4 rounded-xl border-2 cursor-pointer transition-all duration-200 ${
                        formData.isForStaff
                          ? "bg-red-50 border-red-500 shadow-md"
                          : "bg-white border-gray-200 hover:border-gray-300 hover:shadow-sm"
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={formData.isForStaff}
                        onChange={() => handleCheckboxChange("isForStaff")}
                        disabled={isSubmitting}
                        className="mt-1 w-5 h-5 text-red-600 bg-gray-100 border-gray-300 rounded focus:ring-red-500"
                      />
                      <div className="ml-4">
                        <div className="flex items-center">
                          <UserGroupIcon className="w-5 h-5 mr-2 text-red-500" />
                          <span className="text-base font-medium text-gray-900">
                            For Staff
                          </span>
                        </div>
                        <p className="text-sm text-gray-500 mt-1">
                          Staff can select this option when creating records
                        </p>
                      </div>
                    </label>
                  </div>
                </div>
              </div>
            </div>

            {/* Form Actions */}
            <div
              className={`px-6 py-4 ${themeClasses.bgGradientPrimary} border-t border-gray-200`}
            >
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500">
                    Fill in the required fields to create the item
                  </p>
                </div>
                <div className="flex items-center gap-4">
                  <button
                    type="button"
                    onClick={handleCancel}
                    disabled={isSubmitting}
                    className="inline-flex items-center px-4 py-3 rounded-xl border border-gray-200 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
                  >
                    Cancel
                  </button>
                  <button
                    type="button"
                    onClick={handleSubmit}
                    disabled={isSubmitting}
                    className={`inline-flex items-center px-6 sm:px-8 py-3 sm:py-4 border text-sm sm:text-base font-bold rounded-xl shadow-lg focus:outline-none transition-all duration-200 border-transparent text-white hover:shadow-xl focus:ring-4 focus:ring-red-500/20 transform hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed ${themeClasses.buttonPrimary} ${themeClasses.buttonPrimaryHover}`}
                  >
                    {isSubmitting ? (
                      <>
                        <svg
                          className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                          xmlns="http://www.w3.org/2000/svg"
                          fill="none"
                          viewBox="0 0 24 24"
                        >
                          <circle
                            className="opacity-25"
                            cx="12"
                            cy="12"
                            r="10"
                            stroke="currentColor"
                            strokeWidth="4"
                          ></circle>
                          <path
                            className="opacity-75"
                            fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                          ></path>
                        </svg>
                        Creating...
                      </>
                    ) : (
                      <>
                        <CheckCircleIcon className="w-4 h-4 mr-2" />
                        Create Item
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>

          {/* Loading Overlay */}
          {isSubmitting && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div className="bg-white rounded-lg p-6 shadow-xl">
                <div className="flex items-center space-x-4">
                  <div
                    className={`animate-spin rounded-full h-8 w-8 border-b-2 ${themeClasses.loadingSpinner}`}
                  ></div>
                  <div>
                    <p className="text-lg font-medium text-gray-900">
                      Creating How Hear About Us Item...
                    </p>
                    <p className="text-sm text-gray-500">
                      Please wait while we save your changes.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  },
);

SettingHowHearAboutUsItemCreatePageContent.displayName =
  "SettingHowHearAboutUsItemCreatePageContent";

export default SettingHowHearAboutUsItemCreatePage;
