/**
 * Image Optimization Settings
 *
 * Settings for image compression and format conversion
 *
 * @package ProRank\SEO
 * @since   1.0.0
 */

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

const ImageOptimizationSettings = () => {
  const { getSetting, updateSetting } = useSettings();
  const { addNotification } = useNotifications();
  const [stats, setStats] = useState(null);
  const [isLoadingStats, setIsLoadingStats] = useState(true);
  const presetQualities = {
    aggressive: { compression_type: 'aggressive', webp: 65, avif: 55, jxl: 65, png: 60 },
    lossy: { compression_type: 'lossy', webp: 75, avif: 65, jxl: 75, png: 70 },
    glossy: { compression_type: 'glossy', webp: 82, avif: 75, jxl: 82, png: 80 },
    lossless: { compression_type: 'lossless', webp: 100, avif: 100, jxl: 100, png: 100 },
  };

  // Fetch image optimization stats
  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await apiFetch({
          path: '/prorank-seo/v1/image-optimization/stats',
        });
        if (response.success) {
          setStats(response.data);
        }
      } catch (error) {
        // Stats not available
      } finally {
        setIsLoadingStats(false);
      }
    };
    fetchStats();
  }, []);

  const handleToggle = (setting, value) => {
    updateSetting(`image_optimization_${setting}`, value);
    addNotification(
      value
        ? __('Setting enabled', 'prorank-seo')
        : __('Setting disabled', 'prorank-seo'),
      'success'
    );
  };

  const handleSelect = (setting, value) => {
    updateSetting(`image_optimization_${setting}`, value);
    addNotification(__('Setting updated', 'prorank-seo'), 'success');
  };

  const applyPreset = (presetKey) => {
    const preset = presetQualities[presetKey];
    if (!preset) return;
    updateSetting('image_optimization_compression_type', preset.compression_type);
    updateSetting('image_optimization_webp_quality', preset.webp);
    updateSetting('image_optimization_avif_quality', preset.avif);
    updateSetting('image_optimization_jxl_quality', preset.jxl);
    updateSetting('image_optimization_png_quality', preset.png);
    addNotification(__('Preset applied', 'prorank-seo'), 'success');
  };

  const describePreset = (key) => {
    const preset = presetQualities[key];
    if (!preset) return '';
    return `WebP ${preset.webp}% · AVIF ${preset.avif}% · JXL ${preset.jxl}% · PNG ${preset.png}%`;
  };

  const compressionOptions = [
    {
      value: 'aggressive',
      label: __('Aggressive (Best Compression)', 'prorank-seo'),
      description: __('WebP 65%, AVIF 55%, JXL 65% - Smallest files, slight quality loss', 'prorank-seo'),
    },
    {
      value: 'lossy',
      label: __('Balanced (Recommended)', 'prorank-seo'),
      description: __('WebP 75%, AVIF 65%, JXL 75% - Great balance of size and quality', 'prorank-seo'),
    },
    {
      value: 'glossy',
      label: __('High Quality', 'prorank-seo'),
      description: __('WebP 82%, AVIF 75%, JXL 82% - Better quality, larger files', 'prorank-seo'),
    },
    {
      value: 'lossless',
      label: __('Lossless (No Compression)', 'prorank-seo'),
      description: __('100% quality for all formats (WebP/AVIF/JXL) - No loss, larger files', 'prorank-seo'),
    },
  ];

  const deliveryOptions = [
    { value: 'picture_hooks', label: __('Picture Element (Content Hooks)', 'prorank-seo') },
    { value: 'picture_global', label: __('Picture Element (Global Buffer)', 'prorank-seo') },
    { value: 'htaccess', label: __('.htaccess Rewrite Rules', 'prorank-seo') },
  ];

  return (
    <div className="pr:flex pr:flex-col pr:gap-4">
      {/* Stats Card */}
      <Card>
        <CardHeader>
          <h3>{__('Image Optimization Stats', 'prorank-seo')}</h3>
        </CardHeader>
        <CardBody>
          {isLoadingStats ? (
            <div className="pr:text-center pr:py-5">
              <Spinner />
            </div>
          ) : stats ? (
            <div className="prorank-image-stats">
              <div className="pr:flex pr:items-center pr:gap-6 pr:flex-wrap">
                <div className="pr:flex pr:flex-col pr:gap-2">
                  <p className="pr:text-[32px] pr:font-bold">
                    {stats.images_optimized || 0}
                  </p>
                  <p className="pr:opacity-70">{__('Images Optimized', 'prorank-seo')}</p>
                </div>
                <div className="pr:flex pr:flex-col pr:gap-2">
                  <p className="pr:text-[32px] pr:font-bold pr:text-green-600">
                    {stats.total_savings_mb ? `${stats.total_savings_mb}MB` : '0MB'}
                  </p>
                  <p className="pr:opacity-70">{__('Space Saved', 'prorank-seo')}</p>
                </div>
                <div className="pr:flex pr:flex-col pr:gap-2">
                  <p className="pr:text-[32px] pr:font-bold">
                    {stats.avg_compression || '0%'}
                  </p>
                  <p className="pr:opacity-70">{__('Avg. Compression', 'prorank-seo')}</p>
                </div>
              </div>
            </div>
          ) : (
            <p>{__('No optimization data available yet. Optimize some images to see stats.', 'prorank-seo')}</p>
          )}
        </CardBody>
      </Card>

      {/* Compression Settings */}
      <Card>
        <CardHeader>
          <h3>{__('Compression Quality', 'prorank-seo')}</h3>
        </CardHeader>
        <CardBody>
          <div className="pr:flex pr:flex-col pr:gap-4">
            <div>
              <label className="pr:block pr:text-sm pr:font-medium pr:mb-2">
                {__('Compression Level', 'prorank-seo')}
              </label>
              <select
                className="pr:w-full pr:p-2 pr:border pr:border-gray-300 pr:rounded-xs"
                value={getSetting('image_optimization_compression_type', 'lossy')}
                onChange={(e) => handleSelect('compression_type', e.target.value)}
              >
                {compressionOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {compressionOptions.find(
                  (o) => o.value === getSetting('image_optimization_compression_type', 'lossy')
                )?.description}
              </p>
              <div className="pr:flex pr:gap-2 pr:flex-wrap pr:mt-3">
                {compressionOptions.map((option) => (
                  <button
                    key={option.value}
                    type="button"
                    className="pr:text-sm pr:px-3 pr:py-1 pr:border pr:rounded-xs pr:bg-gray-50 pr:hover:bg-gray-100"
                    onClick={() => applyPreset(option.value)}
                  >
                    {option.label} <span className="pr:text-xs pr:text-gray-500 pr:ml-1">({describePreset(option.value)})</span>
                  </button>
                ))}
              </div>
            </div>

            <Notice status="info" isDismissible={false}>
              <p className="pr:font-medium">{__('Compression Level Guide:', 'prorank-seo')}</p>
              <ul className="pr:ml-5 pr:mt-2 pr:text-sm">
                <li><strong>{__('Aggressive:', 'prorank-seo')}</strong> {__('50-60% smaller files. Best for blogs, news sites.', 'prorank-seo')}</li>
                <li><strong>{__('Balanced:', 'prorank-seo')}</strong> {__('40-50% smaller files. Recommended for most sites.', 'prorank-seo')}</li>
                <li><strong>{__('High Quality:', 'prorank-seo')}</strong> {__('25-35% smaller files. For photography portfolios.', 'prorank-seo')}</li>
                <li><strong>{__('Lossless:', 'prorank-seo')}</strong> {__('10-20% smaller files. No quality loss.', 'prorank-seo')}</li>
              </ul>
            </Notice>
          </div>
        </CardBody>
      </Card>

      {/* Format Settings */}
      <Card>
        <CardHeader>
          <h3>{__('Image Formats', 'prorank-seo')}</h3>
        </CardHeader>
        <CardBody>
          <div className="pr:flex pr:flex-col pr:gap-4">
            <Toggle
              label={__('Generate WebP Images', 'prorank-seo')}
              help={__('Create WebP versions for 25-50% smaller files. All modern browsers supported.', 'prorank-seo')}
              checked={getSetting('image_optimization_webp_enabled', true)}
              onChange={(value) => handleToggle('webp_enabled', value)}
            />
            <RangeControl
              label={__('WebP Quality', 'prorank-seo')}
              help={__('Default 82 for glossy, 75 for balanced, 65 for aggressive.', 'prorank-seo')}
              min={40}
              max={100}
              value={getSetting('image_optimization_webp_quality', 85)}
              onChange={(value) => handleSelect('webp_quality', value)}
            />

            <Toggle
              label={__('Generate AVIF Images', 'prorank-seo')}
              help={__('Create AVIF versions for 50-70% smaller files. Chrome, Firefox, Safari 16+.', 'prorank-seo')}
              checked={getSetting('image_optimization_avif_enabled', false)}
              onChange={(value) => handleToggle('avif_enabled', value)}
            />
            <RangeControl
              label={__('AVIF Quality', 'prorank-seo')}
              help={__('Default 75 for glossy, 65 for balanced, 55 for aggressive.', 'prorank-seo')}
              min={30}
              max={100}
              value={getSetting('image_optimization_avif_quality', 80)}
              onChange={(value) => handleSelect('avif_quality', value)}
            />

            <Toggle
              label={__('Generate JPEG XL Images', 'prorank-seo')}
              help={__('Create JPEG XL versions for best-in-class compression (up to 60% smaller). Browser support is still limited and server support is required.', 'prorank-seo')}
              checked={getSetting('image_optimization_jxl_enabled', false)}
              onChange={(value) => handleToggle('jxl_enabled', value)}
            />
            <RangeControl
              label={__('JPEG XL Quality', 'prorank-seo')}
              help={__('Default 82 for glossy, 75 for balanced, 65 for aggressive.', 'prorank-seo')}
              min={40}
              max={100}
              value={getSetting('image_optimization_jxl_quality', 80)}
              onChange={(value) => handleSelect('jxl_quality', value)}
            />

            <Toggle
              label={__('Run PNG Advanced Pipeline', 'prorank-seo')}
              help={__('Use pngquant → oxipng → ECT for PNGs (smaller but slower). Disable if timeouts occur on large PNGs.', 'prorank-seo')}
              checked={getSetting('image_optimization_png_pipeline', false)}
              onChange={(value) => handleToggle('png_pipeline', value)}
            />
            <RangeControl
              label={__('PNG Quality (pngquant)', 'prorank-seo')}
              help={__('Applies to pngquant stage; oxipng/ECT are lossless.', 'prorank-seo')}
              min={50}
              max={100}
              value={getSetting('image_optimization_png_quality', 80)}
              onChange={(value) => handleSelect('png_quality', value)}
            />
            <div className="pr:flex pr:gap-2 pr:flex-wrap pr:mt-2">
              {['aggressive', 'lossy', 'glossy', 'lossless'].map((key) => (
                <button
                  key={key}
                  type="button"
                  className="pr:text-xs pr:px-3 pr:py-1 pr:border pr:rounded-xs pr:bg-gray-50 pr:hover:bg-gray-100"
                  onClick={() => updateSetting('image_optimization_png_quality', presetQualities[key].png)}
                >
                  {__('PNG', 'prorank-seo')} {presetQualities[key].png}%
                </button>
              ))}
            </div>

            <Toggle
              label={__('Convert PNG to JPEG', 'prorank-seo')}
              help={__('Convert PNG images without transparency to JPEG for smaller files.', 'prorank-seo')}
              checked={getSetting('image_optimization_png_to_jpeg', false)}
              onChange={(value) => handleToggle('png_to_jpeg', value)}
            />

            <Toggle
              label={__('Convert CMYK to RGB', 'prorank-seo')}
              help={__('Automatically convert CMYK images to RGB for web compatibility.', 'prorank-seo')}
              checked={getSetting('image_optimization_cmyk_to_rgb', true)}
              onChange={(value) => handleToggle('cmyk_to_rgb', value)}
            />
          </div>
        </CardBody>
      </Card>

      {/* Behavior Settings */}
      <Card>
        <CardHeader>
          <h3>{__('Optimization Behavior', 'prorank-seo')}</h3>
        </CardHeader>
        <CardBody>
          <div className="pr:flex pr:flex-col pr:gap-4">
            <Toggle
              label={__('Optimize on Upload', 'prorank-seo')}
              help={__('Automatically optimize images when uploaded to Media Library.', 'prorank-seo')}
              checked={getSetting('image_optimization_optimize_on_upload', true)}
              onChange={(value) => handleToggle('optimize_on_upload', value)}
            />

            <Toggle
              label={__('Backup Original Images', 'prorank-seo')}
              help={__('Keep backups of original images for restoration.', 'prorank-seo')}
              checked={getSetting('image_optimization_backup_originals', true)}
              onChange={(value) => handleToggle('backup_originals', value)}
            />

            <Toggle
              label={__('Remove EXIF/Metadata', 'prorank-seo')}
              help={__('Strip metadata from images to reduce size and protect privacy.', 'prorank-seo')}
              checked={getSetting('image_optimization_remove_exif', true)}
              onChange={(value) => handleToggle('remove_exif', value)}
            />

            <Toggle
              label={__('Background Processing', 'prorank-seo')}
              help={__('Process images in the background without blocking uploads.', 'prorank-seo')}
              checked={getSetting('image_optimization_background_mode', false)}
              onChange={(value) => handleToggle('background_mode', value)}
            />
          </div>
        </CardBody>
      </Card>

      {/* Advanced Features */}
      <Card>
        <CardHeader>
          <h3>{__('Advanced Features', 'prorank-seo')}</h3>
        </CardHeader>
        <CardBody>
          <div className="pr:flex pr:flex-col pr:gap-4">
            <Toggle
              label={__('Generate Retina (@2x) Images', 'prorank-seo')}
              help={__('Create high-resolution versions for retina displays.', 'prorank-seo')}
              checked={getSetting('image_optimization_generate_retina', false)}
              onChange={(value) => handleToggle('generate_retina', value)}
            />

            <Toggle
              label={__('Optimize PDF Files', 'prorank-seo')}
              help={__('Compress and optimize uploaded PDF documents.', 'prorank-seo')}
              checked={getSetting('image_optimization_optimize_pdf', false)}
              onChange={(value) => handleToggle('optimize_pdf', value)}
            />

            <Toggle
              label={__('AI Training Protection', 'prorank-seo')}
              help={__('Add metadata to prevent AI models from using your images for training.', 'prorank-seo')}
              checked={getSetting('image_optimization_no_ai_training', false)}
              onChange={(value) => handleToggle('no_ai_training', value)}
            />

            <Toggle
              label={__('Custom Media Folders', 'prorank-seo')}
              help={__('Organize media files into custom folder structures.', 'prorank-seo')}
              checked={getSetting('image_optimization_custom_media_folders', false)}
              onChange={(value) => handleToggle('custom_media_folders', value)}
            />
          </div>
        </CardBody>
      </Card>

      {/* Delivery Settings */}
      <Card>
        <CardHeader>
          <h3>{__('Image Delivery', 'prorank-seo')}</h3>
        </CardHeader>
        <CardBody>
          <div className="pr:flex pr:flex-col pr:gap-4">
            <div>
              <label className="pr:block pr:text-sm pr:font-medium pr:mb-2">
                {__('Delivery Method', 'prorank-seo')}
              </label>
              <select
                className="pr:w-full pr:p-2 pr:border pr:border-gray-300 pr:rounded-xs"
                value={getSetting('image_optimization_delivery_method', 'picture_hooks')}
                onChange={(e) => handleSelect('delivery_method', e.target.value)}
              >
                {deliveryOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {__('How optimized images are served to visitors.', 'prorank-seo')}
              </p>
            </div>

            <Toggle
              label={__('Enable CDN Integration', 'prorank-seo')}
              help={__('Serve images through a CDN for faster global delivery.', 'prorank-seo')}
              checked={getSetting('image_optimization_cdn_enabled', false)}
              onChange={(value) => handleToggle('cdn_enabled', value)}
            />
          </div>
        </CardBody>
      </Card>

      {/* How It Works */}
      <Card>
        <CardHeader>
          <h3>{__('How Image Optimization Works', 'prorank-seo')}</h3>
        </CardHeader>
        <CardBody>
          <div className="pr:flex pr:flex-col pr:gap-3">
            <p>
              {__('ProRank SEO creates optimized WebP and AVIF versions of your images:', 'prorank-seo')}
            </p>
            <ol className="pr:ml-5">
              <li>{__('Original JPEG/PNG images are preserved (with optional backup)', 'prorank-seo')}</li>
              <li>{__('Optimized WebP/AVIF versions are generated alongside originals', 'prorank-seo')}</li>
              <li>{__('Modern browsers automatically receive the smaller version', 'prorank-seo')}</li>
              <li>{__('Older browsers fall back to the original image', 'prorank-seo')}</li>
            </ol>
            <Notice status="info" isDismissible={false}>
              <p className="pr:text-sm">
                <strong>{__('JPEG XL:', 'prorank-seo')}</strong> {__('Requires Imagick with libjxl support or the cjxl CLI tool installed on server. Best compression available.', 'prorank-seo')}
              </p>
            </Notice>
          </div>
        </CardBody>
      </Card>
    </div>
  );
};

export default ImageOptimizationSettings;
