// File Path: monorepo/web/frontend/src/pages/Admin/Setting/SpeakerAwayLog/Create/Page.jsx

import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router";
import {
  useSpeakerAwayLogManager,
  useSpeakerManager,
} from "../../../../../services/Services";
import {
  Breadcrumb,
  PageHeader,
  FormCard,
  Alert,
  Button,
  Input,
  Select,
  UIXThemeProvider,
  useUIXTheme
} from "../../../../../components/UIX";
import {
  CalendarDaysIcon,
  PlusIcon,
  Cog6ToothIcon,
  InformationCircleIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  DocumentTextIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";
import { ensureISODateForAPI } from "../../../../../services/Helpers/DateFormatter";

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" },
];

function SettingSpeakerAwayLogCreatePage() {
  return (
    <UIXThemeProvider>
      <SettingSpeakerAwayLogCreatePageContent />
    </UIXThemeProvider>
  );
}

function SettingSpeakerAwayLogCreatePageContent() {
  const speakerAwayLogManager = useSpeakerAwayLogManager();
  const speakerManager = useSpeakerManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // State management
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [formErrors, setFormErrors] = useState({});

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

  // Speakers for selection
  const [speakerOptions, setSpeakerOptions] = useState([]);
  const [loadingOptions, setLoadingOptions] = useState(true);

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

  const handleSpeakerChange = (value) => {
    handleInputChange("speakerId", value);

    // Clear speaker error if it exists
    if (formErrors.speakerId) {
      setFormErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors.speakerId;
        return newErrors;
      });
    }
  };

  // Fetch speakers for selection
  const fetchSpeakers = async () => {
    try {
      setLoadingOptions(true);

      // Create filters for active speakers
      const filtersMap = new Map();
      filtersMap.set("status", 1); // Active status

      // Fetch speakers
      const speakerResponse = await speakerManager.getSpeakerSelectOptions(filtersMap, onUnauthorized);

      // Format the options with proper structure
      const options = (speakerResponse || [])
        .filter(item => item && item.label && item.value)
        .map(item => ({
          value: item.value,
          label: item.label,
        }))
        .sort((a, b) => (a.label || '').localeCompare(b.label || ''));

      setSpeakerOptions(options);
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error("Failed to fetch speakers:", err);
      setError("Failed to load speakers");
      }
    } finally {
      setLoadingOptions(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 = {};

    if (!formData.speakerId) {
      errors.speakerId = "Speaker is required";
    }

    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;
  };

  // Handle form submission
  const handleSubmit = async () => {

    // 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 = {
        speakerId: formData.speakerId,
        reason: parseInt(formData.reason),
        reasonOther: formData.reasonOther?.trim() || "",
        untilFurtherNotice: parseInt(formData.untilFurtherNotice),
        untilDate:
          formData.untilFurtherNotice === "2"
            ? formData.untilDate
              ? ensureISODateForAPI(formData.untilDate)
              : ""
            : "",
        startDate: formData.startDate
          ? ensureISODateForAPI(formData.startDate)
          : "",
      };

      if (import.meta.env.DEV) {
      console.log("Submitting speaker away log data:", submitData);

      await speakerAwayLogManager.createSpeakerAwayLog(
        submitData,
        onUnauthorized,
      );
      }

      setSuccess("Speaker away log created successfully!");

      // Navigate back to list after short delay
      setTimeout(() => {
        navigate("/admin/settings/speaker-away-logs");
      }, 1500);
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error("Failed to create speaker away log:", err);

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

  // Initial load
  useEffect(() => {
    fetchSpeakers();
  }, []);

  // Get today's date for min date validation
  const today = new Date().toISOString().split("T")[0];

  return (
    <div className={`min-h-screen bg-gradient-to-br from-gray-50 via-white ${getThemeClasses('bg-gradient-primary')}`}>
      <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: 'Speaker Away Logs',
            to: '/admin/settings/speaker-away-logs',
            icon: CalendarDaysIcon
          },
          {
            label: 'Create',
            icon: PlusIcon,
            isActive: true
          }
        ]} />

        <PageHeader
          icon={PlusIcon}
          title="Create Speaker Away Log"
          subtitle="Create a new away log to mark speaker unavailability"
          actions={[
            <Button
              key="back"
              variant="secondary"
              size="md"
              onClick={() => navigate("/admin/settings/speaker-away-logs")}
              icon={ArrowLeftIcon}
            >
              Back to List
            </Button>
          ]}
        />

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

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

        {loadingOptions ? (
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${getThemeClasses('loading-spinner')} mx-auto mb-4`}></div>
              <p className={`text-base ${getThemeClasses('text-secondary')}`}>
                Loading speakers...
              </p>
            </div>
          </div>
        ) : (
          <FormCard
            title="Away Log Details"
            icon={DocumentTextIcon}
            actions={
              <div className="flex items-center gap-4">
                <Button
                  variant="secondary"
                  size="md"
                  onClick={() => navigate("/admin/settings/speaker-away-logs")}
                  disabled={loading}
                >
                  Cancel
                </Button>
                <Button
                  variant="primary"
                  size="lg"
                  onClick={handleSubmit}
                  disabled={loading}
                  loading={loading}
                  loadingText="Creating..."
                  icon={CheckCircleIcon}
                >
                  Create Away Log
                </Button>
              </div>
            }
          >
            <div className="space-y-6">
                    {/* Speaker Selection */}
                    <Select
                      id="speakerId"
                      name="speakerId"
                      value={formData.speakerId}
                      onChange={handleSpeakerChange}
                      error={formErrors.speakerId}
                      required={true}
                      label="Speaker"
                      placeholder="Please select a speaker"
                      options={speakerOptions}
                      disabled={loading}
                    />

                    {/* 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
                        id="reasonOther"
                        name="reasonOther"
                        value={formData.reasonOther}
                        onChange={(value) => handleInputChange("reasonOther", value)}
                        error={formErrors.reasonOther}
                        required={true}
                        label="Specify Reason"
                        placeholder="Please specify the reason"
                        disabled={loading}
                      />
                    )}

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

                      {/* 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
                        id="untilDate"
                        name="untilDate"
                        type="date"
                        value={formData.untilDate}
                        onChange={(value) => handleInputChange("untilDate", value)}
                        error={formErrors.untilDate}
                        required={true}
                        label="Until Date"
                        min={today}
                        disabled={loading}
                      />
                    )}

              {/* Info Note */}
              <div className={`p-4 ${getThemeClasses('alert-info-bg')} border ${getThemeClasses('border-primary')} rounded-lg`}>
                <p className={`text-sm ${getThemeClasses('text-primary')} flex items-start`}>
                  <InformationCircleIcon className="w-5 h-5 mr-2 flex-shrink-0 mt-0.5" />
                  <span>
                    This log will mark the selected speaker as unavailable for
                    new work orders during the specified period.
                  </span>
                </p>
              </div>
            </div>
          </FormCard>
        )}

        {/* Loading Overlay */}
        {loading && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className={`${getThemeClasses('bg-primary')} 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 ${getThemeClasses('loading-spinner')}`}></div>
                <div>
                  <p className={`text-lg font-medium ${getThemeClasses('text-primary')}`}>
                    Creating Speaker Away Log...
                  </p>
                  <p className={`text-sm ${getThemeClasses('text-secondary')}`}>
                    Please wait while we save your changes.
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default SettingSpeakerAwayLogCreatePage;