import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
  Card,
  CardHeader,
  CardBody,
  Toggle,
  Input,
  Textarea,
  Select,
  Button,
  Notice,
  Modal,
  Spinner,
} from '../../../components/ui';
import apiFetch from '@wordpress/api-fetch';
import { useLicense } from '../../../contexts/LicenseContext';
import { useNotification } from '../../../contexts/NotificationContext';
import CssCacheManager from './CssCacheManager';
import CssExclusionEditor from './CssExclusionEditor';

const CssOptimizationSettings = ({ onClose, embedded = false }) => {
  const [settings, setSettings] = useState({
    css_minify: false,
    css_combine: false,
    css_inline_imports: true,
    css_external_cache: true,
    css_font_display_swap: true,
    css_gzip: true,
    css_async: false,
    css_exclude: '',
    css_cache_lifetime: 30,
  });

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [cacheStats, setCacheStats] = useState(null);
  const [activeTab, setActiveTab] = useState('settings');

  const { isTierActive } = useLicense();
  const { showNotification } = useNotification();

  useEffect(() => {
    loadSettings();
    loadCacheStats();
  }, []);

  const loadSettings = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/modules/css_opt/settings',
      });
      setSettings(response.settings || {});
    } catch (error) {
      showNotification(__('Failed to load CSS optimization settings', 'prorank-seo'), 'error');
    } finally {
      setLoading(false);
    }
  };

  const loadCacheStats = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/performance/css-cache/stats',
      });
      setCacheStats(response.data);
    } catch (error) {
      // Silently fail - stats are optional
    }
  };

  const saveSettings = async () => {
    setSaving(true);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/modules/css_opt/settings',
        method: 'POST',
        data: { settings },
      });
      showNotification(
        __('CSS optimization settings saved successfully', 'prorank-seo'),
        'success'
      );
      if (onClose) {
        onClose();
      }
    } catch (error) {
      showNotification(error.message || __('Failed to save settings', 'prorank-seo'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const clearCache = async (type = 'all') => {
    try {
      await apiFetch({
        path: '/prorank-seo/v1/performance/css-cache/clear',
        method: 'POST',
        data: { type },
      });
      showNotification(__('CSS cache cleared successfully', 'prorank-seo'), 'success');
      // Reload cache stats
      loadCacheStats();
    } catch (error) {
      showNotification(error.message || __('Failed to clear cache', 'prorank-seo'), 'error');
    }
  };

  if (loading) {
    return (
      <div className="pr:p-5 pr:text-center pr:transition-all pr:duration-300">
        <Spinner />
        <p>{__('Loading CSS optimization settings…', 'prorank-seo')}</p>
      </div>
    );
  }

  const content = (
    <div className="css-optimization-settings">
      {activeTab === 'settings' && (
        <>
          {/* Basic Optimization */}
          <Card>
            <CardHeader>
              <h3>{__('Basic Optimization', 'prorank-seo')}</h3>
            </CardHeader>
            <CardBody>
              <div className="pr:space-y-4">
                <Toggle
                  label={__('Enable CSS Minification', 'prorank-seo')}
                  help={__(
                    'Remove unnecessary whitespace and comments from CSS files',
                    'prorank-seo'
                  )}
                  checked={settings.css_minify}
                  onChange={(value) => setSettings({ ...settings, css_minify: value })}
                />

                <Toggle
                  label={__('Combine CSS Files', 'prorank-seo')}
                  help={__(
                    'Merge multiple CSS files into one to reduce HTTP requests. Keep this off if another optimizer already combines CSS, and prefer split delivery on builder-heavy sites.',
                    'prorank-seo'
                  )}
                  checked={settings.css_combine}
                  onChange={(value) => setSettings({ ...settings, css_combine: value })}
                />

                <Toggle
                  label={__('Enable Gzip Compression', 'prorank-seo')}
                  help={__(
                    'Create compressed versions of CSS files for faster delivery',
                    'prorank-seo'
                  )}
                  checked={settings.css_gzip}
                  onChange={(value) => setSettings({ ...settings, css_gzip: value })}
                />
              </div>
            </CardBody>
          </Card>

          {/* Advanced Features */}
          <Card className="pr:mt-5">
            <CardHeader>
              <h3>{__('Advanced Features', 'prorank-seo')}</h3>
            </CardHeader>
            <CardBody>
              <div className="pr:space-y-4">
                <Toggle
                  label={__('Inline @import Statements', 'prorank-seo')}
                  help={__(
                    'Replace @import with actual CSS content to reduce requests',
                    'prorank-seo'
                  )}
                  checked={settings.css_inline_imports}
                  onChange={(value) => setSettings({ ...settings, css_inline_imports: value })}
                />

                <Toggle
                  label={__('Cache External CSS', 'prorank-seo')}
                  help={__(
                    'Download and serve external CSS files locally (e.g., Google Fonts)',
                    'prorank-seo'
                  )}
                  checked={settings.css_external_cache}
                  onChange={(value) => setSettings({ ...settings, css_external_cache: value })}
                />

                <Toggle
                  label={__('Optimize Font Display', 'prorank-seo')}
                  help={__(
                    'Add font-display: swap to @font-face rules for better performance',
                    'prorank-seo'
                  )}
                  checked={settings.css_font_display_swap}
                  onChange={(value) => setSettings({ ...settings, css_font_display_swap: value })}
                />

                <Toggle
                  label={__('Async CSS Loading (Beta)', 'prorank-seo')}
                  help={__('Builder-sensitive beta. Do not combine with another CSS optimizer, and retest Elementor/template pages before production use.', 'prorank-seo')}
                  checked={settings.css_async}
                  onChange={(value) => setSettings({ ...settings, css_async: value })}
                />
              </div>
            </CardBody>
          </Card>

          {/* Cache Settings */}
          <Card className="pr:mt-5">
            <CardHeader>
              <h3>{__('Cache Settings', 'prorank-seo')}</h3>
            </CardHeader>
            <CardBody>
              <div className="pr:space-y-4">
                <Input
                  type="number"
                  label={__('Cache Lifetime (days)', 'prorank-seo')}
                  help={__('How long to keep optimized CSS files in cache', 'prorank-seo')}
                  value={settings.css_cache_lifetime}
                  onChange={(e) =>
                    setSettings({ ...settings, css_cache_lifetime: parseInt(e.target.value) || 30 })
                  }
                  min={1}
                  max={365}
                />

                {cacheStats && (
                  <div className="pr:mt-5 pr:transition-all pr:duration-300">
                    <p className="pr:text-sm">
                      {__('Cache Status:', 'prorank-seo')} {cacheStats.total_files}{' '}
                      {__('files', 'prorank-seo')} ({cacheStats.total_size_formatted})
                    </p>
                    <Button
                      variant="secondary"
                      onClick={() => clearCache('all')}
                      className="pr:mt-2.5"
                    >
                      {__('Clear CSS Cache', 'prorank-seo')}
                    </Button>
                  </div>
                )}
              </div>
            </CardBody>
          </Card>

          {/* Exclusions */}
          <Card className="pr:mt-5">
            <CardHeader>
              <h3>{__('Exclusions', 'prorank-seo')}</h3>
            </CardHeader>
            <CardBody>
              <Textarea
                label={__('Exclude CSS Files', 'prorank-seo')}
                help={__('Enter CSS file URLs or handles to exclude (one per line)', 'prorank-seo')}
                value={settings.css_exclude}
                onChange={(e) => setSettings({ ...settings, css_exclude: e.target.value })}
                rows={5}
              />
              <Button
                variant="secondary"
                onClick={() => setActiveTab('exclusions')}
                className="pr:transition-all pr:duration-300"
              >
                {__('Advanced Exclusion Editor', 'prorank-seo')}
              </Button>
            </CardBody>
          </Card>
        </>
      )}

      {activeTab === 'cache' && (
        <CssCacheManager
          onBack={() => setActiveTab('settings')}
          onClearCache={clearCache}
          stats={cacheStats}
        />
      )}

      {activeTab === 'exclusions' && (
        <CssExclusionEditor
          exclusions={settings.css_exclude}
          onChange={(value) => setSettings({ ...settings, css_exclude: value })}
          onBack={() => setActiveTab('settings')}
        />
      )}

      {/* Action Buttons */}
      {activeTab === 'settings' && (
        <div className="pr:mt-5 pr:flex pr:gap-2.5">
          <Button variant="primary" onClick={saveSettings} disabled={saving}>
            {saving ? __('Saving…', 'prorank-seo') : __('Save Settings', 'prorank-seo')}
          </Button>

          <Button variant="secondary" onClick={() => setActiveTab('cache')}>
            {__('Manage Cache', 'prorank-seo')}
          </Button>

          {onClose && (
            <Button variant="tertiary" onClick={onClose}>
              {__('Cancel', 'prorank-seo')}
            </Button>
          )}
        </div>
      )}
    </div>
  );

  if (embedded) {
    return content;
  }

  return (
    <Modal
      title={__('CSS Optimization Settings', 'prorank-seo')}
      onRequestClose={onClose}
      className="css-optimization-modal pr:transition-all pr:duration-300"
    >
      {content}
    </Modal>
  );
};

export default CssOptimizationSettings;
