import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import Accordion from '../components/Accordion';
import RouteTest from '../components/RouteTest';

function Collections() {
  const [collections, setCollections] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [migrationModal, setMigrationModal] = useState({
    isOpen: false,
    migration: null,
    loading: false,
    collectionKey: null,
    extensions: [],
    extensionsLoading: false,
    installing: false,
    installSuccess: null
  });
  const [copied, setCopied] = useState(false);
  const [runningMigrations, setRunningMigrations] = useState({});
  const [runningModalMigration, setRunningModalMigration] = useState(false);
  const [runningMigration, setRunningMigration] = useState(null);

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

  const fetchCollections = async () => {
    try {
      const response = await fetch(
        `${window.gatewayAdminScript.apiUrl}gateway/v1/admin-data`,
        {
          headers: {
            'X-WP-Nonce': window.gatewayAdminScript.nonce,
          },
        }
      );

      if (!response.ok) {
        throw new Error('Failed to fetch collections');
      }

      const data = await response.json();
      setCollections(data.collections || []);
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  const fetchExtensions = async () => {
    try {
      const response = await fetch(
        `${window.gatewayAdminScript.apiUrl}gateway/v1/migrations/extensions/list`,
        {
          headers: {
            'X-WP-Nonce': window.gatewayAdminScript.nonce,
          },
        }
      );

      if (!response.ok) {
        throw new Error('Failed to fetch extensions');
      }

      const data = await response.json();
      return data.extensions || [];
    } catch (err) {
      console.error('Error fetching extensions:', err);
      return [];
    }
  };

  const generateMigration = async (collectionKey) => {
    setMigrationModal({
      isOpen: true,
      migration: null,
      loading: true,
      collectionKey,
      extensions: [],
      extensionsLoading: true,
      installing: false,
      installSuccess: null
    });

    try {
      // Fetch both migration and extensions in parallel
      const [migrationResponse, extensions] = await Promise.all([
        fetch(
          `${window.gatewayAdminScript.apiUrl}gateway/v1/migrations/${collectionKey}`,
          {
            headers: {
              'X-WP-Nonce': window.gatewayAdminScript.nonce,
            },
          }
        ),
        fetchExtensions()
      ]);

      if (!migrationResponse.ok) {
        throw new Error('Failed to generate migration');
      }

      const migrationData = await migrationResponse.json();

      setMigrationModal({
        isOpen: true,
        migration: migrationData.migration,
        loading: false,
        collectionKey,
        extensions,
        extensionsLoading: false,
        installing: false,
        installSuccess: null
      });
    } catch (err) {
      alert('Error generating migration: ' + err.message);
      setMigrationModal({
        isOpen: false,
        migration: null,
        loading: false,
        collectionKey: null,
        extensions: [],
        extensionsLoading: false,
        installing: false,
        installSuccess: null
      });
    }
  };

  const installMigration = async (extensionKey) => {
    if (!migrationModal.collectionKey) return;

    setMigrationModal(prev => ({ ...prev, installing: true, installSuccess: null }));

    try {
      const response = await fetch(
        `${window.gatewayAdminScript.apiUrl}gateway/v1/migrations/${migrationModal.collectionKey}/install`,
        {
          method: 'POST',
          headers: {
            'X-WP-Nonce': window.gatewayAdminScript.nonce,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ extension: extensionKey }),
        }
      );

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'Failed to install migration');
      }

      setMigrationModal(prev => ({
        ...prev,
        installing: false,
        installSuccess: {
          message: data.message,
          filePath: data.filePath
        }
      }));
    } catch (err) {
      alert('Error installing migration: ' + err.message);
      setMigrationModal(prev => ({ ...prev, installing: false, installSuccess: null }));
    }
  };

  const runMigration = async (collectionKey) => {
    if (!confirm('Are you sure you want to run this migration? This will create or update the database table.')) {
      return;
    }

    setRunningMigration(collectionKey);

    try {
      const response = await fetch(
        `${window.gatewayAdminScript.apiUrl}gateway/v1/migrations/${collectionKey}/run`,
        {
          method: 'POST',
          headers: {
            'X-WP-Nonce': window.gatewayAdminScript.nonce,
            'Content-Type': 'application/json',
          },
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to run migration');
      }

      const data = await response.json();
      alert(data.message || 'Migration executed successfully!');

      // Refresh collections to update record counts
      fetchCollections();
    } catch (err) {
      alert('Error running migration: ' + err.message);
    } finally {
      setRunningMigration(null);
    }
  };

  const runMigrationFromModal = async () => {
    if (!migrationModal.collectionKey) return;

    setRunningModalMigration(true);

    try {
      const response = await fetch(
        `${window.gatewayAdminScript.apiUrl}gateway/v1/migrations/${migrationModal.collectionKey}/run`,
        {
          method: 'POST',
          headers: {
            'X-WP-Nonce': window.gatewayAdminScript.nonce,
            'Content-Type': 'application/json',
          },
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to run migration');
      }

      const data = await response.json();
      alert(`Success! ${data.message}`);

      // Close modal and refresh collections
      closeMigrationModal();
      await fetchCollections();
    } catch (err) {
      alert('Error running migration: ' + err.message);
    } finally {
      setRunningModalMigration(false);
    }
  };

  const copyToClipboard = async () => {
    if (!migrationModal.migration?.code) return;

    try {
      // Try modern clipboard API first
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(migrationModal.migration.code);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      } else {
        // Fallback for older browsers or non-secure contexts
        const textArea = document.createElement('textarea');
        textArea.value = migrationModal.migration.code;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        document.body.appendChild(textArea);
        textArea.select();

        try {
          document.execCommand('copy');
          setCopied(true);
          setTimeout(() => setCopied(false), 2000);
        } catch (err) {
          console.error('Fallback copy failed:', err);
          alert('Failed to copy to clipboard. Please copy manually.');
        } finally {
          document.body.removeChild(textArea);
        }
      }
    } catch (err) {
      console.error('Copy to clipboard failed:', err);
      alert('Failed to copy to clipboard. Please copy manually.');
    }
  };

  const closeMigrationModal = () => {
    setMigrationModal({
      isOpen: false,
      migration: null,
      loading: false,
      collectionKey: null,
      extensions: [],
      extensionsLoading: false,
      installing: false,
      installSuccess: null
    });
    setCopied(false);
    setRunningModalMigration(false);
  };

  if (loading) {
    return (
      <div className="px-4 py-6 sm:px-0">
        <div className="text-center py-12">
          <p className="text-gray-500">Loading collections...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="px-4 py-6 sm:px-0">
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <p className="text-red-800">Error: {error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="px-4 py-6 sm:px-0">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-900">Registered Collections</h2>
        <p className="text-gray-600 mt-1">
          {collections.length} collection{collections.length !== 1 ? 's' : ''} registered
        </p>
      </div>

      {collections.length === 0 ? (
        <div className="border-2 border-dashed border-gray-200 rounded-lg p-12 text-center">
          <p className="text-gray-500">No collections registered yet</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          {collections.map((collection) => (
            <div
              key={collection.key}
              className="bg-white border border-gray-200 rounded-lg p-6 shadow-sm hover:shadow-md transition-shadow"
            >
              <div className="flex justify-between items-start mb-4">
                <div>
                  <h3 className="text-lg font-semibold text-gray-900">
                    {collection.title}
                  </h3>
                  <Link
                    to={`/collections/${collection.key}`}
                    className="text-sm text-indigo-600 hover:text-indigo-700"
                  >
                    View details →
                  </Link>
                </div>
              </div>

              <div className="space-y-3">
                <div>
                  <dt className="text-xs font-medium text-gray-500">Key</dt>
                  <dd className="mt-1 text-sm text-gray-900 font-mono bg-gray-50 px-2 py-1 rounded">
                    {collection.key}
                  </dd>
                </div>

                <div>
                  <dt className="text-xs font-medium text-gray-500">Class Name</dt>
                  <dd className="mt-1 text-sm text-gray-900 font-mono bg-gray-50 px-2 py-1 rounded">
                    {collection.className}
                  </dd>
                </div>

                <div>
                  <dt className="text-xs font-medium text-gray-500">Fully Qualified Class Name</dt>
                  <dd className="mt-1 text-sm text-gray-900 font-mono bg-gray-50 px-2 py-1 rounded break-all">
                    {collection.fqcn}
                  </dd>
                </div>

                <div>
                  <dt className="text-xs font-medium text-gray-500">Database Table</dt>
                  <dd className="mt-1 text-sm text-gray-900 font-mono bg-gray-50 px-2 py-1 rounded">
                    {collection.table}
                  </dd>
                </div>

                {collection.recordCount !== undefined && (
                  <div>
                    <dt className="text-xs font-medium text-gray-500">Records</dt>
                    <dd className="mt-1 text-sm text-gray-900 font-semibold">
                      {collection.recordCount.toLocaleString()}
                    </dd>
                  </div>
                )}
              </div>

              <div className="border-t border-gray-200 pt-4 mt-4 flex gap-2">
                <button
                  onClick={() => generateMigration(collection.key)}
                  className="flex-1 px-3 py-2 text-sm bg-gray-600 text-white rounded hover:bg-gray-700 transition-colors"
                >
                  Generate Migration
                </button>
                <button
                  onClick={() => runMigration(collection.key)}
                  disabled={runningMigration === collection.key}
                  className="flex-1 px-3 py-2 text-sm bg-indigo-600 text-white rounded hover:bg-indigo-700 transition-colors disabled:bg-indigo-400 disabled:cursor-not-allowed"
                >
                  {runningMigration === collection.key ? 'Running...' : 'Run Migration'}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Migration Modal */}
      {migrationModal.isOpen && (
        <div className="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center p-4" style={{ zIndex: 999999 }}>
          <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            {/* Modal Header */}
            <div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
              <h3 className="text-xl font-semibold text-gray-900">
                {migrationModal.loading ? 'Generating Migration...' : 'Database Migration'}
              </h3>
              <button
                onClick={closeMigrationModal}
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* Modal Body */}
            <div className="flex-1 overflow-y-auto px-6 py-4">
              {migrationModal.loading ? (
                <div className="text-center py-12">
                  <p className="text-gray-500">Generating migration code...</p>
                </div>
              ) : migrationModal.migration ? (
                <div className="space-y-4">
                  {/* Install Success Message */}
                  {migrationModal.installSuccess && (
                    <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                      <h4 className="font-semibold text-green-900 mb-2 flex items-center">
                        <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                        </svg>
                        Migration Installed Successfully!
                      </h4>
                      <p className="text-sm text-green-800">{migrationModal.installSuccess.message}</p>
                      <p className="text-xs text-green-700 mt-2 font-mono bg-green-100 px-2 py-1 rounded">
                        {migrationModal.installSuccess.filePath}
                      </p>
                    </div>
                  )}

                  {/* Install to Extension Section */}
                  {migrationModal.extensions.length > 0 && !migrationModal.installSuccess && (
                    <div className="bg-indigo-50 border border-indigo-200 rounded-lg p-4">
                      <h4 className="font-semibold text-indigo-900 mb-3">Install to Extension</h4>
                      <p className="text-sm text-indigo-800 mb-3">
                        Install this migration directly to one of your registered extensions:
                      </p>
                      <div className="space-y-2">
                        {migrationModal.extensions.map((extension) => (
                          <div key={extension.key} className="flex items-center justify-between bg-white p-3 rounded border border-indigo-100">
                            <div>
                              <div className="font-medium text-gray-900">{extension.slug}</div>
                              <div className="text-xs text-gray-500 font-mono">{extension.databasePath}</div>
                            </div>
                            <button
                              onClick={() => installMigration(extension.key)}
                              disabled={migrationModal.installing}
                              className="px-3 py-1.5 text-sm bg-indigo-600 text-white rounded hover:bg-indigo-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                              {migrationModal.installing ? 'Installing...' : 'Install'}
                            </button>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Instructions */}
                  {!migrationModal.installSuccess && (
                    <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                      <h4 className="font-semibold text-blue-900 mb-2">Manual Installation Instructions:</h4>
                      <ol className="list-decimal list-inside space-y-1 text-sm text-blue-800">
                        <li>Save this file to your plugin (e.g., <code className="bg-blue-100 px-1 rounded">/lib/Database/{migrationModal.migration.className}.php</code>)</li>
                        <li>Require the file in your plugin</li>
                        <li>Call <code className="bg-blue-100 px-1 rounded">{migrationModal.migration.className}::create()</code> from your activation hook</li>
                      </ol>
                    </div>
                  )}

                  {/* Notes */}
                  {migrationModal.migration.notes && migrationModal.migration.notes.length > 0 && (
                    <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                      <h4 className="font-semibold text-yellow-900 mb-2">Notes:</h4>
                      <ul className="list-disc list-inside space-y-1 text-sm text-yellow-800">
                        {migrationModal.migration.notes.map((note, index) => (
                          <li key={index}>{note}</li>
                        ))}
                      </ul>
                    </div>
                  )}

                  {/* Code */}
                  <div className="relative">
                    <div className="flex justify-between items-center mb-2">
                      <h4 className="font-semibold text-gray-900">Generated Code:</h4>
                      <button
                        onClick={copyToClipboard}
                        className="px-3 py-1 text-sm bg-gray-700 text-white rounded hover:bg-gray-800 transition-colors"
                      >
                        {copied ? 'Copied!' : 'Copy to Clipboard'}
                      </button>
                    </div>
                    <pre className="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-sm">
                      <code>{migrationModal.migration.code}</code>
                    </pre>
                  </div>
                </div>
              ) : null}
            </div>

            {/* Modal Footer */}
            <div className="px-6 py-4 border-t border-gray-200 flex justify-between">
              <button
                onClick={runMigrationFromModal}
                disabled={runningModalMigration || migrationModal.loading}
                className={`px-4 py-2 rounded transition-colors ${
                  runningModalMigration || migrationModal.loading
                    ? 'bg-gray-400 text-white cursor-not-allowed'
                    : 'bg-green-600 text-white hover:bg-green-700'
                }`}
              >
                {runningModalMigration ? 'Running Migration...' : 'Run Now'}
              </button>
              <button
                onClick={closeMigrationModal}
                className="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition-colors"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default Collections;
