import { useState, useRef, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { download, upload, trash } from '@wordpress/icons';
import { useNotification } from '../../contexts/NotificationContext';
import { Card, Button, Select, Alert, Modal } from '../../components/ui';

const ImportExport = () => {
  const [exportType, setExportType] = useState('all');
  const [importType, setImportType] = useState('all');
  const [importing, setImporting] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [resetting, setResetting] = useState(false);
  const [showResetModal, setShowResetModal] = useState(false);
  const [importFile, setImportFile] = useState(null);
  const [importError, setImportError] = useState('');
  const fileInputRef = useRef(null);
  const { showNotification } = useNotification();

  // Competitor import state
  const [competitors, setCompetitors] = useState([]);
  const [selectedCompetitors, setSelectedCompetitors] = useState({});
  const [competitorImporting, setCompetitorImporting] = useState(false);
  const [competitorResults, setCompetitorResults] = useState(null);
  const [competitorError, setCompetitorError] = useState('');
  const [competitorProgress, setCompetitorProgress] = useState('');

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

  const TYPE_LABELS = {
    meta: __('SEO Meta', 'prorank-seo'),
    settings: __('Settings', 'prorank-seo'),
    redirects: __('Redirects', 'prorank-seo'),
    schema: __('Schema', 'prorank-seo'),
    locations: __('Local SEO', 'prorank-seo'),
  };

  const detectCompetitors = async () => {
    try {
      // Use migration-status endpoint for richer data (post counts, types)
      const response = await apiFetch({
        path: '/prorank-seo/v1/import-export/migration-status',
      });
      if (response?.data?.competitors) {
        const available = response.data.competitors.filter((c) => c.available);
        setCompetitors(available);
      }
    } catch {
      // Fallback to legacy endpoint
      const FALLBACK_TYPES = {
        yoast: ['meta', 'settings', 'redirects', 'schema', 'locations'],
        rankmath: ['meta', 'settings', 'redirects', 'schema', 'locations'],
        aioseo: ['meta', 'settings', 'redirects', 'schema'],
        seopress: ['meta', 'settings', 'redirects'],
      };
      try {
        const response = await apiFetch({
          path: '/prorank-seo/v1/system/competitors',
        });
        if (response.importable && response.importable.length > 0) {
          const available = [];
          for (const plugin of response.importable) {
            let slug = '';
            if (plugin.name.includes('Yoast')) slug = 'yoast';
            else if (plugin.name.includes('Rank Math')) slug = 'rankmath';
            else if (plugin.name.includes('All in One SEO')) slug = 'aioseo';
            else if (plugin.name.includes('SEOPress')) slug = 'seopress';
            if (slug) {
              available.push({
                slug,
                name: plugin.name,
                available: true,
                post_count: 0,
                types: FALLBACK_TYPES[slug] || ['meta', 'settings'],
              });
            }
          }
          setCompetitors(available);
        }
      } catch {
        // No competitors detected
      }
    }
  };

  const handleCompetitorImport = async () => {
    const selected = Object.keys(selectedCompetitors).filter(k => selectedCompetitors[k]);
    if (selected.length === 0) {
      setCompetitorError(__('Please select at least one plugin to import from.', 'prorank-seo'));
      return;
    }

    setCompetitorImporting(true);
    setCompetitorError('');
    setCompetitorResults(null);

    try {
      const results = {};
      for (const slug of selected) {
        const comp = competitors.find((c) => c.slug === slug);
        setCompetitorProgress(sprintf(__('Importing from %s...', 'prorank-seo'), comp?.name || slug));
        const response = await apiFetch({
          path: '/prorank-seo/v1/import-export/competitor',
          method: 'POST',
          data: {
            source: slug,
            types: comp?.types || ['meta', 'settings', 'redirects', 'schema', 'locations'],
          },
        });
        results[slug] = { ...response, name: comp?.name || slug };
      }
      setCompetitorResults(results);
      setCompetitorProgress('');
      showNotification(__('Import completed successfully!', 'prorank-seo'), 'success');
      // Refresh detection counts
      detectCompetitors();
    } catch (err) {
      setCompetitorError(err.message || __('Import failed. Please try again.', 'prorank-seo'));
    } finally {
      setCompetitorImporting(false);
    }
  };

  // Export options
  const exportOptions = [
    { label: __('All Data', 'prorank-seo'), value: 'all' },
    { label: __('Settings Only', 'prorank-seo'), value: 'settings' },
    { label: __('Module States', 'prorank-seo'), value: 'modules' },
    { label: __('Redirects', 'prorank-seo'), value: 'redirects' },
    { label: __('SEO Meta Data', 'prorank-seo'), value: 'meta' },
  ];

  // Handle export
  const handleExport = async () => {
    setExporting(true);
    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/import-export/export?type=${exportType}`,
      });

      if (response.success) {
        // Create and download file
        const blob = new Blob([atob(response.data)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = response.filename || `prorank-seo-export-${exportType}-${Date.now()}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);

        showNotification(__('Export completed successfully', 'prorank-seo'), 'success');
      }
    } catch (error) {
      showNotification(error.message || __('Export failed', 'prorank-seo'), 'error');
    } finally {
      setExporting(false);
    }
  };

  const handleFileSelect = (event) => {
    const file = event.target.files[0];
    if (file) {
      if (file.type !== 'application/json') {
        setImportError(__('Please select a valid JSON file', 'prorank-seo'));
        setImportFile(null);
        return;
      }
      setImportFile(file);
      setImportError('');
    }
  };

  const handleImport = async () => {
    if (!importFile) {
      setImportError(__('Please select a file to import', 'prorank-seo'));
      return;
    }

    setImporting(true);
    setImportError('');

    try {
      // Read file content
      const fileContent = await new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => resolve(e.target.result);
        reader.onerror = reject;
        reader.readAsText(importFile);
      });

      // Base64 encode for transport
      const encodedData = btoa(fileContent);

      const response = await apiFetch({
        path: '/prorank-seo/v1/import-export/import',
        method: 'POST',
        data: {
          data: encodedData,
          type: importType,
        },
      });

      if (response.success) {
        showNotification(
          response.message || __('Import completed successfully', 'prorank-seo'),
          'success'
        );

        // Reset file input
        setImportFile(null);
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
        
        // Reload page after successful import to reflect changes
        setTimeout(() => {
          window.location.reload();
        }, 2000);
      }
    } catch (error) {
      setImportError(error.message || __('Import failed', 'prorank-seo'));
    } finally {
      setImporting(false);
    }
  };

  const handleReset = async () => {
    setResetting(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/import-export/reset',
        method: 'DELETE',
        data: { confirm: true },
      });

      if (response.success) {
        showNotification(response.message || __('All settings have been reset', 'prorank-seo'), 'success');
        setShowResetModal(false);

        // Reload page after reset
        setTimeout(() => {
          window.location.reload();
        }, 2000);
      }
    } catch (error) {
      showNotification(__('Reset failed', 'prorank-seo'), 'error');
    } finally {
      setResetting(false);
    }
  };

  return (
    <div className="pr:min-h-screen pr:bg-gray-50">
      <div className="pr:p-8 pr:space-y-6">
        <div className="pr:mb-2">
          <h1 className="pr:text-2xl pr:font-semibold pr:text-gray-900 pr:m-0">
            {__('Import & Export', 'prorank-seo')}
          </h1>
          <p className="pr:mt-1 pr:text-sm pr:text-gray-600">
            {__('Transfer settings, module states, and metadata between sites.', 'prorank-seo')}
          </p>
        </div>
        {/* Import from Other SEO Plugins */}
        {competitors.length > 0 && (
          <Card className="pr:mb-6">
            <div className="pr:px-6 pr:py-4 pr:border-b pr:border-gray-200 pr:bg-blue-50">
              <h3 className="pr:text-base pr:font-semibold pr:text-gray-900">
                {__('Import from Other SEO Plugins', 'prorank-seo')}
              </h3>
            </div>
            <div className="pr:p-6">
              <p className="pr:mb-4 pr:text-sm pr:text-gray-600">
                {__('We detected SEO data from other plugins. Select which to import:', 'prorank-seo')}
              </p>

              <div className="pr:space-y-3 pr:mb-4">
                {competitors.map((comp) => (
                  <label
                    key={comp.slug}
                    className={`pr:flex pr:items-start pr:gap-3 pr:p-4 pr:rounded-lg pr:border pr:cursor-pointer pr:transition-all ${
                      selectedCompetitors[comp.slug]
                        ? 'pr:border-blue-500 pr:bg-blue-50'
                        : 'pr:border-gray-200 pr:bg-white hover:pr:border-gray-300'
                    } ${competitorImporting ? 'pr:opacity-60 pr:cursor-not-allowed' : ''}`}
                  >
                    <input
                      type="checkbox"
                      checked={selectedCompetitors[comp.slug] || false}
                      onChange={(e) =>
                        setSelectedCompetitors({
                          ...selectedCompetitors,
                          [comp.slug]: e.target.checked,
                        })
                      }
                      disabled={competitorImporting}
                      className="pr:w-5 pr:h-5 pr:mt-0.5"
                    />
                    <div className="pr:flex-1">
                      <div className="pr:flex pr:items-center pr:gap-2">
                        <span className="pr:font-medium pr:text-gray-900">{comp.name}</span>
                        {comp.post_count > 0 && (
                          <span className="pr:text-xs pr:text-gray-500">
                            {sprintf(__('~%d posts detected', 'prorank-seo'), comp.post_count)}
                          </span>
                        )}
                      </div>
                      {comp.types && comp.types.length > 0 && (
                        <div className="pr:flex pr:flex-wrap pr:gap-1 pr:mt-1">
                          {comp.types.map((type) => (
                            <span
                              key={type}
                              className="pr:inline-block pr:rounded pr:px-1.5 pr:py-0.5 pr:text-xs pr:bg-gray-100 pr:text-gray-500"
                            >
                              {TYPE_LABELS[type] || type}
                            </span>
                          ))}
                        </div>
                      )}
                    </div>
                  </label>
                ))}
              </div>

              {/* Import Results — inline */}
              {competitorResults && (
                <Alert variant="success" className="pr:mb-4">
                  <strong>{__('Import completed!', 'prorank-seo')}</strong>
                  <div className="pr:mt-2 pr:space-y-1">
                    {Object.entries(competitorResults).map(([slug, result]) => (
                      <div key={slug} className="pr:text-sm">
                        <span className="pr:font-medium">{result.name || slug}:</span>{' '}
                        {result.stats
                          ? [
                              result.stats.posts > 0 && sprintf(__('%d posts', 'prorank-seo'), result.stats.posts),
                              result.stats.terms > 0 && sprintf(__('%d terms', 'prorank-seo'), result.stats.terms),
                              result.stats.redirects > 0 && sprintf(__('%d redirects', 'prorank-seo'), result.stats.redirects),
                              result.stats.settings > 0 && sprintf(__('%d settings', 'prorank-seo'), result.stats.settings),
                            ]
                              .filter(Boolean)
                              .join(', ') || __('completed', 'prorank-seo')
                          : __('completed', 'prorank-seo')}
                      </div>
                    ))}
                  </div>
                </Alert>
              )}

              {competitorError && (
                <Alert variant="error" className="pr:mb-4">
                  <p>{competitorError}</p>
                </Alert>
              )}

              {competitorProgress && (
                <div className="pr:flex pr:items-center pr:gap-3 pr:mb-4">
                  <div className="pr:animate-spin pr:w-4 pr:h-4 pr:border-2 pr:border-blue-500 pr:border-t-transparent pr:rounded-full" />
                  <span className="pr:text-sm pr:text-gray-700">{competitorProgress}</span>
                </div>
              )}

              <Button
                variant="primary"
                onClick={handleCompetitorImport}
                disabled={competitorImporting || Object.keys(selectedCompetitors).filter(k => selectedCompetitors[k]).length === 0}
              >
                {competitorImporting
                  ? __('Importing\u2026', 'prorank-seo')
                  : __('Import from Selected Plugins', 'prorank-seo')}
              </Button>
            </div>
          </Card>
        )}

        <div className="pr:grid pr:grid-cols-1 pr:lg:grid-cols-2 pr:gap-6 pr:mb-6">
        {/* Export Section */}
        <Card className="pr:transition-all pr:duration-300">
          <div className="pr:px-6 pr:py-4 pr:border-b pr:border-gray-200 pr:bg-gray-50 pr:transition-all pr:duration-300">
            <h3 className="pr:text-base pr:font-semibold pr:text-gray-900">{__('Export Settings', 'prorank-seo')}</h3>
          </div>
          <div className="pr:p-6">
            <p>
              {__(
                'Export your ProRank SEO settings to a JSON file. This file can be imported into another WordPress site.',
                'prorank-seo'
              )}
            </p>

            <Select
              label={__('Export Type', 'prorank-seo')}
              value={exportType}
              options={exportOptions}
              onChange={setExportType}
              description={__('Choose what data to include in the export', 'prorank-seo')}
              className="pr:mb-4 pr:transition-all pr:duration-300"
            />

            <div className="pr:mb-4">
              {exportType === 'all' && (
                <Alert variant="info" className="pr:transition-all pr:duration-300">
                  <p>
                    {__(
                      'This will export all settings, module states, redirects, and SEO meta data.',
                      'prorank-seo'
                    )}
                  </p>
                </Alert>
              )}
              {exportType === 'settings' && (
                <p>
                  {__(
                    'Only plugin settings will be exported. Module states and content data will not be included.',
                    'prorank-seo'
                  )}
                </p>
              )}
              {exportType === 'modules' && (
                <p>
                  {__(
                    'Only module enabled/disabled states and their settings will be exported.',
                    'prorank-seo'
                  )}
                </p>
              )}
              {exportType === 'redirects' && (
                <p>{__('Only redirect rules will be exported.', 'prorank-seo')}</p>
              )}
              {exportType === 'meta' && (
                <p>
                  {__(
                    'Only SEO meta data (titles, descriptions, etc.) for posts and pages will be exported.',
                    'prorank-seo'
                  )}
                </p>
              )}
            </div>

            <Button
              variant="primary"
              onClick={handleExport}
              disabled={exporting === true}
              className="pr:transition-all pr:duration-300"
            >
              {exporting ? __('Exporting…', 'prorank-seo') : __('Export', 'prorank-seo')}
            </Button>
          </div>
        </Card>

        {/* Import Section */}
        <Card className="pr:transition-all pr:duration-300">
          <div className="pr:px-6 pr:py-4 pr:border-b pr:border-gray-200 pr:bg-gray-50 pr:transition-all pr:duration-300">
            <h3 className="pr:text-base pr:font-semibold pr:text-gray-900">{__('Import Settings', 'prorank-seo')}</h3>
          </div>
          <div className="pr:p-6">
            <p>
              {__(
                'Import ProRank SEO settings from a JSON file exported from another site.',
                'prorank-seo'
              )}
            </p>

            <div className="pr:flex pr:items-center pr:gap-3 pr:mb-4">
              <input
                ref={fileInputRef}
                type="file"
                accept=".json"
                onChange={handleFileSelect}
                style={{ display: 'none' }}
                id="prorank-import-file"
              />
              <label htmlFor="prorank-import-file">
                <Button
                  variant="secondary"
                  icon={upload}
                  onClick={() => fileInputRef.current?.click()}
                >
                  {__('Choose File', 'prorank-seo')}
                </Button>
              </label>
              {importFile && (
                <span className="pr:text-sm pr:text-gray-700 pr:font-medium">
                  {/* translators: %s: placeholder description */}
                  {sprintf(__('Selected: %s', 'prorank-seo'), importFile.name)}
                </span>
              )}
            </div>

            <Select
              label={__('Import Type', 'prorank-seo')}
              value={importType}
              options={exportOptions}
              onChange={setImportType}
              description={__('Choose what data to import from the file', 'prorank-seo')}
              className="pr:mb-4 pr:transition-all pr:duration-300"
            />

            {importError && (
              <Alert variant="error" className="pr:mb-4 pr:transition-all pr:duration-300">
                <p>{importError}</p>
              </Alert>
            )}

            <Alert variant="warning" className="pr:mb-4 pr:transition-all pr:duration-300">
              <p>
                {__(
                  'Warning: Importing will overwrite existing settings. This action cannot be undone.',
                  'prorank-seo'
                )}
              </p>
            </Alert>

            <Button
              variant="primary"
              onClick={handleImport}
              disabled={importing || !importFile}
              className="pr:transition-all pr:duration-300"
            >
              {importing ? __('Importing…', 'prorank-seo') : __('Import', 'prorank-seo')}
            </Button>
          </div>
        </Card>
      </div>

      {/* Reset Section - Full Width */}
      <Card className="pr:transition-all pr:duration-300">
          <div className="pr:px-6 pr:py-4 pr:border-b pr:border-gray-200 pr:bg-gray-50 pr:transition-all pr:duration-300">
            <h3 className="pr:text-base pr:font-semibold pr:text-gray-900">{__('Reset Settings', 'prorank-seo')}</h3>
          </div>
          <div className="pr:p-6">
            <Alert variant="error" className="pr:mb-4 pr:transition-all pr:duration-300">
              <strong>{__('Danger Zone:', 'prorank-seo')}</strong>{' '}
              {__('This action is irreversible!', 'prorank-seo')}
            </Alert>

            <p>
              {__(
                'Reset all ProRank SEO settings to their default values. This will remove all settings, module configurations, and custom data.',
                'prorank-seo'
              )}
            </p>

            <p>
              <strong>{__('This will permanently delete:', 'prorank-seo')}</strong>
            </p>
            <ul>
              <li>{__('All plugin settings', 'prorank-seo')}</li>
              <li>{__('Module configurations', 'prorank-seo')}</li>
              <li>{__('Redirect rules', 'prorank-seo')}</li>
              <li>{__('Custom SEO data', 'prorank-seo')}</li>
            </ul>

            <Button
              variant="danger"
              onClick={() => setShowResetModal(true)}
              className="pr:transition-all pr:duration-300"
            >
              {__('Reset All Settings', 'prorank-seo')}
            </Button>
          </div>
        </Card>

      {/* Reset Confirmation Modal */}
      {showResetModal && (
        <Modal
          isOpen={showResetModal}
          onClose={() => setShowResetModal(false)}
          title={__('Confirm Reset', 'prorank-seo')}
          className="pr:transition-all pr:duration-300"
        >
          <p>
            {__(
              'Are you absolutely sure you want to reset all ProRank SEO settings?',
              'prorank-seo'
            )}
          </p>
          <p>
            <strong>{__('This will permanently delete:', 'prorank-seo')}</strong>
          </p>
          <ul>
            <li>{__('All plugin settings', 'prorank-seo')}</li>
            <li>{__('Module configurations', 'prorank-seo')}</li>
            <li>{__('Redirect rules', 'prorank-seo')}</li>
            <li>{__('Custom SEO data', 'prorank-seo')}</li>
          </ul>
          <p>
            <strong>{__('This action cannot be undone!', 'prorank-seo')}</strong>
          </p>

          <div className="pr:flex pr:gap-2 pr:justify-end pr:mt-6">
            <Button variant="secondary" onClick={() => setShowResetModal(false)} className="pr:transition-all pr:duration-300">
              {__('Cancel', 'prorank-seo')}
            </Button>
            <Button
              variant="danger"
              onClick={handleReset}
              disabled={resetting === true}
              className="pr:transition-all pr:duration-300"
            >
              {resetting
                ? __('Resetting…', 'prorank-seo')
                : __('Yes, Reset Everything', 'prorank-seo')}
            </Button>
          </div>
        </Modal>
      )}
      </div>
    </div>
  );
};

export default ImportExport;
