/**
 * Schema Tab Content Component
 *
 * @package
 */

import { __ } from '@wordpress/i18n';
import {
  SelectControl,
  TextControl,
  TextareaControl,
  Spinner,
  Notice,
  Button,
  PanelBody,
} from '@wordpress/components';
import { useState, useEffect, useCallback, useMemo } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import apiFetch from '@wordpress/api-fetch';

// Access lodash from WordPress global
const { debounce } = window.lodash || { debounce: (fn) => fn };

/**
 * Schema Preview Component
 * @param {Object}  root0
 * @param {number}  root0.postId
 * @param {Object}  root0.schemaData
 */
const SchemaPreview = ({ postId, schemaData }) => {
  const [preview, setPreview] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchPreview = useCallback(async () => {
    if (!postId) return;

    setIsLoading(true);
    setError(null);

    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/meta/${postId}/schema-preview`,
        method: 'POST',
        data: {
          schema_data: schemaData,
        },
      });

      if (response.success && response.data?.preview) {
        setPreview(response.data.preview);
        // Preview expanded
      } else {
        throw new Error(response.message || __('Failed to generate preview.', 'prorank-seo'));
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  }, [postId, schemaData]);

  return (
    <div className="prorank-schema-preview">
      <div className="prorank-schema-preview-actions">
        <Button variant="secondary" onClick={fetchPreview} disabled={isLoading}>
          {isLoading ? (
            <>
              <Spinner />
              {__('Loading…', 'prorank-seo')}
            </>
          ) : (
            __('Refresh Preview', 'prorank-seo')
          )}
        </Button>
      </div>

      {error && (
        <Notice status="error" isDismissible={true} onRemove={() => setError(null)}>
          {error}
        </Notice>
      )}

      {preview && !error && (
        <div className="prorank-schema-preview-content">
          <div className="prorank-code-preview">
            <pre>
              <code>{preview}</code>
            </pre>
          </div>
          <p className="description">
            {__('This preview shows the JSON-LD that will be output on your page.', 'prorank-seo')}
          </p>
        </div>
      )}
    </div>
  );
};

/**
 * Schema Validation Button Component
 * @param {Object}  root0
 * @param {boolean} root0.isAvailable
 */
const SchemaValidationButton = ({ isAvailable }) => {
  // Get post visibility and permalink
  const { postVisibility, permalink } = useSelect((select) => {
    const editorStore = select('core/editor');
    if (!editorStore) {
      // Classic editor — core/editor store not available
      return { postVisibility: 'public', permalink: window.location.href };
    }
    const { getEditedPostVisibility, getPermalink } = editorStore;
    return {
      postVisibility: getEditedPostVisibility ? getEditedPostVisibility() : 'public',
      permalink: getPermalink ? getPermalink() : '',
    };
  }, []);

  // Check if button should be enabled
  const isPublic = postVisibility === 'public';
  const isEnabled = isAvailable && isPublic && permalink;

  const handleValidate = () => {
    if (!isEnabled || !permalink) return;

    const testUrl = `https://search.google.com/test/rich-results?url=${encodeURIComponent(permalink)}`;
    window.open(testUrl, '_blank', 'noopener,noreferrer');
  };

  return (
    <div className="prorank-schema-validation">
      <Button
        variant="secondary"
        onClick={handleValidate}
        disabled={!isEnabled}
        href={isEnabled ? undefined : '#'}
        target={isEnabled ? '_blank' : undefined}
        rel={isEnabled ? 'noopener noreferrer' : undefined}
      >
        {__('Validate Schema', 'prorank-seo')}
      </Button>
      {!isAvailable && (
        <p className="description">
          {__('Schema validation is currently unavailable in this editor context.', 'prorank-seo')}
        </p>
      )}
      {isAvailable && !isPublic && (
        <p className="description">
          {__('Schema validation is only available for published posts.', 'prorank-seo')}
        </p>
      )}
      {isAvailable && isPublic && (
        <p className="description">
          {__("Test your structured data with Google's Rich Results Test.", 'prorank-seo')}
        </p>
      )}
    </div>
  );
};

// Schema types from Reference Appendix B §15
const SCHEMA_TYPES = [
  { label: __('Article', 'prorank-seo'), value: 'Article' },
  { label: __('Blog Post', 'prorank-seo'), value: 'BlogPosting' },
  { label: __('News Article', 'prorank-seo'), value: 'NewsArticle' },
  { label: __('Web Page', 'prorank-seo'), value: 'WebPage' },
  { label: __('About Page', 'prorank-seo'), value: 'AboutPage' },
  { label: __('Contact Page', 'prorank-seo'), value: 'ContactPage' },
  { label: __('Product', 'prorank-seo'), value: 'Product' },
  { label: __('Service', 'prorank-seo'), value: 'Service' },
  { label: __('Recipe', 'prorank-seo'), value: 'Recipe' },
  { label: __('Event', 'prorank-seo'), value: 'Event' },
  { label: __('Course', 'prorank-seo'), value: 'Course' },
  { label: __('FAQ Page', 'prorank-seo'), value: 'FAQPage' },
  { label: __('How-To', 'prorank-seo'), value: 'HowTo' },
  { label: __('Video Object', 'prorank-seo'), value: 'VideoObject' },
  { label: __('Local Business', 'prorank-seo'), value: 'LocalBusiness' },
  { label: __('Restaurant', 'prorank-seo'), value: 'Restaurant' },
  { label: __('Person', 'prorank-seo'), value: 'Person' },
  { label: __('Organization', 'prorank-seo'), value: 'Organization' },
  { label: __('Review', 'prorank-seo'), value: 'Review' },
  { label: __('Custom', 'prorank-seo'), value: 'Custom' },
];

const SchemaTabContent = ({ postId }) => {
  // State for schema data
  const [schemaData, setSchemaData] = useState({
    type: 'Article',
    properties: {},
    custom_json: '',
  });

  // State for UI
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);
  const [jsonError, setJsonError] = useState(null);

  // Load existing schema data
  useEffect(() => {
    if (!postId) {
      setIsLoading(false);
      return;
    }

    const loadSchemaData = async () => {
      setIsLoading(true);
      setError(null);

      try {
        const response = await apiFetch({
          path: `/prorank-seo/v1/meta/${postId}`,
          method: 'GET',
        });

        if (response.success && response.data.schema_data) {
          setSchemaData(response.data.schema_data);
        } else {
          // Set defaults based on post type
          const postType = document.querySelector('[name="post_type"]')?.value || 'post';
          setSchemaData((prev) => ({
            ...prev,
            type: postType === 'page' ? 'WebPage' : 'Article',
          }));
        }
      } catch (err) {
        setError(__('Failed to load schema data.', 'prorank-seo'));
      } finally {
        setIsLoading(false);
      }
    };

    loadSchemaData();
  }, [postId]);

  // Save function
  const saveSchemaDataImpl = useCallback(
    async (data) => {
      if (!postId) return;

      setIsSaving(true);
      setError(null);

      try {
        const response = await apiFetch({
          path: `/prorank-seo/v1/meta/${postId}`,
          method: 'POST',
          data: {
            schema_data: data,
          },
        });

        if (!response.success) {
          throw new Error(response.message || __('Failed to save schema data.', 'prorank-seo'));
        }
      } catch (err) {
        setError(err.message);
      } finally {
        setIsSaving(false);
      }
    },
    [postId]
  );

  // Debounced save
  const saveSchemaData = useMemo(() => debounce(saveSchemaDataImpl, 500), [saveSchemaDataImpl]);

  // Handle schema type change
  const handleSchemaTypeChange = (value) => {
    const newData = {
      ...schemaData,
      type: value,
      properties: {}, // Reset properties when type changes
    };
    setSchemaData(newData);
    saveSchemaData(newData);
  };

  // Handle property change
  const handlePropertyChange = (key, value) => {
    const newData = {
      ...schemaData,
      properties: {
        ...schemaData.properties,
        [key]: value,
      },
    };
    setSchemaData(newData);
    saveSchemaData(newData);
  };

  // Handle custom JSON change
  const handleCustomJsonChange = (value) => {
    // Validate JSON
    if (value) {
      try {
        JSON.parse(value);
        setJsonError(null);
      } catch (e) {
        setJsonError(__('Invalid JSON format', 'prorank-seo'));
      }
    } else {
      setJsonError(null);
    }

    const newData = {
      ...schemaData,
      custom_json: value,
    };
    setSchemaData(newData);
    saveSchemaData(newData);
  };

  // Render dynamic fields based on schema type
  const renderSchemaFields = () => {
    const { type, properties } = schemaData;

    switch (type) {
      case 'Article':
      case 'BlogPosting':
      case 'NewsArticle':
        return (
          <>
            <TextControl
              label={__('Headline', 'prorank-seo')}
              value={properties.headline || ''}
              onChange={(value) => handlePropertyChange('headline', value)}
              help={__(
                'The headline of the article. Defaults to post title if empty.',
                'prorank-seo'
              )}
            />
            <SelectControl
              label={__('Article Section', 'prorank-seo')}
              value={properties.articleSection || ''}
              onChange={(value) => handlePropertyChange('articleSection', value)}
              options={[
                { label: __('None', 'prorank-seo'), value: '' },
                { label: __('Technology', 'prorank-seo'), value: 'Technology' },
                { label: __('Business', 'prorank-seo'), value: 'Business' },
                { label: __('Health', 'prorank-seo'), value: 'Health' },
                { label: __('Lifestyle', 'prorank-seo'), value: 'Lifestyle' },
                { label: __('Entertainment', 'prorank-seo'), value: 'Entertainment' },
                { label: __('Sports', 'prorank-seo'), value: 'Sports' },
              ]}
            />
            <TextControl
              label={__('Word Count', 'prorank-seo')}
              type="number"
              value={properties.wordCount || ''}
              onChange={(value) => handlePropertyChange('wordCount', parseInt(value))}
            />
          </>
        );

      case 'Product':
        return (
          <>
            <TextControl
              label={__('Product Name', 'prorank-seo')}
              value={properties.name || ''}
              onChange={(value) => handlePropertyChange('name', value)}
            />
            <TextControl
              label={__('Brand', 'prorank-seo')}
              value={properties.brand || ''}
              onChange={(value) => handlePropertyChange('brand', value)}
            />
            <TextControl
              label={__('SKU', 'prorank-seo')}
              value={properties.sku || ''}
              onChange={(value) => handlePropertyChange('sku', value)}
            />
            <TextControl
              label={__('Price', 'prorank-seo')}
              type="number"
              value={properties.price || ''}
              onChange={(value) => handlePropertyChange('price', value)}
              help={__('Product price in your store currency', 'prorank-seo')}
            />
            <SelectControl
              label={__('Availability', 'prorank-seo')}
              value={properties.availability || 'InStock'}
              onChange={(value) => handlePropertyChange('availability', value)}
              options={[
                { label: __('In Stock', 'prorank-seo'), value: 'InStock' },
                { label: __('Out of Stock', 'prorank-seo'), value: 'OutOfStock' },
                { label: __('Pre Order', 'prorank-seo'), value: 'PreOrder' },
                { label: __('Discontinued', 'prorank-seo'), value: 'Discontinued' },
              ]}
            />
          </>
        );

      case 'Event':
        return (
          <>
            <TextControl
              label={__('Event Name', 'prorank-seo')}
              value={properties.name || ''}
              onChange={(value) => handlePropertyChange('name', value)}
            />
            <TextControl
              label={__('Start Date', 'prorank-seo')}
              type="datetime-local"
              value={properties.startDate || ''}
              onChange={(value) => handlePropertyChange('startDate', value)}
            />
            <TextControl
              label={__('End Date', 'prorank-seo')}
              type="datetime-local"
              value={properties.endDate || ''}
              onChange={(value) => handlePropertyChange('endDate', value)}
            />
            <TextControl
              label={__('Location Name', 'prorank-seo')}
              value={properties.locationName || ''}
              onChange={(value) => handlePropertyChange('locationName', value)}
            />
            <TextareaControl
              label={__('Location Address', 'prorank-seo')}
              value={properties.locationAddress || ''}
              onChange={(value) => handlePropertyChange('locationAddress', value)}
            />
          </>
        );

      case 'Recipe':
        return (
          <>
            <TextControl
              label={__('Recipe Name', 'prorank-seo')}
              value={properties.name || ''}
              onChange={(value) => handlePropertyChange('name', value)}
            />
            <TextControl
              label={__('Prep Time (minutes)', 'prorank-seo')}
              type="number"
              value={properties.prepTime || ''}
              onChange={(value) => handlePropertyChange('prepTime', parseInt(value))}
            />
            <TextControl
              label={__('Cook Time (minutes)', 'prorank-seo')}
              type="number"
              value={properties.cookTime || ''}
              onChange={(value) => handlePropertyChange('cookTime', parseInt(value))}
            />
            <TextControl
              label={__('Total Time (minutes)', 'prorank-seo')}
              type="number"
              value={properties.totalTime || ''}
              onChange={(value) => handlePropertyChange('totalTime', parseInt(value))}
            />
            <TextControl
              label={__('Recipe Yield', 'prorank-seo')}
              value={properties.recipeYield || ''}
              onChange={(value) => handlePropertyChange('recipeYield', value)}
              help={__('e.g., "4 servings" or "1 loaf"', 'prorank-seo')}
            />
          </>
        );

      case 'Person':
        return (
          <>
            <TextControl
              label={__('Full Name', 'prorank-seo')}
              value={properties.name || ''}
              onChange={(value) => handlePropertyChange('name', value)}
            />
            <TextControl
              label={__('Job Title', 'prorank-seo')}
              value={properties.jobTitle || ''}
              onChange={(value) => handlePropertyChange('jobTitle', value)}
            />
            <TextControl
              label={__('Works For', 'prorank-seo')}
              value={properties.worksFor || ''}
              onChange={(value) => handlePropertyChange('worksFor', value)}
            />
          </>
        );

      case 'Organization':
        return (
          <>
            <TextControl
              label={__('Organization Name', 'prorank-seo')}
              value={properties.name || ''}
              onChange={(value) => handlePropertyChange('name', value)}
            />
            <TextControl
              label={__('Logo URL', 'prorank-seo')}
              type="url"
              value={properties.logo || ''}
              onChange={(value) => handlePropertyChange('logo', value)}
            />
            <TextControl
              label={__('URL', 'prorank-seo')}
              type="url"
              value={properties.url || ''}
              onChange={(value) => handlePropertyChange('url', value)}
            />
          </>
        );

      case 'FAQPage':
        return (
          <PanelBody title={__('FAQ Schema', 'prorank-seo')} initialOpen={true}>
            <p className="description">
              {__(
                'FAQ schema is automatically generated from FAQ blocks in your content.',
                'prorank-seo'
              )}
            </p>
          </PanelBody>
        );

      default:
        return null;
    }
  };

  if (isLoading) {
    return (
      <div className="prorank-schema-tab-content">
        <div className="prorank-loading">
          <Spinner />
          <span>{__('Loading schema settings…', 'prorank-seo')}</span>
        </div>
      </div>
    );
  }

  return (
    <div className="prorank-schema-tab-content">
      {error && (
        <Notice status="error" isDismissible={true} onRemove={() => setError(null)}>
          {error}
        </Notice>
      )}

      {/* Schema Type Selector */}
      <div className="prorank-schema-section">
        <SelectControl
          label={__('Schema Type', 'prorank-seo')}
          value={schemaData.type}
          onChange={handleSchemaTypeChange}
          options={SCHEMA_TYPES}
        />
      </div>

      {/* Schema Properties - inline, no accordion */}
      {schemaData.type !== 'Custom' && (
        <div className="prorank-schema-section prorank-schema-properties">
          {renderSchemaFields()}
        </div>
      )}

      {/* Custom JSON-LD */}
      {schemaData.type === 'Custom' && (
        <div className="prorank-schema-section">
          <TextareaControl
            label={__('Custom JSON-LD', 'prorank-seo')}
            value={schemaData.custom_json}
            onChange={handleCustomJsonChange}
            placeholder={`{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "Your Title"
}`}
            rows={8}
          />
          {jsonError && (
            <Notice status="error" isDismissible={false}>
              {jsonError}
            </Notice>
          )}
        </div>
      )}

      {/* Actions Row */}
      <div className="prorank-schema-actions">
        <SchemaValidationButton postId={postId} isAvailable={true} />
      </div>

      <PanelBody title={__('Preview JSON-LD', 'prorank-seo')} initialOpen={false}>
        <SchemaPreview postId={postId} schemaData={schemaData} />
      </PanelBody>

      {/* Save Status */}
      {isSaving && (
        <div className="prorank-save-status prorank-save-status--saving">
          <Spinner />
          <span>{__('Saving…', 'prorank-seo')}</span>
        </div>
      )}
    </div>
  );
};

export default SchemaTabContent;
