// File Path: monorepo/web/frontend/src/pages/Admin/Setting/SkillCategory/Update/Page.jsx
import React, { useState, useEffect, useMemo, memo } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { useSkillCategoryManager } from "../../../../../services/Services";
import {
  UIXThemeProvider,
  Breadcrumb,
  PageHeader,
  Alert,
  FormCard,
  Input,
  Select,
  Button,
  BackToDetailsButton,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  AcademicCapIcon,
  XMarkIcon,
  PlusIcon,
  InformationCircleIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  Cog6ToothIcon,
  ExclamationTriangleIcon,
  HashtagIcon,
  HomeIcon,
  PencilSquareIcon,
} from "@heroicons/react/24/outline";

function SettingSkillCategoryUpdatePage() {
  return (
    <UIXThemeProvider>
      <SettingSkillCategoryUpdatePageContent />
    </UIXThemeProvider>
  );
}

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

    // Memoize theme classes
    const themeClasses = useMemo(
      () => ({
        textError: getThemeClasses("text-error"),
        borderError: getThemeClasses("border-error"),
        bgMuted: getThemeClasses("bg-muted"),
        textMuted: getThemeClasses("text-muted"),
        focusRing: getThemeClasses("focus-ring"),
        borderPrimary: getThemeClasses("border-primary"),
      }),
      [getThemeClasses],
    );

    // Form state
    const [formData, setFormData] = useState({
      name: "",
      description: "",
      status: 1,
    });

    // UI state
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const [validationErrors, setValidationErrors] = useState({});
    const [successMessage, setSuccessMessage] = useState("");
    const [skillCategory, setSkillCategory] = useState(null);
    const [hasChanges, setHasChanges] = useState(false);

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

    // Load existing skill category data using real API
    const loadSkillCategoryData = async () => {
      try {
        setIsLoading(true);
        setError(null);

        if (import.meta.env.DEV) {
          console.log(
            "SkillCategoryUpdatePage: Loading skill category data for ID:",
            id,
          );
        }

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

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

        if (data && data.id) {
          setSkillCategory(data);

          // Populate form with existing data
          setFormData({
            name: data.name || "",
            description: data.description || "",
            status: data.status || 1,
          });

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

    // Load data on component mount
    useEffect(() => {
      window.scrollTo(0, 0);
      loadSkillCategoryData();
    }, [id]);

    // Handle form field changes
    const handleInputChange = (fieldName, value) => {
      let processedValue = value;

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

      // Check for changes
      if (skillCategory) {
        const originalValue = skillCategory[fieldName];
        const hasFieldChanged = value !== originalValue;

        // Check if any field has changed
        const newFormData = { ...formData, [fieldName]: value };
        const hasAnyChanges = Object.keys(newFormData).some(
          (key) => newFormData[key] !== skillCategory[key],
        );

        setHasChanges(hasAnyChanges);
      }

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

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

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

      // Validate description (optional, max length)
      if (formData.description && formData.description.length > 500) {
        errors.description = "Description must be less than 500 characters";
      }

      return errors;
    };

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

      // Check if skill category data is available
      if (!skillCategory || !skillCategory.id) {
        setError(
          "Skill category information not available. Please refresh the page.",
        );
        return;
      }

      // 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 skillCategoryData = {
          name: formData.name.trim(),
          description: formData.description.trim(),
          status: parseInt(formData.status, 10),
        };

        if (import.meta.env.DEV) {
          console.log(
            "SkillCategoryUpdatePage: Submitting skill category update:",
            skillCategoryData,
          );
        }

        // Update via SkillCategoryManager
        await skillCategoryManager.updateSkillCategory(
          skillCategory.id,
          skillCategoryData,
          onUnauthorized,
        );

        if (import.meta.env.DEV) {
          console.log(
            "SkillCategoryUpdatePage: Skill category updated successfully",
          );
        }

        // Navigate to detail page immediately with success message
        navigate(`/admin/settings/skill-category/${id}/detail`, {
          state: {
            successMessage: "Skill category updated successfully",
          },
        });
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error(
            "SkillCategoryUpdatePage: Failed to update skill category:",
            err,
          );
        }

        // Handle validation errors from API
        if (err && typeof err === "object" && !err.message) {
          setValidationErrors(err);
          setError("Please correct the errors below");
        } else {
          setError(err.message || "Failed to update skill category");
        }
        window.scrollTo(0, 0);
      } finally {
        setIsSubmitting(false);
      }
    };

    // Handle cancel
    const handleCancel = () => {
      const originalData = {
        name: skillCategory?.name || "",
        description: skillCategory?.description || "",
        status: skillCategory?.status || 1,
      };

      if (
        formData.name !== originalData.name ||
        formData.description !== originalData.description ||
        formData.status !== originalData.status
      ) {
        if (
          window.confirm(
            "Are you sure you want to cancel? Your changes will be lost.",
          )
        ) {
          navigate(`/admin/settings/skill-category/${id}/detail`);
        }
      } else {
        navigate(`/admin/settings/skill-category/${id}/detail`);
      }
    };

    // Status options
    const statusOptions = [
      { value: 1, label: "Active" },
      { value: 0, label: "Inactive" },
    ];

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

    // Loading state
    if (isLoading) {
      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 can't load initial data
    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="relative 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 || "Update",
                to: `/admin/settings/skill-category/${id}/detail`,
                icon: AcademicCapIcon,
              },
              {
                label: "Edit",
                icon: PencilSquareIcon,
                isActive: true,
              },
            ]}
          />

          <PageHeader
            icon={PencilSquareIcon}
            title="Edit Skill Category"
            subtitle={hasChanges ? "Unsaved changes" : undefined}
            subtitleIcon={hasChanges ? ExclamationTriangleIcon : undefined}
            actions={[
              <BackToDetailsButton
                key="back-to-details"
                onClick={() =>
                  navigate(`/admin/settings/skill-category/${id}/detail`)
                }
              />,
            ]}
          />

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

          {/* Main Content Layout - Centered */}
          <div className="max-w-4xl mx-auto">
            <FormCard title="Skill Category Information">
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  handleSubmit();
                }}
              >
                <div className="space-y-6">
                  {/* Name Field */}
                  <Input
                    label="Skill Category Name"
                    name="name"
                    type="text"
                    value={formData.name}
                    onChange={(value) => handleInputChange("name", value)}
                    error={validationErrors.name}
                    placeholder="e.g., Technical Skills, Communication Skills, Leadership"
                    helperText="Enter a descriptive name for the skill category"
                    required
                  />

                  {/* Description Field */}
                  <div>
                    <label
                      htmlFor="description"
                      className={`block text-base sm:text-lg font-semibold ${getThemeClasses("text-secondary")} mb-3`}
                    >
                      Description
                    </label>
                    <textarea
                      id="description"
                      name="description"
                      value={formData.description || ""}
                      onChange={(e) =>
                        handleInputChange("description", e.target.value)
                      }
                      placeholder="Describe the purpose and characteristics of this skill category..."
                      disabled={isSubmitting}
                      maxLength={500}
                      rows={4}
                      autoComplete="off"
                      className={`
                      w-full px-5 py-4 border-2 ${getThemeClasses("border-secondary")} rounded-xl shadow-sm
                      transition-all duration-200 ${getThemeClasses("placeholder-text")} resize-none
                      focus:outline-none ${themeClasses.focusRing} ${themeClasses.borderPrimary}
                      text-base sm:text-lg ${getThemeClasses("bg-primary")} ${getThemeClasses("text-primary")}
                      ${validationErrors.description ? `${themeClasses.borderError}` : ""}
                      ${isSubmitting ? `${themeClasses.bgMuted} cursor-not-allowed` : ""}
                    `}
                    />
                    {validationErrors.description && (
                      <p
                        className={`mt-1 text-sm ${themeClasses.textError} flex items-center`}
                      >
                        <ExclamationTriangleIcon className="h-4 w-4 mr-1" />
                        {validationErrors.description}
                      </p>
                    )}
                    <div
                      className={`mt-1 flex justify-between text-xs ${themeClasses.textMuted}`}
                    >
                      <span>
                        Provide a detailed description of what types of skills
                        belong in this category
                      </span>
                      <span>
                        {formData.description?.length || 0}/500 characters
                      </span>
                    </div>
                  </div>

                  {/* Status Field */}
                  <Select
                    label="Status"
                    name="status"
                    value={formData.status}
                    onChange={(value) =>
                      handleInputChange("status", parseInt(value))
                    }
                    options={statusOptions}
                    error={validationErrors.status}
                    helperText="Set the status of the skill category"
                  />
                </div>

                {/* Form Actions */}
                <div
                  className={`flex flex-col sm:flex-row sm:justify-end sm:space-x-4 space-y-3 sm:space-y-0 pt-8 border-t ${getThemeClasses("border-secondary")} mt-8`}
                >
                  <Button
                    type="button"
                    variant="secondary"
                    onClick={handleCancel}
                    disabled={isSubmitting}
                  >
                    Cancel
                  </Button>
                  <Button
                    type="submit"
                    variant="primary"
                    loading={isSubmitting}
                    loadingText="Updating..."
                    icon={CheckCircleIcon}
                    disabled={!hasChanges}
                  >
                    Update Skill Category
                  </Button>
                </div>
              </form>
            </FormCard>
          </div>
        </div>
      </div>
    );
  },
);

SettingSkillCategoryUpdatePageContent.displayName =
  "SettingSkillCategoryUpdatePageContent";

export default SettingSkillCategoryUpdatePage;
