/**
 * Ready Step Component
 *
 * Final step showing setup completion and next steps
 * with confirmation modal before completing setup
 */

import { useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Card, Button, Alert, Modal } from '../../../../components/ui';
import {
  CheckCircleIcon,
  ArrowRightIcon,
  ArrowTopRightOnSquareIcon,
  DocumentTextIcon,
  QuestionMarkCircleIcon,
  ChartBarIcon,
  CogIcon,
  RocketLaunchIcon,
  XMarkIcon,
} from '@heroicons/react/24/outline';

const ReadyStep = ({ wizardData, onComplete }) => {
  const [showConfirmation, setShowConfirmation] = useState(false);
  const [completing, setCompleting] = useState(false);

  // Handle final completion with confirmation
  const handleCompleteSetup = () => {
    setShowConfirmation(true);
  };

  const handleConfirm = async () => {
    setCompleting(true);
    try {
      if (onComplete) {
        await onComplete();
      } else {
        window.location.href = '/wp-admin/admin.php?page=prorank-seo';
      }
    } finally {
      setCompleting(false);
    }
  };

  const handleCancel = () => {
    setShowConfirmation(false);
  };

  // Calculate setup summary
  const setupSummary = {
    competitorsHandled: wizardData.deactivatedCompetitors?.length > 0 || wizardData.skippedImport,
    dataImported: wizardData.importResults ? Object.keys(wizardData.importResults).length : 0,
    siteBasicsConfigured: wizardData.siteBasicsCompleted || false,
    analyticsConnected: wizardData.analytics_status?.ga4?.connected || wizardData.analytics_status?.gsc?.connected || false,
    modulesSelected: Object.values(wizardData.selectedModules || {}).filter(Boolean).length,
    optimizationsApplied: Object.values(wizardData.optimizations_applied || {}).filter(Boolean).length,
  };

  const nextSteps = [
    {
      title: __('Run SEO Audit', 'prorank-seo'),
      description: __('Analyze your site for SEO issues and get recommendations', 'prorank-seo'),
      link: '/wp-admin/admin.php?page=prorank-site-audit',
      icon: ChartBarIcon,
    },
    {
      title: __('Optimize Your Content', 'prorank-seo'),
      description: __('Use AI-powered content analysis to improve your posts and pages', 'prorank-seo'),
      link: '/wp-admin/edit.php',
      icon: DocumentTextIcon,
    },
    {
      title: __('Configure Advanced Settings', 'prorank-seo'),
      description: __('Fine-tune your SEO settings for maximum performance', 'prorank-seo'),
      link: '/wp-admin/admin.php?page=prorank-seo',
      icon: CogIcon,
    },
    {
      title: __('View Documentation', 'prorank-seo'),
      description: __('Learn how to use all ProRank SEO features effectively', 'prorank-seo'),
      link: 'https://docs.prorank.io',
      icon: DocumentTextIcon,
      external: true,
    },
  ];

  return (
    <div className="pr:space-y-6">
      {/* Success Header */}
      <div className="pr:text-center pr:py-8">
        <div className="pr:inline-flex pr:items-center pr:justify-center pr:w-20 pr:h-20 pr:bg-success-100 pr:rounded-full pr:mb-4">
          <CheckCircleIcon className="pr:w-12 pr:h-12 pr:text-success-600" />
        </div>
        <h1 className="pr:text-3xl pr:font-semibold pr:text-gray-900 pr:mb-2">
          {__('Congratulations! Setup Complete', 'prorank-seo')}
        </h1>
        <p className="pr:text-gray-600 pr:text-lg">
          {__('ProRank SEO is now configured and ready to help you improve your search rankings.', 'prorank-seo')}
        </p>
      </div>

      {/* Setup Summary */}
      <Card variant="elevated">
        <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-4">
          {__('Setup Summary', 'prorank-seo')}
        </h3>
        <div className="pr:space-y-3">
          <div className="pr:flex pr:items-center pr:gap-3">
            <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600 pr:shrink-0" />
            <p className="pr:text-sm pr:text-gray-700">
              {setupSummary.competitorsHandled
                ? __('Competitor plugins handled', 'prorank-seo')
                : __('No competitor plugins found', 'prorank-seo')
              }
            </p>
          </div>

          {setupSummary.dataImported > 0 && (
            <div className="pr:flex pr:items-center pr:gap-3">
              <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600 pr:shrink-0" />
              <p className="pr:text-sm pr:text-gray-700">
                {sprintf(__('Data imported from %d plugin(s)', 'prorank-seo'), setupSummary.dataImported)}
              </p>
            </div>
          )}

          {setupSummary.siteBasicsConfigured && (
            <div className="pr:flex pr:items-center pr:gap-3">
              <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600 pr:shrink-0" />
              <p className="pr:text-sm pr:text-gray-700">{__('Site basics configured', 'prorank-seo')}</p>
            </div>
          )}

          {setupSummary.analyticsConnected && (
            <div className="pr:flex pr:items-center pr:gap-3">
              <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600 pr:shrink-0" />
              <p className="pr:text-sm pr:text-gray-700">{__('Analytics services connected', 'prorank-seo')}</p>
            </div>
          )}

          {setupSummary.modulesSelected > 0 && (
            <div className="pr:flex pr:items-center pr:gap-3">
              <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600 pr:shrink-0" />
              <p className="pr:text-sm pr:text-gray-700">
                {sprintf(__('%d modules activated', 'prorank-seo'), setupSummary.modulesSelected)}
              </p>
            </div>
          )}

          {setupSummary.optimizationsApplied > 0 && (
            <div className="pr:flex pr:items-center pr:gap-3">
              <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600 pr:shrink-0" />
              <p className="pr:text-sm pr:text-gray-700">
                {sprintf(__('%d optimizations applied', 'prorank-seo'), setupSummary.optimizationsApplied)}
              </p>
            </div>
          )}
        </div>
      </Card>

      {/* Next Steps */}
      <Card variant="elevated">
        <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-4">
          {__('Recommended Next Steps', 'prorank-seo')}
        </h3>
        <div className="pr:space-y-4">
          {nextSteps.map((step, index) => {
            const IconComponent = step.icon;
            return (
              <div key={index} className="pr:flex pr:items-start pr:gap-4 pr:p-4 pr:bg-gray-50 pr:rounded-lg">
                <div className="pr:p-2 pr:bg-primary-100 pr:rounded-lg">
                  <IconComponent className="pr:w-5 pr:h-5 pr:text-primary-600" />
                </div>
                <div className="pr:flex-1">
                  <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
                    {step.title}
                  </h4>
                  <p className="pr:text-sm pr:text-gray-600">{step.description}</p>
                </div>
                <a
                  href={step.link}
                  target={step.external ? '_blank' : '_self'}
                  rel={step.external ? 'noopener noreferrer' : undefined}
                  className="pr:inline-flex pr:items-center pr:gap-2 pr:text-sm pr:font-medium pr:text-primary-600 pr:hover:text-primary-700 pr:transition-colors"
                >
                  {step.external ? __('Learn More', 'prorank-seo') : __('Go', 'prorank-seo')}
                  {step.external ? (
                    <ArrowTopRightOnSquareIcon className="pr:w-4 pr:h-4" />
                  ) : (
                    <ArrowRightIcon className="pr:w-4 pr:h-4" />
                  )}
                </a>
              </div>
            );
          })}
        </div>
      </Card>

      {/* Help Section */}
      <Card variant="elevated">
        <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-2">
          {__('Need Help?', 'prorank-seo')}
        </h3>
        <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
          {__('Our support team is here to help you succeed with ProRank SEO.', 'prorank-seo')}
        </p>
        <div className="pr:flex pr:items-center pr:gap-3">
          <Button
            variant="secondary"
            onClick={() => window.open('https://support.prorank.io', '_blank')}
            icon={QuestionMarkCircleIcon}
          >
            {__('Contact Support', 'prorank-seo')}
          </Button>
          <a
            href="https://community.prorank.io"
            target="_blank"
            rel="noopener noreferrer"
            className="pr:text-sm pr:font-medium pr:text-primary-600 pr:hover:text-primary-700 pr:transition-colors"
          >
            {__('Join Community', 'prorank-seo')}
          </a>
        </div>
      </Card>

      {/* Pro Tip */}
      <Alert variant="info" title={__('Pro Tip', 'prorank-seo')}>
        {__('Run the SEO Audit tool regularly to monitor your site\'s health and discover new optimization opportunities.', 'prorank-seo')}
      </Alert>

      {/* Final Action */}
      <div className="pr:flex pr:justify-center">
        <Button
          variant="primary"
          size="lg"
          onClick={handleCompleteSetup}
          icon={RocketLaunchIcon}
          disabled={completing}
        >
          {__('Complete Setup & Go to Dashboard', 'prorank-seo')}
        </Button>
      </div>

      {/* Confirmation Modal */}
      {showConfirmation && (
        <div
          className="pr:fixed pr:inset-0 pr:z-50 pr:flex pr:items-center pr:justify-center pr:bg-black/50"
          role="dialog"
          aria-modal="true"
          aria-labelledby="confirmation-title"
        >
          <div className="pr:bg-white pr:rounded-xl pr:shadow-xl pr:max-w-md pr:w-full pr:mx-4 pr:overflow-hidden">
            {/* Modal Header */}
            <div className="pr:flex pr:items-center pr:justify-between pr:px-6 pr:py-4 pr:border-b pr:border-gray-200">
              <h3 id="confirmation-title" className="pr:text-lg pr:font-semibold pr:text-gray-900">
                {__('Complete Setup?', 'prorank-seo')}
              </h3>
              <button
                type="button"
                onClick={handleCancel}
                className="pr:p-2 pr:text-gray-400 pr:hover:text-gray-500 pr:rounded-lg pr:hover:bg-gray-100 pr:transition-colors"
                aria-label={__('Close', 'prorank-seo')}
              >
                <XMarkIcon className="pr:w-5 pr:h-5" />
              </button>
            </div>

            {/* Modal Body */}
            <div className="pr:px-6 pr:py-4">
              <div className="pr:flex pr:items-start pr:gap-4">
                <div className="pr:shrink-0 pr:p-3 pr:bg-success-100 pr:rounded-full">
                  <CheckCircleIcon className="pr:w-6 pr:h-6 pr:text-success-600" />
                </div>
                <div>
                  <p className="pr:text-gray-700 pr:mb-3">
                    {__('You\'re all set! Your settings will be saved and you\'ll be redirected to the dashboard.', 'prorank-seo')}
                  </p>
                  <p className="pr:text-sm pr:text-gray-500">
                    {__('You can always change these settings later from the Settings page.', 'prorank-seo')}
                  </p>
                </div>
              </div>
            </div>

            {/* Modal Footer */}
            <div className="pr:flex pr:items-center pr:justify-end pr:gap-3 pr:px-6 pr:py-4 pr:bg-gray-50 pr:border-t pr:border-gray-200">
              <Button
                variant="secondary"
                onClick={handleCancel}
                disabled={completing}
              >
                {__('Review Settings', 'prorank-seo')}
              </Button>
              <Button
                variant="primary"
                onClick={handleConfirm}
                loading={completing}
                disabled={completing}
                icon={RocketLaunchIcon}
              >
                {completing ? __('Completing...', 'prorank-seo') : __('Complete Setup', 'prorank-seo')}
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ReadyStep;
