/**
 * Schema Type Selector - Step 1 of Schema Wizard
 * Visual selection of schema types with categories
 */

import { useState, useMemo, useCallback, useRef, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
  MagnifyingGlassIcon,
  Squares2X2Icon,
  CheckCircleIcon
} from '@heroicons/react/24/outline';
import { Input, Card, Badge } from '../../../../components/ui';
import { schemaCategories, schemaTypes } from '../utils/schemaTypes';

const SchemaTypeSelector = ({ selectedType, onSelectType, schemaName, onNameChange }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const debounceTimerRef = useRef(null);

  // Debounce effect - updates debouncedSearchTerm after 300ms delay
  useEffect(() => {
    // Clear any existing timer
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    // Set new timer
    debounceTimerRef.current = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
    }, 300);

    // Cleanup on unmount or when searchTerm changes
    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
    };
  }, [searchTerm]);

  // Handle search input change
  const handleSearchChange = (value) => {
    setSearchTerm(value); // Update input immediately, debounce handles the rest
  };

  // Memoized filtered schemas - only recalculate when dependencies change
  const filteredSchemas = useMemo(() => {
    let filtered = [];

    if (selectedCategory === 'all') {
      // Show all schemas
      Object.keys(schemaCategories).forEach(category => {
        schemaCategories[category].schemas.forEach(schemaKey => {
          if (schemaTypes[schemaKey]) {
            filtered.push({
              ...schemaTypes[schemaKey],
              type: schemaKey,
              category
            });
          }
        });
      });
    } else {
      // Show schemas from selected category
      const category = schemaCategories[selectedCategory];
      if (category) {
        category.schemas.forEach(schemaKey => {
          if (schemaTypes[schemaKey]) {
            filtered.push({
              ...schemaTypes[schemaKey],
              type: schemaKey,
              category: selectedCategory
            });
          }
        });
      }
    }

    // Apply search filter using debounced term
    if (debouncedSearchTerm) {
      const lowerSearch = debouncedSearchTerm.toLowerCase();
      filtered = filtered.filter(schema =>
        schema.label.toLowerCase().includes(lowerSearch) ||
        schema.description.toLowerCase().includes(lowerSearch)
      );
    }

    return filtered;
  }, [selectedCategory, debouncedSearchTerm]);

  return (
    <div className="pr:space-y-6">
      {/* Header */}
      <div>
        <h3 className="pr:text-xl pr:font-semibold pr:text-gray-900 pr:mb-2">
          {__('Step 1: Select a Schema Type', 'prorank-seo')}
        </h3>
        <p className="pr:text-sm pr:text-gray-600">
          {__('Choose the schema type that best describes your content. We offer 30+ schema types to help search engines understand your content better.', 'prorank-seo')}
        </p>
      </div>

      {/* Schema Name Field */}
      <Input
        label={__('Schema Configuration Name', 'prorank-seo')}
        value={schemaName}
        onChange={(value) => onNameChange(value)}
        placeholder={__('e.g., Blog Post Schema, Product Schema', 'prorank-seo')}
        helperText={__('Give your schema configuration a descriptive name for easy management.', 'prorank-seo')}
      />

      {/* Search Field */}
      <Input
        type="search"
        label={__('Search Schema Types', 'prorank-seo')}
        value={searchTerm}
        onChange={handleSearchChange}
        placeholder={__('Search for a schema type...', 'prorank-seo')}
        leftIcon={MagnifyingGlassIcon}
      />

      {/* Category Tabs */}
      <div className="pr:flex pr:flex-wrap pr:gap-2 pr:border-b pr:border-gray-200 pr:pb-4">
        <button
          className={`pr:inline-flex pr:items-center pr:gap-2 pr:px-4 pr:py-2 pr:text-sm pr:font-medium pr:rounded-md pr:transition-colors ${
            selectedCategory === 'all'
              ? 'pr:bg-primary-500 pr:text-white'
              : 'pr:bg-gray-100 pr:text-gray-700 pr:hover:bg-gray-200'
          }`}
          onClick={() => setSelectedCategory('all')}
        >
          <Squares2X2Icon className="pr:w-4 pr:h-4" />
          {__('All Types', 'prorank-seo')}
        </button>
        {Object.keys(schemaCategories).map(categoryKey => {
          const category = schemaCategories[categoryKey];
          return (
            <button
              key={categoryKey}
              className={`pr:inline-flex pr:items-center pr:gap-2 pr:px-4 pr:py-2 pr:text-sm pr:font-medium pr:rounded-md pr:transition-colors ${
                selectedCategory === categoryKey
                  ? 'pr:bg-primary-500 pr:text-white'
                  : 'pr:bg-gray-100 pr:text-gray-700 pr:hover:bg-gray-200'
              }`}
              onClick={() => setSelectedCategory(categoryKey)}
            >
              {category.label}
            </button>
          );
        })}
      </div>

      {/* Schema Grid */}
      <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:lg:grid-cols-3 pr:gap-4">
        {filteredSchemas.length > 0 ? (
          filteredSchemas.map(schema => (
            <Card
              key={schema.type}
              padding="default"
              className={`pr:cursor-pointer pr:transition-all pr:duration-200 ${
                selectedType === schema.type
                  ? 'pr:ring-2 pr:ring-primary-500 pr:border-primary-500'
                  : 'pr:hover:shadow-lg'
              }`}
              onClick={() => onSelectType(schema.type)}
            >
              <div className="pr:space-y-3">
                {/* Header with Icon and Badge */}
                <div className="pr:flex pr:items-start pr:justify-between">
                  <div className="pr:flex pr:items-center pr:justify-center pr:w-10 pr:h-10 pr:bg-primary-100 pr:rounded-lg">
                    <span className="pr:text-primary-600 pr:text-xl">
                      {(() => {
                        // Handle different icon formats safely
                        if (!schema.icon) return '📄';
                        // If it's a React component (function or forwardRef object), render it as element
                        if (typeof schema.icon === 'function') {
                          const IconComponent = schema.icon;
                          return <IconComponent className="pr:w-5 pr:h-5" />;
                        }
                        // If it's a forwardRef or memo component (object with $$typeof)
                        if (typeof schema.icon === 'object' && schema.icon.$$typeof) {
                          const IconComponent = schema.icon;
                          return <IconComponent className="pr:w-5 pr:h-5" />;
                        }
                        // If it's an HTML entity code like &#128196;
                        if (typeof schema.icon === 'string' && schema.icon.includes('&#')) {
                          const codePoint = parseInt(schema.icon.replace(/[^0-9]/g, ''), 10);
                          return codePoint ? String.fromCharCode(codePoint) : '📄';
                        }
                        // Otherwise return the string as-is (e.g., emoji)
                        return schema.icon;
                      })()}
                    </span>
                  </div>
                  {selectedType === schema.type && (
                    <CheckCircleIcon className="pr:w-6 pr:h-6 pr:text-success-500" />
                  )}
                </div>

                {/* Schema Info */}
                <div>
                  <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                    {schema.label}
                  </h4>
                  <p className="pr:text-sm pr:text-gray-600">
                    {schema.description}
                  </p>
                </div>

                {/* Category Badge */}
                <Badge variant="info" size="sm">
                  {schemaCategories[schema.category]?.label}
                </Badge>

                {/* Extends Info */}
                {schema.extends && (
                  <p className="pr:text-xs pr:text-gray-500 pr:italic">
                    {__('Extends:', 'prorank-seo')} {schema.extends}
                  </p>
                )}
              </div>
            </Card>
          ))
        ) : (
          <div className="pr:col-span-full pr:text-center pr:py-12">
            <MagnifyingGlassIcon className="pr:w-12 pr:h-12 pr:text-gray-300 pr:mx-auto pr:mb-4" />
            <p className="pr:text-sm pr:text-gray-500">
              {__('No schema types found matching your search.', 'prorank-seo')}
            </p>
          </div>
        )}
      </div>

      {/* Selected Schema Info */}
      {selectedType && (
        <Card variant="elevated" className="pr:bg-primary-50 pr:border-primary-200">
          <div className="pr:space-y-3">
            <h4 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Selected Schema:', 'prorank-seo')} {schemaTypes[selectedType]?.label}
            </h4>
            <p className="pr:text-sm pr:text-gray-700">
              {schemaTypes[selectedType]?.description}
            </p>
            <div>
              <strong className="pr:text-sm pr:font-medium pr:text-gray-900">
                {__('Available Properties:', 'prorank-seo')}
              </strong>
              <ul className="pr:mt-2 pr:space-y-1">
                {Object.keys(schemaTypes[selectedType]?.properties || {}).slice(0, 5).map(prop => (
                  <li key={prop} className="pr:text-sm pr:text-gray-700">
                    • {schemaTypes[selectedType].properties[prop].label}
                  </li>
                ))}
                {Object.keys(schemaTypes[selectedType]?.properties || {}).length > 5 && (
                  <li className="pr:text-sm pr:text-gray-500 pr:italic">
                    ...{__('and more', 'prorank-seo')}
                  </li>
                )}
              </ul>
            </div>
          </div>
        </Card>
      )}
    </div>
  );
};

export default SchemaTypeSelector;
