// monorepo/web/frontend/src/pages/Admin/SkillSet/FacilitatorSearchCriteriaPage.jsx

import React, { useState } from "react";
import { Link, useNavigate } from "react-router";
import {
  ChartBarIcon,
  MagnifyingGlassIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  WrenchScrewdriverIcon,
  UserGroupIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { SkillSetsMultiSelect } from "../../../components/business/selects";
import { Card, Alert, Button, Radio, UIXThemeProvider, useUIXTheme, Breadcrumb } from "../../../components/UIX";

function AdminSkillSetFacilitatorSearchCriteriaPage() {
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [selectedSkillSetIds, setSelectedSkillSetIds] = useState([]);
  const [searchType, setSearchType] = useState("");
  const [alert, setAlert] = useState(null);

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

  // Handle skill set change
  const handleSkillSetChange = (value) => {
    setSelectedSkillSetIds(value);
    // Clear skill set error when user selects something
    if (value && value.length > 0 && errors.skillSets) {
      setErrors((prev) => ({ ...prev, skillSets: undefined }));
    }
  };

  // Handle search type change
  const handleSearchTypeChange = (value) => {
    setSearchType(value);
    // Clear search type error when user selects something
    if (value && errors.searchType) {
      setErrors((prev) => ({ ...prev, searchType: undefined }));
    }
  };

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

    // Validation
    const newErrors = {};
    let hasErrors = false;

    if (!selectedSkillSetIds || selectedSkillSetIds.length === 0) {
      newErrors.skillSets = "Please select at least one skill set";
      hasErrors = true;
    }

    if (!searchType) {
      newErrors.searchType = "Please select a search type";
      hasErrors = true;
    }

    if (hasErrors) {
      setErrors(newErrors);
      setAlert({
        type: "error",
        message: "Please correct the errors below before searching.",
      });
      window.scrollTo(0, 0);
      return;
    }

    // Clear any previous errors
    setErrors({});
    setAlert(null);

    // Navigate to results page with search parameters
    const skillSetIdsStr = selectedSkillSetIds.join(",");
    navigate(
      `/admin/skill-sets/search-results?ssids=${skillSetIdsStr}&type=${searchType}`,
    );
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Breadcrumb */}
      <Breadcrumb
        items={[
          {
            label: 'Dashboard',
            to: '/admin/dashboard',
            icon: ChartBarIcon,
          },
          {
            label: 'Skill Sets',
            icon: WrenchScrewdriverIcon,
            isActive: true,
          },
        ]}
      />

      {/* Page Title */}
      <div className="mb-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className={`text-3xl font-bold ${getThemeClasses('text-primary')} flex items-center`}>
              <WrenchScrewdriverIcon className="w-8 h-8 mr-3 text-blue-600" />
              Skill Sets
            </h1>
          </div>
        </div>
      </div>

      {/* Alert Messages */}
      {alert && (
        <Alert
          type={alert.type}
          dismissible
          onDismiss={() => setAlert(null)}
          className="mb-6"
        >
          {alert.message}
        </Alert>
      )}

      {/* Main Content Card */}
      <Card className="shadow-lg">
        {/* Card Body */}
        <form onSubmit={handleSubmit} className="p-6">
          <div className="space-y-6">
            {/* Information Alert */}
            <Alert type="info">
              <div>
                <p className="font-medium text-base">How to use this search:</p>
                <ul className="mt-2 list-disc list-inside text-base">
                  <li>Select one or more skill sets from the dropdown</li>
                  <li>
                    Choose whether facilitators must have ALL selected skills
                    or ANY of them
                  </li>
                  <li>Click Search to find matching facilitators</li>
                </ul>
              </div>
            </Alert>

            {/* Skill Set Selection */}
            <div>
              <SkillSetsMultiSelect
                value={selectedSkillSetIds}
                onChange={handleSkillSetChange}
                error={errors.skillSets}
                required={true}
                placeholder="Choose skill sets to search for..."
                helperText=""
                onUnauthorized={onUnauthorized}
              />
            </div>

            {/* Search Type Selection */}
            <div className={`${getThemeClasses('bg-muted')} rounded-lg p-4`}>
              <label className={`block text-base font-medium ${getThemeClasses('text-secondary')} mb-4`}>
                Search Type <span className="text-red-500">*</span>
              </label>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <Radio
                  name="searchType"
                  value="all"
                  checked={searchType === "all"}
                  onChange={(e) => handleSearchTypeChange(e.target.value)}
                  label="Match ALL skill sets"
                  helperText="Facilitators must have every selected skill set"
                  size="lg"
                />

                <Radio
                  name="searchType"
                  value="in"
                  checked={searchType === "in"}
                  onChange={(e) => handleSearchTypeChange(e.target.value)}
                  label="Match ANY skill set"
                  helperText="Facilitators must have at least one of the selected skill sets"
                  size="lg"
                />
              </div>

              {errors.searchType && (
                <p className="mt-3 text-base text-red-600 flex items-center">
                  <ExclamationTriangleIcon className="w-5 h-5 mr-2" />
                  {errors.searchType}
                </p>
              )}
            </div>

            {/* Selected Skills Summary */}
            {selectedSkillSetIds.length > 0 && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <p className="text-base font-medium text-blue-900 mb-2">
                  Search Summary:
                </p>
                <p className="text-base text-blue-700">
                  Finding facilitators who have{" "}
                  <strong>{searchType === "all" ? "ALL" : "ANY"}</strong> of the{" "}
                  {selectedSkillSetIds.length} selected skill
                  {selectedSkillSetIds.length === 1 ? " set" : " sets"}
                </p>
              </div>
            )}
          </div>

          {/* Form Actions */}
          <div className="flex justify-between items-center mt-8">
            <Link to="/admin/dashboard">
              <Button type="button" variant="outline" icon={ChevronLeftIcon}>
                Back to Dashboard
              </Button>
            </Link>

            <div className="flex gap-3">
              <Button
                type="button"
                variant="secondary"
                onClick={() => {
                  setSelectedSkillSetIds([]);
                  setSearchType("");
                  setErrors({});
                  setAlert(null);
                }}
              >
                Clear
              </Button>

              <Button
                type="submit"
                variant="primary"
                icon={MagnifyingGlassIcon}
              >
                Search Facilitators
              </Button>
            </div>
          </div>
        </form>
      </Card>
    </div>
  );
}

function AdminSkillSetFacilitatorSearchCriteriaPageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminSkillSetFacilitatorSearchCriteriaPage />
    </UIXThemeProvider>
  );
}

export default AdminSkillSetFacilitatorSearchCriteriaPageWrapper;
