/**
 * Quick Fix Panel Component
 *
 * Shows one-click fixes for common issues
 */

import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Card, Button, Alert, Spinner } from '../../../components/ui';
import { CheckIcon, ExclamationTriangleIcon, InformationCircleIcon } from '@heroicons/react/24/outline';
import apiFetch from '@wordpress/api-fetch';

const QuickFixPanel = ({ fixes }) => {
  const [fixingItems, setFixingItems] = useState({});
  const [fixedItems, setFixedItems] = useState({});
  const [errors, setErrors] = useState({});

  const applyFix = async (fix) => {
    setFixingItems({ ...fixingItems, [fix.id]: true });
    setErrors({ ...errors, [fix.id]: null });

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/audit/quick-fix',
        method: 'POST',
        data: {
          fix_id: fix.id,
          fix_type: fix.type,
          params: fix.params,
        },
      });

      if (response.success) {
        setFixedItems({ ...fixedItems, [fix.id]: true });
      } else {
        setErrors({ ...errors, [fix.id]: response.message });
      }
    } catch (error) {
      setErrors({ ...errors, [fix.id]: error.message });
    } finally {
      setFixingItems({ ...fixingItems, [fix.id]: false });
    }
  };

  const getSeverityIcon = (severity) => {
    switch (severity) {
      case 'critical':
        return { Icon: ExclamationTriangleIcon, className: 'pr:text-error-500' };
      case 'warning':
        return { Icon: ExclamationTriangleIcon, className: 'pr:text-warning-500' };
      default:
        return { Icon: InformationCircleIcon, className: 'pr:text-info-500' };
    }
  };

  return (
    <Card className="prorank-quick-fix-panel">
      <div className="pr:p-6">
        <div className="pr:mb-6">
          <h3 className="pr:text-lg pr:font-semibold">{__('Quick Fixes Available', 'prorank-seo')}</h3>
          <p className="pr:text-gray-600 pr:mt-1">{__('One-click solutions for common issues', 'prorank-seo')}</p>
        </div>

        <div className="quick-fix-list pr:space-y-4">
          {fixes.map((fix) => {
            const isFixing = fixingItems[fix.id];
            const isFixed = fixedItems[fix.id];
            const error = errors[fix.id];
            const { Icon: IconComponent, className: iconClassName } = getSeverityIcon(fix.severity);

            return (
              <div key={fix.id} className={`quick-fix-item pr:p-4 pr:border pr:rounded-md ${isFixed ? 'pr:bg-success-50' : 'pr:bg-white'}`}>
                <div className="fix-info pr:flex pr:items-start pr:gap-4 pr:mb-4">
                  <IconComponent className={`pr:w-6 pr:h-6 ${iconClassName}`} />
                  <div className="pr:flex-1">
                    <h4 className="pr:font-semibold">{fix.title}</h4>
                    <p className="pr:text-gray-600 pr:mt-1">{fix.description}</p>
                    {fix.impact && (
                      <span className="fix-impact pr:text-sm pr:text-gray-500 pr:mt-2 pr:block">
                        {__('Impact:', 'prorank-seo')} {fix.impact}
                      </span>
                    )}
                  </div>
                </div>

                <div className="fix-action">
                  {error && (
                    <Alert variant="error" className="pr:mb-3">
                      {error}
                    </Alert>
                  )}

                  {isFixed ? (
                    <div className="fix-success pr:flex pr:items-center pr:gap-2 pr:text-success-600">
                      <CheckIcon className="pr:w-5 pr:h-5" />
                      <span className="pr:font-medium">{__('Fixed!', 'prorank-seo')}</span>
                    </div>
                  ) : (
                    <Button
                      variant="secondary"
                      onClick={() => applyFix(fix)}
                      disabled={isFixing}
                      loading={isFixing}
                    >
                      {__('Apply Fix', 'prorank-seo')}
                    </Button>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        <Alert variant="info" className="pr:mt-6">
          <div className="pr:flex pr:items-start pr:gap-2">
            <InformationCircleIcon className="pr:w-5 pr:h-5 pr:shrink-0" />
            <p className="pr:text-sm">
              {__(
                'Quick fixes are safe, automated solutions. Always backup your site before applying fixes.',
                'prorank-seo'
              )}
            </p>
          </div>
        </Alert>
      </div>
    </Card>
  );
};

export default QuickFixPanel;
