import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Button, Alert, Toggle, Select } from '../../../components/ui';
import {
  CheckIcon,
  PencilSquareIcon,
  ArrowTrendingUpIcon,
  RectangleGroupIcon,
} from '@heroicons/react/24/outline';
import { useNotification } from '../../../contexts/NotificationContext';

const ContentAnalysisSettings = () => {
  const [settings, setSettings] = useState({
    enable_realtime: true,
    min_content_length: 300,
    target_readability_score: 60,
    auto_analyze_delay: 2000,
    show_keyword_density: false,
    show_entity_detection: false,
    show_intent_classification: false,
  });
  const [isSaving, setIsSaving] = useState(false);
  const [hasSaved, setHasSaved] = useState(false);
  const { showNotification } = useNotification();

  // Load settings on mount
  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/content-analysis',
      });
      if (response.data) {
        setSettings(prev => ({ ...prev, ...response.data }));
      }
    } catch (error) {
      // Use defaults if settings not found
    }
  };

  const saveSettings = async () => {
    setIsSaving(true);
    setHasSaved(false);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/content-analysis',
        method: 'POST',
        data: settings,
      });
      setHasSaved(true);
      showNotification(__('Settings saved successfully', 'prorank-seo'), 'success');
      setTimeout(() => setHasSaved(false), 3000);
    } catch (error) {
      showNotification(__('Failed to save settings', 'prorank-seo'), 'error');
    }
    setIsSaving(false);
  };

  const updateSetting = (key, value) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  const features = [
    {
      icon: PencilSquareIcon,
      title: __('Readability Scoring', 'prorank-seo'),
      description: __('Real-time Flesch-Kincaid readability analysis with grade level assessment', 'prorank-seo')
    },
    {
      icon: ArrowTrendingUpIcon,
      title: __('SEO Optimization Tips', 'prorank-seo'),
      description: __('Actionable suggestions to improve content structure and keyword usage', 'prorank-seo')
    },
    {
      icon: RectangleGroupIcon,
      title: __('Content Structure Analysis', 'prorank-seo'),
      description: __('Evaluates heading hierarchy, paragraph length, and content organization', 'prorank-seo')
    },
  ];

  const steps = [
    __('Open any post or page in the WordPress editor', 'prorank-seo'),
    __('Look for the "Content Analysis & SEO" panel in the ProRank SEO sidebar', 'prorank-seo'),
    __('Review readability and SEO score insights in the panel', 'prorank-seo'),
    __('Follow the optimization suggestions to improve your content', 'prorank-seo')
  ];

  return (
    <div className="pr:space-y-6 pr:max-w-4xl">
      {/* Header */}
      <div className="pr:mb-6">
        <h2 className="pr:text-2xl pr:font-semibold pr:text-gray-900 pr:mb-2">
          {__('Content Analysis', 'prorank-seo')}
        </h2>
        <p className="pr:text-sm pr:text-gray-600">
          {__('Enhance your content with readability scoring and SEO optimization directly in the editor.', 'prorank-seo')}
        </p>
      </div>

      {/* Info Notice */}
      <Alert variant="info">
        {__('This feature runs directly inside the WordPress editor. The settings below customize the analysis panel.', 'prorank-seo')}
      </Alert>

      {/* Features Card */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Features', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-6">
            {features.map((feature, index) => {
              const IconComponent = feature.icon;
              return (
                <div key={index} className="pr:flex pr:gap-3">
                  <div className="pr:shrink-0 pr:w-8 pr:h-8 pr:rounded-lg pr:bg-primary-50 pr:flex pr:items-center pr:justify-center">
                    <IconComponent className="pr:w-5 pr:h-5 pr:text-primary-600" />
                  </div>
                  <div className="pr:flex-1">
                    <h4 className="pr:text-sm pr:font-semibold pr:text-gray-900 pr:mb-1">
                      {feature.title}
                    </h4>
                    <p className="pr:text-xs pr:text-gray-600 pr:leading-relaxed">
                      {feature.description}
                    </p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </Card>

      {/* How to Use Card */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('How to Use', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <ol className="pr:space-y-3">
            {steps.map((step, index) => (
              <li key={index} className="pr:flex pr:gap-3">
                <span className="pr:shrink-0 pr:w-6 pr:h-6 pr:rounded-full pr:bg-primary-500 pr:text-white pr:flex pr:items-center pr:justify-center pr:text-xs pr:font-semibold">
                  {index + 1}
                </span>
                <span className="pr:text-sm pr:text-gray-700 pr:leading-relaxed pr:pt-0.5">
                  {step}
                </span>
              </li>
            ))}
          </ol>
        </div>
      </Card>

      {/* Configuration Card */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Configuration', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6 pr:space-y-6">
          {/* Analysis Settings Section */}
          <div className="pr:space-y-4">
            <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
              {__('Analysis Settings', 'prorank-seo')}
            </h4>

            <Toggle
              label={__('Enable Real-time Analysis', 'prorank-seo')}
              description={__('Automatically analyze content as you type in the editor', 'prorank-seo')}
              checked={settings.enable_realtime}
              onChange={(value) => updateSetting('enable_realtime', value)}
            />

            <Select
              label={__('Auto-analyze Delay', 'prorank-seo')}
              helperText={__('Time to wait after user stops typing before analyzing', 'prorank-seo')}
              value={settings.auto_analyze_delay.toString()}
              onChange={(value) => updateSetting('auto_analyze_delay', parseInt(value))}
              options={[
                { value: '1000', label: __('1 second', 'prorank-seo') },
                { value: '2000', label: __('2 seconds (recommended)', 'prorank-seo') },
                { value: '3000', label: __('3 seconds', 'prorank-seo') },
                { value: '5000', label: __('5 seconds', 'prorank-seo') },
              ]}
            />
          </div>

          <hr className="pr:border-gray-200" />

          {/* Content Thresholds Section */}
          <div className="pr:space-y-4">
            <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
              {__('Content Thresholds', 'prorank-seo')}
            </h4>

            <div className="pr:space-y-2">
              <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                {__('Target Readability Score', 'prorank-seo')}
              </label>
              <input
                type="range"
                min="30"
                max="90"
                step="5"
                value={settings.target_readability_score}
                onChange={(e) => updateSetting('target_readability_score', parseInt(e.target.value))}
                className="pr:w-full pr:h-2 pr:bg-gray-200 pr:rounded-lg pr:appearance-none pr:cursor-pointer"
              />
              <div className="pr:flex pr:justify-between pr:text-xs pr:text-gray-500">
                <span>{__('30 (Difficult)', 'prorank-seo')}</span>
                <span className="pr:font-medium pr:text-primary-600">{settings.target_readability_score}</span>
                <span>{__('90 (Very Easy)', 'prorank-seo')}</span>
              </div>
              <p className="pr:text-xs pr:text-gray-500">
                {__('Minimum Flesch reading ease score for good readability', 'prorank-seo')}
              </p>
            </div>

            <div className="pr:space-y-2">
              <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                {__('Minimum Content Length', 'prorank-seo')}
              </label>
              <input
                type="range"
                min="100"
                max="1000"
                step="50"
                value={settings.min_content_length}
                onChange={(e) => updateSetting('min_content_length', parseInt(e.target.value))}
                className="pr:w-full pr:h-2 pr:bg-gray-200 pr:rounded-lg pr:appearance-none pr:cursor-pointer"
              />
              <div className="pr:flex pr:justify-between pr:text-xs pr:text-gray-500">
                <span>{__('100 words', 'prorank-seo')}</span>
                <span className="pr:font-medium pr:text-primary-600">{settings.min_content_length}</span>
                <span>{__('1000 words', 'prorank-seo')}</span>
              </div>
              <p className="pr:text-xs pr:text-gray-500">
                {__('Minimum word count before showing analysis', 'prorank-seo')}
              </p>
            </div>
          </div>

          {/* Save Button */}
          <div className="pr:flex pr:items-center pr:gap-3 pr:pt-4">
            <Button
              variant="primary"
              onClick={saveSettings}
              loading={isSaving}
              disabled={isSaving}
            >
              {isSaving ? __('Saving...', 'prorank-seo') : __('Save Settings', 'prorank-seo')}
            </Button>
            {hasSaved && (
              <span className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-success-600">
                <CheckIcon className="pr:w-5 pr:h-5" />
                {__('Settings saved successfully', 'prorank-seo')}
              </span>
            )}
          </div>
        </div>
      </Card>

      {/* Help Section */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-2">
            {__('Need Help?', 'prorank-seo')}
          </h3>
          <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
            {__('Learn more about using content analysis features in the editor', 'prorank-seo')}
          </p>
          <Button
            variant="secondary"
            onClick={() => window.open('https://prorank.io/docs/ai-tools/', '_blank')}
          >
            {__('View Documentation', 'prorank-seo')}
          </Button>
        </div>
      </Card>
    </div>
  );
};

export default ContentAnalysisSettings;
