import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Button, Textarea, Alert } from '../../../components/ui';

const RobotsSettings = () => {
  const [content, setContent] = useState('');
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [notice, setNotice] = useState(null);

  // Load current robots.txt content from API
  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    setLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/robots_indexing',
      });

      // Set content from API or use default template
      const defaultContent = `# Robots.txt
User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php

Sitemap: ${window.location.origin}/sitemap_index.xml`;

      setContent(response.settings?.robots_txt_rules || defaultContent);
    } catch (error) {
      setNotice({ type: 'error', message: __('Failed to load robots.txt settings', 'prorank-seo') });
    } finally {
      setLoading(false);
    }
  };

  // 2025 Enhancement: Real API integration instead of mock save
  const handleSave = async () => {
    setSaving(true);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/robots_indexing',
        method: 'POST',
        data: {
          robots_txt_rules: content,
          enable_robots_editor: true,
        },
      });

      setNotice({ type: 'success', message: __('Robots.txt saved successfully!', 'prorank-seo') });
      setTimeout(() => setNotice(null), 3000);
    } catch (error) {
      setNotice({
        type: 'error',
        message: error.message || __('Failed to save robots.txt', 'prorank-seo')
      });
    } finally {
      setSaving(false);
    }
  };

  // Show loading state
  if (loading) {
    return (
      <div className="prorank-sidebar-content pr:text-center pr:p-5">
        <p>{__('Loading robots.txt settings…', 'prorank-seo')}</p>
      </div>
    );
  }

  return (
    <div className="prorank-sidebar-content">
      <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-2">
        {__('Robots.txt Editor', 'prorank-seo')}
      </h3>
      <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
        {__('Control how search engines crawl your site.', 'prorank-seo')}
      </p>

      {notice && (
        <Alert
          type={notice.type}
          className="pr:mb-4"
        >
          {notice.message}
        </Alert>
      )}

      <div className="pr:mt-5">
        <Textarea
          label={__('Robots.txt Content', 'prorank-seo')}
          value={content}
          onChange={(value) => setContent(value)}
          rows={10}
          className="pr:font-mono"
        />

        <div className="pr:mt-2.5 pr:mb-5 pr:transition-all pr:duration-300">
          <p className="pr:mb-1.5">
            <strong>{__('File Location:', 'prorank-seo')}</strong> {window.location.origin}
            /robots.txt
          </p>
          <a
            href={`${window.location.origin}/robots.txt`}
            target="_blank"
            rel="noopener noreferrer"
            className="pr:text-primary-600 pr:hover:text-primary-700 pr:underline pr:text-sm pr:transition-all pr:duration-300"
          >
            {__('View current robots.txt', 'prorank-seo')}
          </a>
        </div>

        <Button
          variant="primary"
          onClick={handleSave}
          loading={saving}
          disabled={saving}
        >
          {__('Save Robots.txt', 'prorank-seo')}
        </Button>
      </div>
    </div>
  );
};

export default RobotsSettings;
