// File Path: monorepo/web/frontend/src/pages/Admin/Setting/FacilitatorAwayLog/Update/Page.jsx

import React, { useState, useEffect } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
  useFacilitatorAwayLogManager,
} from "../../../../../services/Services";
import {
  UIXThemeProvider,
  useUIXTheme,
  Breadcrumb,
  PageHeader,
  Alert,
  FormCard,
  Input,
  Select,
  Button,
  DetailPageIcon,
  Modal,
} from "../../../../../components/UIX";
import {
  CalendarDaysIcon,
  ChevronRightIcon,
  XMarkIcon,
  PencilSquareIcon,
  ExclamationTriangleIcon,
  ArrowPathIcon,
  CheckCircleIcon,
  Cog6ToothIcon,
  ChartBarIcon,
  ClipboardDocumentIcon,
  InformationCircleIcon,
  ArrowLeftIcon,
  DocumentTextIcon,
  UserGroupIcon,
  CalendarIcon,
  ClockIcon,
  BriefcaseIcon,
  SparklesIcon,
} from "@heroicons/react/24/outline";

const REASON_OPTIONS = [
  { value: 2, label: "Going on vacation" },
  { value: 3, label: "Personal reasons" },
  { value: 4, label: "Commercial insurance expired" },
  { value: 5, label: "Policy check expired" },
  { value: 6, label: "Auto Insurance Expired" },
  { value: 7, label: "WSIB Expired" },
  { value: 8, label: "Dues Date Expired" },
  { value: 1, label: "Other" },
];

const UNTIL_FURTHER_NOTICE_OPTIONS = [
  { value: 1, label: "Yes" },
  { value: 2, label: "No" },
];

// Helper functions to get labels from IDs
const getReasonLabel = (reasonId) => {
  const reason = REASON_OPTIONS.find(option => option.value === parseInt(reasonId));
  return reason ? reason.label : `Reason ID: ${reasonId}`;
};

const getUntilFurtherNoticeLabel = (untilFurtherNoticeId) => {
  const option = UNTIL_FURTHER_NOTICE_OPTIONS.find(option => option.value === parseInt(untilFurtherNoticeId));
  return option ? option.label : `Option ID: ${untilFurtherNoticeId}`;
};

function SettingFacilitatorAwayLogUpdatePage() {
  return (
    <UIXThemeProvider>
      <SettingFacilitatorAwayLogUpdatePageContent />
    </UIXThemeProvider>
  );
}

