import { useState, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Button, Alert, Badge } from '../../components/ui';
import {
  CheckCircleIcon,
  XCircleIcon,
  ExclamationTriangleIcon,
  InformationCircleIcon,
  LightBulbIcon,
} from '@heroicons/react/24/outline';
import { useNotification } from '../../contexts/NotificationContext';
import LoadingState from '../../components/LoadingState';

const HealthTab = () => {
  const [healthData, setHealthData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [scanning, setScanning] = useState(false);
  const { showNotification } = useNotification();

  useEffect(() => {
    loadHealthData();
  }, []);

  const loadHealthData = async () => {
    setLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/health/status',
      });
      setHealthData(response.data || response);
    } catch (error) {
      setHealthData(null);
    } finally {
      setLoading(false);
    }
  };

  const runHealthScan = async () => {
    setScanning(true);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/health/scan',
        method: 'POST',
      });

      await loadHealthData();
      showNotification(__('SEO health scan completed', 'prorank-seo'), 'success');
    } catch (error) {
      showNotification(__('Failed to run health scan', 'prorank-seo'), 'error');
    } finally {
      setScanning(false);
    }
  };

  const getScoreColor = (score) => {
    if (score >= 80) return 'pr:text-success-600';
    if (score >= 60) return 'pr:text-warning-600';
    return 'pr:text-error-600';
  };

  const getCheckIcon = (status) => {
    switch (status) {
      case 'pass':
        return CheckCircleIcon;
      case 'fail':
        return XCircleIcon;
      case 'warning':
        return ExclamationTriangleIcon;
      default:
        return InformationCircleIcon;
    }
  };

  const getCheckColor = (status) => {
    switch (status) {
      case 'pass':
        return 'pr:text-success-600';
      case 'fail':
        return 'pr:text-error-600';
      case 'warning':
        return 'pr:text-warning-600';
      default:
        return 'pr:text-info-600';
    }
  };

  const getBadgeVariant = (status) => {
    switch (status) {
      case 'pass':
        return 'success';
      case 'fail':
        return 'danger';
      case 'warning':
        return 'warning';
      default:
        return 'secondary';
    }
  };

  if (loading && !healthData) {
    return <LoadingState message={__('Loading SEO health data…', 'prorank-seo')} />;
  }

  const score = healthData?.score || 0;
  const scoreColor = getScoreColor(score);

  return (
    <div className="pr:space-y-6">
      {/* Health Score Card */}
      <Card variant="elevated" padding="lg">
        <div className="pr:flex pr:flex-col pr:md:flex-row pr:items-center pr:gap-8">
          {/* Score Circle */}
          <div className="pr:relative pr:w-48 pr:h-48">
            <svg viewBox="0 0 200 200" className="pr:w-full pr:h-full">
              <circle
                cx="100"
                cy="100"
                r="90"
                fill="none"
                stroke="currentColor"
                strokeWidth="20"
                opacity="0.1"
                className="pr:text-gray-300"
              />
              <circle
                cx="100"
                cy="100"
                r="90"
                fill="none"
                stroke="currentColor"
                strokeWidth="20"
                strokeDasharray={`${(score / 100) * 565.48} 565.48`}
                strokeLinecap="round"
                transform="rotate(-90 100 100)"
                className={scoreColor}
              />
            </svg>
            <div className="pr:absolute pr:inset-0 pr:flex pr:flex-col pr:items-center pr:justify-center">
              <span className={`pr:text-5xl pr:font-bold ${scoreColor}`}>{score}</span>
              <span className="pr:text-sm pr:text-gray-600 pr:uppercase pr:tracking-wide">
                {__('Score', 'prorank-seo')}
              </span>
            </div>
          </div>

          {/* Summary */}
          <div className="pr:flex-1">
            <h3 className="pr:text-2xl pr:font-semibold pr:text-gray-900 pr:mb-2">
              {__('SEO Health Score', 'prorank-seo')}
            </h3>
            <p className="pr:text-gray-600 pr:mb-6">
              {__("Your site's overall SEO health status", 'prorank-seo')}
            </p>

            <div className="pr:grid pr:grid-cols-3 pr:gap-4 pr:mb-6">
              <div className="pr:text-center pr:p-4 pr:bg-success-50 pr:rounded-lg">
                <div className="pr:text-2xl pr:font-bold pr:text-success-700">
                  {healthData?.summary?.passed || 0}
                </div>
                <div className="pr:text-sm pr:text-success-600">{__('Passed', 'prorank-seo')}</div>
              </div>
              <div className="pr:text-center pr:p-4 pr:bg-warning-50 pr:rounded-lg">
                <div className="pr:text-2xl pr:font-bold pr:text-warning-700">
                  {healthData?.summary?.warnings || 0}
                </div>
                <div className="pr:text-sm pr:text-warning-600">{__('Warnings', 'prorank-seo')}</div>
              </div>
              <div className="pr:text-center pr:p-4 pr:bg-error-50 pr:rounded-lg">
                <div className="pr:text-2xl pr:font-bold pr:text-error-700">
                  {healthData?.summary?.failed || 0}
                </div>
                <div className="pr:text-sm pr:text-error-600">{__('Failed', 'prorank-seo')}</div>
              </div>
            </div>

            <Button
              variant="primary"
              onClick={runHealthScan}
              loading={scanning}
              disabled={scanning}
            >
              {scanning ? __('Scanning…', 'prorank-seo') : __('Run Full Scan', 'prorank-seo')}
            </Button>
          </div>
        </div>
      </Card>

      {/* Health Checks */}
      <Card
        variant="elevated"
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('SEO Health Checks', 'prorank-seo')}
          </h3>
        }
      >
        {healthData?.checks && healthData.checks.length > 0 ? (
          <div className="pr:space-y-4">
            {healthData.checks.map((checkItem, index) => {
              const IconComponent = getCheckIcon(checkItem.status);
              const iconColor = getCheckColor(checkItem.status);
              const badgeVariant = getBadgeVariant(checkItem.status);

              return (
                <div
                  key={index}
                  className="pr:flex pr:items-start pr:gap-4 pr:p-4 pr:rounded-lg pr:border pr:border-gray-200"
                >
                  <IconComponent className={`pr:w-6 pr:h-6 pr:shrink-0 pr:mt-0.5 ${iconColor}`} />
                  <div className="pr:flex-1">
                    <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                      {checkItem.name}
                    </h4>
                    <p className="pr:text-sm pr:text-gray-600">{checkItem.message}</p>

                    {checkItem.status !== 'pass' && checkItem.solution && (
                      <div className="pr:mt-3 pr:p-3 pr:bg-gray-50 pr:rounded-md">
                        <p className="pr:text-sm pr:text-gray-700">
                          <span className="pr:font-semibold">{__('Solution:', 'prorank-seo')}</span>{' '}
                          {checkItem.solution}
                        </p>
                        {checkItem.action && (
                          <a
                            href={checkItem.action.url}
                            className="pr:inline-block pr:mt-2 pr:text-sm pr:text-primary-600 pr:hover:text-primary-700 pr:font-medium"
                          >
                            {checkItem.action.label} →
                          </a>
                        )}
                      </div>
                    )}
                  </div>
                  <Badge variant={badgeVariant} size="sm">
                    {checkItem.status === 'pass' && __('Passed', 'prorank-seo')}
                    {checkItem.status === 'warning' && __('Warning', 'prorank-seo')}
                    {checkItem.status === 'fail' && __('Failed', 'prorank-seo')}
                  </Badge>
                </div>
              );
            })}
          </div>
        ) : (
          <Alert variant="info" title={__('No Checks Available', 'prorank-seo')}>
            {__('No health checks available. Run a scan to check your SEO health.', 'prorank-seo')}
          </Alert>
        )}
      </Card>

      {/* Recommendations */}
      {healthData?.recommendations && healthData.recommendations.length > 0 && (
        <Card
          variant="elevated"
          header={
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Recommendations', 'prorank-seo')}
            </h3>
          }
        >
          <div className="pr:space-y-4">
            {healthData.recommendations.map((rec, index) => (
              <div
                key={index}
                className="pr:flex pr:items-start pr:gap-4 pr:p-4 pr:rounded-lg pr:bg-info-50 pr:border pr:border-info-200"
              >
                <LightBulbIcon className="pr:w-6 pr:h-6 pr:text-info-600 pr:shrink-0" />
                <div className="pr:flex-1">
                  <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                    {rec.title}
                  </h4>
                  <p className="pr:text-sm pr:text-gray-600">{rec.description}</p>
                  {rec.link && (
                    <a
                      href={rec.link}
                      className="pr:inline-block pr:mt-2 pr:text-sm pr:text-primary-600 pr:hover:text-primary-700 pr:font-medium"
                    >
                      {__('Learn More →', 'prorank-seo')}
                    </a>
                  )}
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* Last Scan Info */}
      {healthData?.last_scan && (
        <p className="pr:text-sm pr:text-gray-500 pr:text-center">
          {sprintf(
            __('Last scan: %s', 'prorank-seo'),
            new Date(healthData.last_scan).toLocaleString()
          )}
        </p>
      )}
    </div>
  );
};

export default HealthTab;
