/**
 * Schema Mapper - Step 3 of Schema Wizard
 * Visual content mapping without coding
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import {
  ArrowPathIcon,
  LightBulbIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon
} from '@heroicons/react/24/outline';
import { Button, Input, Select, Toggle, Alert, Card, Badge, Textarea } from '../../../../components/ui';
import LoadingState from '../../../../components/LoadingState';
import { getSchemaProperties } from '../utils/schemaTypes';

const SchemaMapper = ({ schemaType, mapping, onUpdateMapping }) => {
  const [availableFields, setAvailableFields] = useState([]);
  const [customFields, setCustomFields] = useState([]);
  const [loading, setLoading] = useState(true);
  const [autoMapEnabled, setAutoMapEnabled] = useState(true);
  const [showAdvanced, setShowAdvanced] = useState(false);

  // Get schema properties
  const schemaProperties = getSchemaProperties(schemaType);

  // Load available WordPress fields and custom fields
  useEffect(() => {
    loadAvailableFields();
  }, []);

  // Auto-map fields on initial load
  useEffect(() => {
    if (autoMapEnabled && Object.keys(mapping).length === 0) {
      autoMapFields();
    }
  }, [schemaProperties, availableFields]);

  const loadAvailableFields = async () => {
    try {
      // Get custom fields
      const customFieldsResponse = await apiFetch({
        path: '/prorank-seo/v1/schema/custom-fields'
      });
      setCustomFields(customFieldsResponse || []);
    } catch (error) {
      // Could not load custom fields, will continue without them
    } finally {
      setLoading(false);
    }

    // Set available WordPress fields
    setAvailableFields([
      { label: __('Post Title', 'prorank-seo'), value: 'post_title', type: 'text' },
      { label: __('Post Content', 'prorank-seo'), value: 'post_content', type: 'content' },
      { label: __('Post Excerpt', 'prorank-seo'), value: 'post_excerpt', type: 'text' },
      { label: __('Post Author', 'prorank-seo'), value: 'post_author', type: 'person' },
      { label: __('Post Date', 'prorank-seo'), value: 'post_date', type: 'date' },
      { label: __('Post Modified Date', 'prorank-seo'), value: 'post_modified', type: 'date' },
      { label: __('Featured Image', 'prorank-seo'), value: 'featured_image', type: 'image' },
      { label: __('Post URL', 'prorank-seo'), value: 'post_url', type: 'url' },
      { label: __('Post Categories', 'prorank-seo'), value: 'post_categories', type: 'array' },
      { label: __('Post Tags', 'prorank-seo'), value: 'post_tags', type: 'array' },
      { label: __('Comment Count', 'prorank-seo'), value: 'comment_count', type: 'number' },
      { label: __('Site Name', 'prorank-seo'), value: 'site_name', type: 'text' },
      { label: __('Site Logo', 'prorank-seo'), value: 'site_logo', type: 'image' },
      { label: __('Author Name', 'prorank-seo'), value: 'author_name', type: 'text' },
      { label: __('Author Bio', 'prorank-seo'), value: 'author_bio', type: 'text' },
      { label: __('Author Avatar', 'prorank-seo'), value: 'author_avatar', type: 'image' },
      { label: __('User Rating Average', 'prorank-seo'), value: 'user_rating_avg', type: 'number' },
      { label: __('User Rating Count', 'prorank-seo'), value: 'user_rating_count', type: 'number' },
      { label: __('Custom Field', 'prorank-seo'), value: 'custom', type: 'custom' },
      { label: __('Static Value', 'prorank-seo'), value: 'static', type: 'static' },
      { label: __('Dynamic Function', 'prorank-seo'), value: 'function', type: 'function' }
    ]);
  };

  const autoMapFields = () => {
    const autoMapped = {};

    Object.keys(schemaProperties).forEach(property => {
      const prop = schemaProperties[property];

      // Try to auto-map based on property name and type
      if (prop.autoMap) {
        autoMapped[property] = {
          source: prop.autoMap,
          type: 'field'
        };
      } else {
        // Smart mapping based on property name
        const mappingRules = {
          'headline': 'post_title',
          'name': 'post_title',
          'title': 'post_title',
          'description': 'post_excerpt',
          'articleBody': 'post_content',
          'content': 'post_content',
          'author': 'post_author',
          'datePublished': 'post_date',
          'dateModified': 'post_modified',
          'image': 'featured_image',
          'thumbnailUrl': 'featured_image',
          'url': 'post_url',
          'logo': 'site_logo',
          'publisher': 'site_name'
        };

        if (mappingRules[property]) {
          autoMapped[property] = {
            source: mappingRules[property],
            type: 'field'
          };
        }
      }
    });

    onUpdateMapping(autoMapped);
  };

  const updateFieldMapping = (property, source, additionalData = {}, propertyType = null) => {
    const newMapping = { ...mapping };

    if (source === 'none' || !source) {
      delete newMapping[property];
    } else {
      let mappingType = source === 'static' ? 'static' : source === 'custom' ? 'custom' : 'field';
      let customField = additionalData.customField || '';

      if (source.startsWith('custom_field:')) {
        mappingType = 'custom';
        customField = source.replace('custom_field:', '');
      }

      if (propertyType === 'list') {
        mappingType = 'list';
      }

      if (propertyType === 'json') {
        mappingType = 'json';
      }

      newMapping[property] = {
        source,
        type: mappingType,
        customField,
        ...additionalData
      };
    }

    onUpdateMapping(newMapping);
  };

  const updateRepeaterMapping = (property, field, subMapping, propertyData) => {
    const newMapping = { ...mapping };

    if (!field) {
      delete newMapping[property];
      onUpdateMapping(newMapping);
      return;
    }

    newMapping[property] = {
      type: 'repeater',
      field,
      itemType: propertyData?.itemType || '',
      nestedTypes: propertyData?.nestedTypes || {},
      subMapping: subMapping || {}
    };

    onUpdateMapping(newMapping);
  };

  const getRepeaterFields = () => {
    return customFields.filter(field => field.type === 'repeater' || Array.isArray(field.subFields));
  };

  const getRepeaterSubFields = (fieldKey) => {
    const repeater = getRepeaterFields().find(field => field.key === fieldKey);
    if (!repeater || !Array.isArray(repeater.subFields)) {
      return [];
    }
    return repeater.subFields.map(subField => ({
      label: subField.label,
      value: subField.key
    }));
  };

  const getFieldOptions = (propertyType) => {
    const options = [
      { label: __('-- Not Mapped --', 'prorank-seo'), value: 'none' }
    ];

    // Add WordPress fields
    availableFields.forEach(field => {
      // Filter fields by compatible type
      const compatible =
        (propertyType === 'text' && ['text', 'content'].includes(field.type)) ||
        (propertyType === 'textarea' && ['text', 'content'].includes(field.type)) ||
        (propertyType === 'content' && field.type === 'content') ||
        (propertyType === 'image' && field.type === 'image') ||
        (propertyType === 'date' && field.type === 'date') ||
        (propertyType === 'person' && field.type === 'person') ||
        (propertyType === 'url' && field.type === 'url') ||
        (propertyType === 'number' && field.type === 'number') ||
        (propertyType === 'list' && ['text', 'content', 'array'].includes(field.type)) ||
        field.value === 'custom' ||
        field.value === 'static' ||
        field.value === 'function';

      if (compatible) {
        options.push(field);
      }
    });

    // Add custom fields
    customFields.forEach(field => {
      options.push({
        label: `Custom: ${field.label}`,
        value: `custom_field:${field.key}`
      });
    });

    return options;
  };

  const renderPropertyMapper = (property, propertyData) => {
    const currentMapping = mapping[property] || {};
    const isRequired = propertyData.required;

    return (
      <Card
        key={property}
        className={isRequired ? 'pr:border-l-4 pr:border-l-error-500' : ''}
      >
        <div className="pr:space-y-4">
          {/* Property Header */}
          <div className="pr:flex pr:items-start pr:justify-between">
            <div className="pr:flex-1">
              <div className="pr:flex pr:items-center pr:gap-2 pr:mb-1">
                <h5 className="pr:text-sm pr:font-semibold pr:text-gray-900">
                  {propertyData.label}
                </h5>
                {isRequired && (
                  <Badge variant="error" size="sm">
                    {__('Required', 'prorank-seo')}
                  </Badge>
                )}
                {propertyData.autoDetect && (
                  <Badge variant="success" size="sm">
                    <LightBulbIcon className="pr:w-3 pr:h-3" />
                    {__('Auto', 'prorank-seo')}
                  </Badge>
                )}
              </div>
              {propertyData.help && (
                <p className="pr:text-xs pr:text-gray-600">
                  {propertyData.help}
                </p>
              )}
            </div>
          </div>

          {/* Mapping Controls */}
          <div className="pr:space-y-3">
            {propertyData.type !== 'repeater' && (
              <Select
                value={currentMapping.source || 'none'}
                onChange={(value) => updateFieldMapping(property, value, {}, propertyData.type)}
                options={getFieldOptions(propertyData.type)}
              />
            )}

            {propertyData.type === 'repeater' && (
              <div className="pr:space-y-4">
                <Select
                  label={__('Repeater Field', 'prorank-seo')}
                  value={currentMapping.field || 'none'}
                  onChange={(value) => updateRepeaterMapping(property, value === 'none' ? '' : value, currentMapping.subMapping || {}, propertyData)}
                  options={[
                    { label: __('-- Select Repeater Field --', 'prorank-seo'), value: 'none' },
                    ...getRepeaterFields().map(field => ({
                      label: field.label,
                      value: field.key
                    }))
                  ]}
                />

                {currentMapping.field && (
                  <div className="pr:space-y-3">
                    {propertyData.subFields?.map(subField => (
                      <Select
                        key={`${property}-${subField.path}`}
                        label={subField.label}
                        value={currentMapping.subMapping?.[subField.path] || 'none'}
                        onChange={(value) => {
                          const updatedSub = {
                            ...(currentMapping.subMapping || {}),
                            [subField.path]: value === 'none' ? '' : value
                          };
                          updateRepeaterMapping(property, currentMapping.field, updatedSub, propertyData);
                        }}
                        options={[
                          { label: __('-- Not Mapped --', 'prorank-seo'), value: 'none' },
                          ...getRepeaterSubFields(currentMapping.field)
                        ]}
                      />
                    ))}
                  </div>
                )}
              </div>
            )}

            {currentMapping.source === 'static' && currentMapping.type !== 'json' && (
              <Input
                placeholder={__('Enter static value...', 'prorank-seo')}
                value={currentMapping.value || ''}
                onChange={(value) => updateFieldMapping(property, 'static', { value }, propertyData.type)}
              />
            )}

            {currentMapping.type === 'json' && currentMapping.source === 'static' && (
              <Textarea
                label={__('JSON-LD', 'prorank-seo')}
                placeholder={__('Paste JSON here...', 'prorank-seo')}
                value={currentMapping.value || ''}
                onChange={(value) => updateFieldMapping(property, 'static', { value }, propertyData.type)}
                rows={6}
              />
            )}

            {currentMapping.source === 'custom' && (
              <Input
                placeholder={__('Enter custom field name...', 'prorank-seo')}
                value={currentMapping.customField || ''}
                onChange={(value) => updateFieldMapping(property, 'custom', { customField: value }, propertyData.type)}
              />
            )}

            {currentMapping.type === 'list' && (
              <Input
                label={__('List Separator (optional)', 'prorank-seo')}
                placeholder={__('Comma, pipe, or newline', 'prorank-seo')}
                value={currentMapping.listSeparator || ''}
                onChange={(value) => updateFieldMapping(
                  property,
                  currentMapping.source || 'static',
                  { listSeparator: value, customField: currentMapping.customField || '' },
                  propertyData.type
                )}
                helperText={__('Leave empty to auto-detect separators.', 'prorank-seo')}
              />
            )}

            {currentMapping.source === 'function' && (
              <Select
                value={currentMapping.function || ''}
                onChange={(value) => updateFieldMapping(property, 'function', { function: value }, propertyData.type)}
                options={[
                  { label: __('Select function...', 'prorank-seo'), value: '' },
                  { label: __('Current Date/Time', 'prorank-seo'), value: 'current_datetime' },
                  { label: __('Word Count', 'prorank-seo'), value: 'word_count' },
                  { label: __('Reading Time', 'prorank-seo'), value: 'reading_time' },
                  { label: __('Comment Count', 'prorank-seo'), value: 'comment_count' },
                  { label: __('Category List', 'prorank-seo'), value: 'category_list' },
                  { label: __('Tag List', 'prorank-seo'), value: 'tag_list' },
                  { label: __('Author Social Profiles', 'prorank-seo'), value: 'author_social' }
                ]}
              />
            )}
          </div>

          {/* Preview */}
          {currentMapping.source && currentMapping.source !== 'none' && (
            <div className="pr:flex pr:items-center pr:gap-2 pr:p-3 pr:bg-primary-50 pr:rounded-md pr:border pr:border-primary-200">
              <span className="pr:text-xs pr:font-medium pr:text-primary-900">
                {__('Preview:', 'prorank-seo')}
              </span>
              <code className="pr:text-xs pr:text-primary-700 pr:font-mono">
                {currentMapping.source === 'static'
                  ? currentMapping.value
                  : `{${currentMapping.source}}`}
              </code>
            </div>
          )}
        </div>
      </Card>
    );
  };

  if (loading) {
    return <LoadingState message={__('Loading mapping options...', 'prorank-seo')} />;
  }

  // Calculate stats
  const requiredFields = Object.keys(schemaProperties).filter(p => schemaProperties[p].required);
  const mappedRequired = requiredFields.filter(p => mapping[p]).length;
  const totalMapped = Object.keys(mapping).length;
  const staticValues = Object.keys(mapping).filter(k => mapping[k].source === 'static').length;

  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 3: Map Your Content', 'prorank-seo')}
        </h3>
        <p className="pr:text-sm pr:text-gray-600">
          {__('Map your content fields to schema properties. ProRank automatically detects and suggests the best mappings for you.', 'prorank-seo')}
        </p>
      </div>

      {/* Controls */}
      <Card variant="flat">
        <div className="pr:flex pr:flex-wrap pr:items-center pr:gap-4">
          <Toggle
            label={__('Auto-map fields', 'prorank-seo')}
            description={__('Automatically map fields based on smart detection', 'prorank-seo')}
            checked={autoMapEnabled}
            onChange={(enabled) => {
              setAutoMapEnabled(enabled);
              if (enabled) {
                autoMapFields();
              }
            }}
          />

          <Button
            variant="secondary"
            size="sm"
            icon={ArrowPathIcon}
            onClick={autoMapFields}
          >
            {__('Reset to Auto-mapping', 'prorank-seo')}
          </Button>

          <Button
            variant="ghost"
            size="sm"
            onClick={() => setShowAdvanced(!showAdvanced)}
          >
            {showAdvanced ? __('Hide Advanced Options', 'prorank-seo') : __('Show Advanced Options', 'prorank-seo')}
          </Button>
        </div>
      </Card>

      {/* Required Fields Section */}
      <div className="pr:space-y-4">
        <div>
          <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
            {__('Required Fields', 'prorank-seo')}
          </h4>
          <p className="pr:text-sm pr:text-gray-600">
            {__('These fields must be mapped for valid schema output.', 'prorank-seo')}
          </p>
        </div>
        <div className="pr:grid pr:grid-cols-1 pr:gap-4">
          {Object.keys(schemaProperties)
            .filter(prop => schemaProperties[prop].required)
            .map(property => renderPropertyMapper(property, schemaProperties[property]))}
        </div>
      </div>

      {/* Recommended Fields Section */}
      <div className="pr:space-y-4">
        <div>
          <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
            {__('Recommended Fields', 'prorank-seo')}
          </h4>
          <p className="pr:text-sm pr:text-gray-600">
            {__('Optional fields that improve your schema quality.', 'prorank-seo')}
          </p>
        </div>
        <div className="pr:grid pr:grid-cols-1 pr:gap-4">
          {Object.keys(schemaProperties)
            .filter(prop => !schemaProperties[prop].required)
            .slice(0, showAdvanced ? undefined : 5)
            .map(property => renderPropertyMapper(property, schemaProperties[property]))}
        </div>
      </div>

      {/* Advanced Options */}
      {showAdvanced && (
        <Card>
          <div className="pr:space-y-4">
            <div>
              <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                {__('Advanced Mappings', 'prorank-seo')}
              </h4>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Advanced mappings allow you to add custom schema properties and use dynamic functions.', 'prorank-seo')}
              </p>
            </div>

            <div className="pr:space-y-3">
              <Toggle
                label={__('Include organization data', 'prorank-seo')}
                checked={mapping.includeOrganization || false}
                onChange={(value) => updateFieldMapping('includeOrganization', value ? 'true' : '')}
              />

              <Toggle
                label={__('Include breadcrumbs', 'prorank-seo')}
                checked={mapping.includeBreadcrumbs || false}
                onChange={(value) => updateFieldMapping('includeBreadcrumbs', value ? 'true' : '')}
              />

              <Toggle
                label={__('Include author details', 'prorank-seo')}
                checked={mapping.includeAuthor || false}
                onChange={(value) => updateFieldMapping('includeAuthor', value ? 'true' : '')}
              />
            </div>
          </div>
        </Card>
      )}

      {/* Mapping Summary */}
      <Card variant="elevated" className="pr:bg-primary-50 pr:border-primary-200">
        <div className="pr:space-y-4">
          <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
            {__('Mapping Summary', 'prorank-seo')}
          </h4>

          {/* Stats Grid */}
          <div className="pr:grid pr:grid-cols-3 pr:gap-4">
            <div className="pr:text-center pr:p-4 pr:bg-white pr:rounded-lg pr:border pr:border-primary-200">
              <div className="pr:text-2xl pr:font-bold pr:text-primary-600">
                {totalMapped}
              </div>
              <div className="pr:text-xs pr:text-gray-600 pr:mt-1">
                {__('Fields Mapped', 'prorank-seo')}
              </div>
            </div>
            <div className="pr:text-center pr:p-4 pr:bg-white pr:rounded-lg pr:border pr:border-primary-200">
              <div className="pr:text-2xl pr:font-bold pr:text-primary-600">
                {mappedRequired}/{requiredFields.length}
              </div>
              <div className="pr:text-xs pr:text-gray-600 pr:mt-1">
                {__('Required Fields', 'prorank-seo')}
              </div>
            </div>
            <div className="pr:text-center pr:p-4 pr:bg-white pr:rounded-lg pr:border pr:border-primary-200">
              <div className="pr:text-2xl pr:font-bold pr:text-primary-600">
                {staticValues}
              </div>
              <div className="pr:text-xs pr:text-gray-600 pr:mt-1">
                {__('Static Values', 'prorank-seo')}
              </div>
            </div>
          </div>

          {/* Validation Warning */}
          {mappedRequired < requiredFields.length && (
            <Alert variant="warning" icon={ExclamationTriangleIcon}>
              {__('Some required fields are not mapped. Please map all required fields for valid schema output.', 'prorank-seo')}
            </Alert>
          )}

          {/* Success Message */}
          {mappedRequired === requiredFields.length && requiredFields.length > 0 && (
            <Alert variant="success" icon={CheckCircleIcon}>
              {__('All required fields are mapped! Your schema is ready.', 'prorank-seo')}
            </Alert>
          )}
        </div>
      </Card>
    </div>
  );
};

export default SchemaMapper;
