// File: src/components/UIX/TagSelector/TagSelector.jsx
// Card-style tag selector with modal - theme-aware, matches IconPicker design

import React, { useState, useEffect, useMemo, useCallback } from "react";
import { useTags } from "../../../services/Services";
import { TagIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { useUIXTheme } from "../themes/useUIXTheme";
import Button from "../Button/Button";

// UUID validation regex for tag IDs
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

/**
 * TagSelector Component
 *
 * Card-style tag selector with modal picker.
 * Designed to match the IconPicker card layout.
 *
 * @param {Object} props
 * @param {Array} props.value - Array of selected tag IDs
 * @param {Function} props.onChange - Callback (tagIds) => void
 * @param {boolean} props.disabled - Whether the selector is disabled
 * @param {string} props.label - Label for the selector (default: "Tags")
 * @param {boolean} props.required - Whether tag selection is required
 * @param {string} props.error - Error message to display
 */
export default function TagSelector({
  value = [],
  onChange,
  disabled = false,
  label = "Tags",
  required = false,
  error = null
}) {
  const { getThemeClasses } = useUIXTheme();
  const { tagManager } = useTags();
  const [availableTags, setAvailableTags] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [pendingSelection, setPendingSelection] = useState([]);

  const loadTags = useCallback(async () => {
    try {
      setIsLoading(true);
      const tags = await tagManager.listTags();
      setAvailableTags(tags || []);
    } catch (err) {
      console.error("Failed to load tags:", err);
      setAvailableTags([]);
    } finally {
      setIsLoading(false);
    }
  }, [tagManager]);

  useEffect(() => {
    loadTags();
  }, [loadTags]);

  // Validate and filter incoming value prop
  const validatedValue = useMemo(() => {
    if (!Array.isArray(value)) return [];
    return value.filter(id => typeof id === 'string' && UUID_REGEX.test(id));
  }, [value]);

  const selectedTags = useMemo(() =>
    availableTags.filter(tag => validatedValue.includes(tag.id)),
    [availableTags, validatedValue]
  );

  // Truncated display of selected tag names (max 3 shown)
  const selectedTagsDisplay = useMemo(() => {
    if (selectedTags.length === 0) return "";
    if (selectedTags.length <= 3) {
      return selectedTags.map(t => t.name).join(", ");
    }
    return `${selectedTags.slice(0, 3).map(t => t.name).join(", ")} +${selectedTags.length - 3} more`;
  }, [selectedTags]);

  const handleOpenModal = useCallback(() => {
    setPendingSelection([...validatedValue]);
    setIsModalOpen(true);
  }, [validatedValue]);

  const handleCloseModal = useCallback(() => {
    setIsModalOpen(false);
    setPendingSelection([]);
  }, []);

  const handleToggleTag = useCallback((tagId) => {
    // Validate tag ID format before adding
    if (typeof tagId !== 'string' || !UUID_REGEX.test(tagId)) {
      console.warn('[TagSelector] Invalid tag ID format:', tagId);
      return;
    }
    setPendingSelection(prev => {
      if (prev.includes(tagId)) {
        return prev.filter(id => id !== tagId);
      } else {
        return [...prev, tagId];
      }
    });
  }, []);

  const handleConfirm = useCallback(() => {
    onChange(pendingSelection);
    setIsModalOpen(false);
    setPendingSelection([]);
  }, [pendingSelection, onChange]);

  const handleReset = useCallback(() => {
    onChange([]);
    setIsModalOpen(false);
    setPendingSelection([]);
  }, [onChange]);

  // Handle backdrop click
  const handleBackdropClick = useCallback((e) => {
    if (e.target === e.currentTarget) {
      handleCloseModal();
    }
  }, [handleCloseModal]);

  // Handle escape key
  const handleKeyDown = useCallback((e) => {
    if (e.key === "Escape") {
      handleCloseModal();
    }
  }, [handleCloseModal]);

  const selectedCount = validatedValue.length;

  // Compact mode: when label is empty, render a minimal card without the outer label
  const isCompactMode = !label;

  return (
    <div className="w-full h-full flex flex-col">
      {/* Label - only show when label is provided */}
      {label && (
        <label className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-3`}>
          <span className="flex items-center">
            <TagIcon className="h-4 w-4 mr-2" />
            {label}
            {required && <span className="text-red-500 ml-1">*</span>}
            {!required && (
              <span className={`ml-2 text-xs font-normal ${getThemeClasses("text-secondary")}`}>
                (Optional)
              </span>
            )}
          </span>
        </label>
      )}

      {/* Card container - compact mode has simpler layout */}
      {isCompactMode ? (
        // Compact mode: simple button with selected count
        <div className="flex flex-col space-y-3">
          {selectedCount > 0 && (
            <div className="flex flex-wrap gap-2">
              {selectedTags.slice(0, 3).map(tag => (
                <span
                  key={tag.id}
                  className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium`}
                  style={{ backgroundColor: `${tag.color}20`, color: tag.color }}
                >
                  <span
                    className="w-2 h-2 rounded-full mr-1.5"
                    style={{ backgroundColor: tag.color }}
                  />
                  {tag.name}
                </span>
              ))}
              {selectedCount > 3 && (
                <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${getThemeClasses("bg-muted")} ${getThemeClasses("text-secondary")}`}>
                  +{selectedCount - 3} more
                </span>
              )}
            </div>
          )}
          <div className="flex space-x-2">
            <Button
              type="button"
              onClick={handleOpenModal}
              disabled={disabled || isLoading}
              variant="secondary"
              size="sm"
            >
              {selectedCount > 0 ? `Change Tags (${selectedCount})` : "Choose Tags"}
            </Button>
            {selectedCount > 0 && (
              <Button
                type="button"
                onClick={() => onChange([])}
                disabled={disabled}
                variant="ghost"
                size="sm"
              >
                Clear
              </Button>
            )}
          </div>
        </div>
      ) : (
        // Full mode: card with icon preview - matches Icon selector
        <div className={`flex items-center p-4 rounded-lg border ${error ? 'border-red-500' : getThemeClasses("border-secondary")} ${getThemeClasses("bg-muted")} flex-1`}>
          {/* Tag preview */}
          <div className={`w-12 h-12 rounded-lg flex items-center justify-center mr-4 flex-shrink-0 ${getThemeClasses("bg-card")} border ${getThemeClasses("border-secondary")}`}>
            {selectedCount > 0 ? (
              <span className={`text-lg font-semibold ${getThemeClasses("text-accent")}`}>
                {selectedCount}
              </span>
            ) : (
              <TagIcon className={`h-6 w-6 ${getThemeClasses("text-muted")}`} />
            )}
          </div>

          <div className="flex-1">
            <p className={`text-sm ${getThemeClasses("text-primary")} font-medium mb-1`}>
              {selectedCount > 0
                ? `${selectedCount} tag${selectedCount !== 1 ? 's' : ''} selected`
                : "No tags selected"
              }
            </p>
            <p className={`text-xs ${getThemeClasses("text-secondary")} mb-3 truncate`}>
              {selectedCount > 0
                ? selectedTagsDisplay
                : "Add tags to organize your folder"
              }
            </p>
            <div className="flex space-x-2">
              <Button
                type="button"
                onClick={handleOpenModal}
                disabled={disabled || isLoading}
                variant="secondary"
                size="sm"
              >
                {selectedCount > 0 ? "Change Tags" : "Choose Tags"}
              </Button>
              {selectedCount > 0 && (
                <Button
                  type="button"
                  onClick={() => onChange([])}
                  disabled={disabled}
                  variant="ghost"
                  size="sm"
                >
                  Clear
                </Button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Error message */}
      {error && (
        <p className={`mt-1 text-sm ${getThemeClasses("text-error")}`}>{error}</p>
      )}

      {/* Modal */}
      {isModalOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50"
          onClick={handleBackdropClick}
          onKeyDown={handleKeyDown}
          role="dialog"
          aria-modal="true"
          aria-labelledby="tag-picker-title"
        >
          <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-xl w-full max-w-lg max-h-[85vh] flex flex-col`}>
            {/* Header */}
            <div className={`flex items-center justify-between p-4 border-b ${getThemeClasses("border-secondary")}`}>
              <h3 id="tag-picker-title" className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}>
                Choose Tags
              </h3>
              <Button
                onClick={handleCloseModal}
                variant="ghost"
                size="sm"
                aria-label="Close tag picker"
              >
                <XMarkIcon className="h-5 w-5" />
              </Button>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto p-4">
              {isLoading ? (
                <div className={`p-8 text-center ${getThemeClasses("text-secondary")}`}>
                  Loading tags...
                </div>
              ) : availableTags.length === 0 ? (
                <div className={`p-8 text-center ${getThemeClasses("text-secondary")}`}>
                  <TagIcon className={`h-12 w-12 mx-auto mb-3 ${getThemeClasses("text-muted")}`} />
                  <p>No tags available</p>
                  <p className="text-sm mt-1">Create tags in your profile settings</p>
                </div>
              ) : (
                <div className="flex flex-wrap gap-3">
                  {availableTags.map(tag => {
                    const isSelected = pendingSelection.includes(tag.id);
                    return (
                      <Button
                        key={tag.id}
                        type="button"
                        onClick={() => handleToggleTag(tag.id)}
                        variant="ghost"
                        className={`px-4 py-2 rounded-full border-2 transition-all ${
                          isSelected
                            ? `border-current ${getThemeClasses("bg-accent-light")}`
                            : `${getThemeClasses("border-secondary")} ${getThemeClasses("hover:bg-muted")}`
                        }`}
                        style={isSelected ? { borderColor: tag.color, color: tag.color } : {}}
                      >
                        <span
                          className="w-3 h-3 rounded-full mr-2 flex-shrink-0"
                          style={{ backgroundColor: tag.color }}
                        />
                        <span className={isSelected ? "" : getThemeClasses("text-primary")}>
                          {tag.name}
                        </span>
                      </Button>
                    );
                  })}
                </div>
              )}
            </div>

            {/* Footer */}
            <div className={`flex items-center justify-between p-4 border-t ${getThemeClasses("border-secondary")} ${getThemeClasses("bg-muted")} rounded-b-xl`}>
              <Button
                onClick={handleReset}
                variant="ghost"
                size="sm"
                icon={TagIcon}
              >
                Clear All
              </Button>
              <div className="flex space-x-2">
                <Button
                  onClick={handleCloseModal}
                  variant="secondary"
                  size="sm"
                >
                  Cancel
                </Button>
                <Button
                  onClick={handleConfirm}
                  variant="primary"
                  size="sm"
                >
                  Confirm ({pendingSelection.length})
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