function SettingFacilitatorAwayLogUpdatePageContent() {
  const facilitatorAwayLogManager = useFacilitatorAwayLogManager();
  const navigate = useNavigate();
  const { id } = useParams();
  const { getThemeClasses } = useUIXTheme();

  // State management
  const [loading, setLoading] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [formErrors, setFormErrors] = useState({});
  const [hasChanges, setHasChanges] = useState(false);
  const [showCancelModal, setShowCancelModal] = useState(false);

  // Form state
  const [formData, setFormData] = useState({
    facilitatorId: "",
    facilitatorName: "",
    reason: "",
    reasonLabel: "",
    reasonOther: "",
    untilFurtherNotice: "",
    untilFurtherNoticeLabel: "",
    untilDate: "",
    startDate: "",
  });

  // Original data for comparison
  const [originalData, setOriginalData] = useState(null);

  // Facilitator data is now read-only, no dropdown needed

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

  // Facilitator fetching removed - using read-only display

  // Fetch facilitator away log data
  const fetchFacilitatorAwayLogData = async () => {
    try {
      setInitialLoading(true);
      setError(null);

      const response =
        await facilitatorAwayLogManager.getFacilitatorAwayLogDetail(
          id,
          onUnauthorized,
        );

      // Format dates for input fields
      const formattedData = {
        facilitatorId: response.facilitatorId?.toString() || "",
        facilitatorName: response.facilitatorName || "",
        reason: response.reason || "",
        reasonLabel: getReasonLabel(response.reason),
        reasonOther: response.reasonOther || "",
        untilFurtherNotice: response.untilFurtherNotice || "",
        untilFurtherNoticeLabel: getUntilFurtherNoticeLabel(response.untilFurtherNotice),
        untilDate: response.untilDate
          ? formatDateForInput(response.untilDate)
          : "",
        startDate: response.startDate
          ? formatDateForInput(response.startDate)
          : "",
      };

      setFormData(formattedData);
      setOriginalData(response);
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error("Failed to fetch facilitator away log data:", err);
      setError(err.message || "Failed to load facilitator away log data");
      }
    } finally {
      setInitialLoading(false);
    }
  };

  // Handle form field changes
  const handleInputChange = (field, value) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }));

    // Clear field error when user starts typing
    if (formErrors[field]) {
      setFormErrors((prev) => ({
        ...prev,
        [field]: null,
      }));
    }
  };

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

    // Facilitator validation removed - field is now read-only

    if (!formData.reason) {
      errors.reason = "Reason is required";
    }

    if (formData.reason === 1 && !formData.reasonOther?.trim()) {
      errors.reasonOther = "Please specify the reason";
    }

    if (!formData.untilFurtherNotice) {
      errors.untilFurtherNotice =
        "Please specify if this is until further notice";
    }

    if (formData.untilFurtherNotice === 2 && !formData.untilDate) {
      errors.untilDate = "Until date is required when not until further notice";
    }

    if (!formData.startDate) {
      errors.startDate = "Start date is required";
    }

    // Validate dates
    if (formData.startDate && formData.untilDate) {
      const startDate = new Date(formData.startDate);
      const untilDate = new Date(formData.untilDate);

      if (untilDate <= startDate) {
        errors.untilDate = "Until date must be after start date";
      }
    }

    return errors;
  };

  // Check if form has changes
  useEffect(() => {
    if (originalData) {
      const changed =
        // Check all editable fields (facilitator is read-only)
        formData.reason !== originalData.reason ||
        formData.reasonOther !== (originalData.reasonOther || "") ||
        formData.untilFurtherNotice !== originalData.untilFurtherNotice ||
        formData.untilDate !==
          (originalData.untilDate
            ? formatDateForInput(originalData.untilDate)
            : "") ||
        formData.startDate !==
          (originalData.startDate
            ? formatDateForInput(originalData.startDate)
            : "");

      setHasChanges(changed);
    }
  }, [formData, originalData]);

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();

    // Check if there are changes
    if (!hasChanges) {
      setError("No changes detected");
      return;
    }

    // Validate form
    const errors = validateForm();
    if (Object.keys(errors).length > 0) {
      setFormErrors(errors);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      setFormErrors({});

      // Prepare data for API
      const submitData = {
        facilitatorId: originalData.facilitatorId, // Use original ObjectID
        reason: parseInt(formData.reason),
        reasonOther: formData.reasonOther?.trim() || "",
        untilFurtherNotice: parseInt(formData.untilFurtherNotice),
        untilDate: parseInt(formData.untilFurtherNotice) === 2 ? formData.untilDate : "",
        startDate: formData.startDate,
      };

      await facilitatorAwayLogManager.updateFacilitatorAwayLogModern(
        id,
        submitData,
        onUnauthorized,
      );

      setSuccess("Facilitator away log updated successfully!");

      // Navigate back to detail page after short delay
      setTimeout(() => {
        navigate(`/admin/settings/facilitator-away-log/${id}/detail`);
      }, 1500);
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error("Failed to update facilitator away log:", err);

      if (err && typeof err === "object") {
        // Handle validation errors from API
        setFormErrors(err);
      }
      } else {
        setError(err.message || "Failed to update facilitator away log");
      }
    } finally {
      setLoading(false);
    }
  };

  // Handle reset form
  const handleReset = () => {
    if (originalData) {
      setFormData({
        facilitatorId: originalData.facilitatorId?.toString() || "",
        facilitatorName: originalData.facilitatorName || "",
        reason: originalData.reason || "",
        reasonLabel: getReasonLabel(originalData.reason),
        reasonOther: originalData.reasonOther || "",
        untilFurtherNotice: originalData.untilFurtherNotice || "",
        untilFurtherNoticeLabel: getUntilFurtherNoticeLabel(originalData.untilFurtherNotice),
        untilDate: originalData.untilDate
          ? formatDateForInput(originalData.untilDate)
          : "",
        startDate: originalData.startDate
          ? formatDateForInput(originalData.startDate)
          : "",
      });
      setFormErrors({});
      setError(null);
    }
  };

  // Handle cancel
  const handleCancel = () => {
    if (hasChanges) {
      setShowCancelModal(true);
    } else {
      navigate(`/admin/settings/facilitator-away-log/${id}/detail`);
    }
  };

  const handleConfirmCancel = () => {
    setShowCancelModal(false);
    navigate(`/admin/settings/facilitator-away-log/${id}/detail`);
  };

  // Initial load
  useEffect(() => {
    if (id) {
      fetchFacilitatorAwayLogData();
    } else {
      setError("No facilitator away log ID provided");
      setInitialLoading(false);
    }
  }, [id]);

  // Clear success message after 3 seconds
  useEffect(() => {
    if (success) {
      const timer = setTimeout(() => setSuccess(null), 3000);
      return () => clearTimeout(timer);
    }
  }, [success]);

  // Format date for input (YYYY-MM-DD)
  const formatDateForInput = (dateString) => {
    if (!dateString) return "";
    try {
      return new Date(dateString).toISOString().split("T")[0];
    } catch {
      return "";
    }
  };

  // Loading state
  if (initialLoading) {
    return (
      <div className={`min-h-screen ${getThemeClasses('bg-secondary')} flex items-center justify-center p-4`}>
        <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 facilitator away log...</p>
        </div>
      </div>
    );
  }

  // Error state
  if (error && !originalData) {
    return (
      <div className={`min-h-screen ${getThemeClasses('bg-secondary')} p-4 sm:p-6 lg:p-8`}>
        <div className="max-w-2xl mx-auto">
          <div className={`${getThemeClasses('alert-error-bg')} ${getThemeClasses('border-error')} px-4 py-3 rounded-lg mb-4`}>
            <p className={getThemeClasses('text-error')}>{error}</p>
          </div>
          <Link
            to="/admin/settings/facilitator-away-logs"
            className={`inline-flex items-center ${getThemeClasses('link-primary')}`}
          >
            <ArrowLeftIcon className="w-4 h-4 mr-2" />
            Back to Facilitator Away Logs
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className={`min-h-screen ${getThemeClasses('bg-secondary')}`}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-6">
        <Breadcrumb items={[
          {
            label: 'Dashboard',
            to: '/admin/dashboard',
            icon: ChartBarIcon
          },
          {
            label: 'Settings',
            to: '/admin/settings',
            icon: Cog6ToothIcon
          },
          {
            label: 'Away Logs',
            to: '/admin/settings/facilitator-away-logs',
            icon: CalendarDaysIcon
          },
          {
            label: 'Detail',
            to: `/admin/settings/facilitator-away-log/${id}/detail`,
            icon: ClipboardDocumentIcon
          },
          {
            label: 'Edit',
            icon: PencilSquareIcon,
            isActive: true
          }
        ]} />

        <PageHeader
          title="Edit Away Log"
          subtitle={hasChanges ? "Unsaved changes" : undefined}
          subtitleIcon={hasChanges ? ExclamationTriangleIcon : undefined}
          backButton={{
            text: "Back to Detail",
            onClick: () => navigate(`/admin/settings/facilitator-away-log/${id}/detail`)
          }}
        />

        {/* Success/Error Messages */}
        {success && (
          <Alert
            type="success"
            message={success}
            onClose={() => setSuccess(null)}
            className="mb-6"
          />
        )}

        {error && (
          <Alert
            type="error"
            message={error}
            onClose={() => setError(null)}
            className="mb-6"
          />
        )}

        {/* Main Content Layout */}
        <div className="max-w-4xl mx-auto">
          <FormCard title="Update Away Log Details">

            <div className="space-y-6">
              <form onSubmit={handleSubmit}>
                <div className="space-y-6">
                  {/* Facilitator (Read-only) */}
                  <Input
                    label="Facilitator"
                    value={formData.facilitatorName || `Facilitator ID: ${formData.facilitatorId}`}
                    disabled={true}
                    readOnly={true}
                    placeholder="Loading facilitator information..."
                    helperText="Facilitator assignment cannot be changed after creation"
                  />

                  {/* Reason Selection */}
                  <Select
                    id="reason"
                    name="reason"
                    value={formData.reason}
                    onChange={(value) => handleInputChange("reason", value)}
                    error={formErrors.reason}
                    required={true}
                    label="Reason"
                    placeholder="Select a reason"
                    options={REASON_OPTIONS}
                    disabled={loading}
                  />

                  {/* Other Reason (conditional) */}
                  {formData.reason === 1 && (
                    <Input
                      label="Specify Reason"
                      value={formData.reasonOther}
                      onChange={(e) => handleInputChange("reasonOther", e.target.value)}
                      placeholder="Please specify the reason"
                      disabled={loading}
                      error={formErrors.reasonOther}
                      required
                    />
                  )}

                  {/* Date Fields */}
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    {/* Start Date */}
                    <Input
                      type="date"
                      label="Start Date"
                      value={formData.startDate}
                      onChange={(e) => handleInputChange("startDate", e.target.value)}
                      disabled={loading}
                      error={formErrors.startDate}
                      required
                    />

                    {/* Until Further Notice */}
                    <Select
                      id="untilFurtherNotice"
                      name="untilFurtherNotice"
                      value={formData.untilFurtherNotice}
                      onChange={(value) => handleInputChange("untilFurtherNotice", value)}
                      error={formErrors.untilFurtherNotice}
                      required={true}
                      label="Until Further Notice?"
                      placeholder="Select Yes or No"
                      options={UNTIL_FURTHER_NOTICE_OPTIONS}
                      disabled={loading}
                    />
                  </div>

                  {/* Until Date (conditional) */}
                  {formData.untilFurtherNotice === 2 && (
                    <Input
                      type="date"
                      label="Until Date"
                      value={formData.untilDate}
                      onChange={(e) => handleInputChange("untilDate", e.target.value)}
                      disabled={loading}
                      error={formErrors.untilDate}
                      required
                    />
                  )}

                  {/* Info Note */}
                  <Alert
                    type="info"
                    message="Changes will take effect immediately and affect the facilitator's availability for new work orders."
                    showIcon
                  />

                  {/* Form Actions */}
                  <div className="flex items-center justify-between mt-6">
                    <div>
                      {hasChanges ? (
                        <Button
                          variant="secondary"
                          onClick={handleReset}
                          disabled={loading}
                          icon={ArrowPathIcon}
                        >
                          Reset Changes
                        </Button>
                      ) : (
                        <Button
                          variant="secondary"
                          onClick={handleCancel}
                          disabled={loading}
                        >
                          Cancel
                        </Button>
                      )}
                    </div>
                    <Button
                      type="submit"
                      variant="primary"
                      disabled={loading || !hasChanges}
                      loading={loading}
                      loadingText="Updating..."
                      icon={CheckCircleIcon}
                    >
                      Update Away Log
                    </Button>
                  </div>
                </div>
              </form>
            </div>
          </FormCard>
        </div>


        {/* Loading Overlay - Responsive */}
        {loading && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className={`${getThemeClasses('bg-primary')} rounded-lg p-4 sm:p-6 flex items-center space-x-3 sm:space-x-4 max-w-xs`}>
              <div className={`animate-spin rounded-full h-6 w-6 sm:h-8 sm:w-8 border-b-2 ${getThemeClasses('loading-spinner')}`}></div>
              <span className={`text-sm sm:text-base ${getThemeClasses('text-primary')}`}>
                Updating away log...
              </span>
            </div>
          </div>
        )}

        {/* Cancel Confirmation Modal */}
        <Modal
          isOpen={showCancelModal}
          onClose={() => setShowCancelModal(false)}
          title="Discard Changes?"
          size="sm"
        >
          <div className="space-y-4">
            <p className={getThemeClasses('text-primary')}>
              Are you sure you want to cancel? Any unsaved changes will be lost.
            </p>
            <div className="flex justify-end space-x-3">
              <Button
                variant="secondary"
                onClick={() => setShowCancelModal(false)}
              >
                Keep Editing
              </Button>
              <Button
                variant="danger"
                onClick={handleConfirmCancel}
              >
                Discard Changes
              </Button>
            </div>
          </div>
        </Modal>
      </div>
    </div>
  );
}

export default SettingFacilitatorAwayLogUpdatePage;
