import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
  Card,
  CardHeader,
  CardBody,
  Button,
  Notice,
  Spinner,
} from '../../../components/ui';
import apiFetch from '@wordpress/api-fetch';

const CssCacheManager = ({ onBack, onClearCache, stats }) => {
  const [loading, setLoading] = useState(false);
  const [clearing, setClearing] = useState(false);
  const [previewData, setPreviewData] = useState(null);
  const [testResults, setTestResults] = useState(null);

  const formatBytes = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const clearCache = async (type) => {
    setClearing(true);
    try {
      await onClearCache(type);
    } finally {
      setClearing(false);
    }
  };

  const testOptimization = async () => {
    setLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/performance/css/test',
        method: 'POST',
        data: { url: window.location.origin },
      });
      setTestResults(response.data);
    } catch (error) {
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="css-cache-manager">
      <div className="pr:mb-5">
        <Button variant="link" onClick={onBack}>
          ← {__('Back to Settings', 'prorank-seo')}
        </Button>
      </div>

      <h3>{__('CSS Cache Management', 'prorank-seo')}</h3>

      {/* Cache Statistics */}
      {stats && (
        <Card className="pr:mb-5">
          <CardHeader>
            <h3>{__('Cache Statistics', 'prorank-seo')}</h3>
          </CardHeader>
          <CardBody>
            <div className="css-cache-stats">
              <div className="stat-item">
                <div className="stat-value">{stats.total_files || 0}</div>
                <div className="stat-label">{__('Cached Files', 'prorank-seo')}</div>
              </div>
              <div className="stat-item">
                <div className="stat-value">{stats.total_size_formatted || '0 KB'}</div>
                <div className="stat-label">{__('Total Size', 'prorank-seo')}</div>
              </div>
              <div className="stat-item">
                <div className="stat-value">{stats.cache_hits || 0}</div>
                <div className="stat-label">{__('Cache Hits', 'prorank-seo')}</div>
              </div>
              <div className="stat-item">
                <div className="stat-value">{stats.compression_ratio || 0}%</div>
                <div className="stat-label">{__('Avg. Compression', 'prorank-seo')}</div>
              </div>
            </div>
          </CardBody>
        </Card>
      )}

      {/* Cache Actions */}
      <Card className="pr:mb-5">
        <CardHeader>
          <h3>{__('Cache Actions', 'prorank-seo')}</h3>
        </CardHeader>
        <CardBody>
          <div className="pr:flex pr:gap-2.5 pr:flex-wrap">
            <Button variant="secondary" onClick={() => clearCache('all')} disabled={clearing}>
              {clearing ? __('Clearing…', 'prorank-seo') : __('Clear All Cache', 'prorank-seo')}
            </Button>

            <Button variant="secondary" onClick={() => clearCache('minified')} disabled={clearing}>
              {__('Clear Minified Files', 'prorank-seo')}
            </Button>

            <Button variant="secondary" onClick={() => clearCache('external')} disabled={clearing}>
              {__('Clear External CSS', 'prorank-seo')}
            </Button>
          </div>

          <Notice status="info" isDismissible={false} className="pr:mt-4">
            {__(
              'Clearing the cache will force CSS files to be re-optimized on next page load.',
              'prorank-seo'
            )}
          </Notice>
        </CardBody>
      </Card>

      {/* Test Optimization */}
      <Card>
        <CardHeader>
          <h3>{__('Test CSS Optimization', 'prorank-seo')}</h3>
        </CardHeader>
        <CardBody>
          <p>{__('Test how CSS optimization would affect your homepage.', 'prorank-seo')}</p>

          <Button
            variant="primary"
            onClick={testOptimization}
            disabled={loading}
            className="pr:mt-2.5"
          >
            {loading ? <Spinner /> : __('Run Test', 'prorank-seo')}
          </Button>

          {testResults && (
            <div className="pr:mt-5">
              <h3>{__('Test Results', 'prorank-seo')}</h3>
              <div className="test-results">
                <p>
                  <strong>{__('CSS Files Found:', 'prorank-seo')}</strong>{' '}
                  {testResults.css_files_count}
                </p>
                <p>
                  <strong>{__('Original Size:', 'prorank-seo')}</strong>{' '}
                  {testResults.total_original_size_formatted}
                </p>
                <p>
                  <strong>{__('Optimized Size:', 'prorank-seo')}</strong>{' '}
                  {testResults.total_optimized_size_formatted}
                </p>
                <p>
                  <strong>{__('Potential Savings:', 'prorank-seo')}</strong>{' '}
                  {testResults.potential_savings_formatted} ({testResults.potential_reduction}%)
                </p>
              </div>
            </div>
          )}
        </CardBody>
      </Card>
    </div>
  );
};

export default CssCacheManager;
