import React, { useState, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Button, Alert, Badge, Toggle } from '../../../components/ui';

interface VersionSettings {
  auto_update: boolean;
}

interface BackupInfo {
  path: string;
  name: string;
  downloadUrl?: string;
  createdAt?: string;
  size?: number;
}

const CHANGELOG_URL = 'https://wordpress.org/plugins/prorank-seo/#developers';

interface VersionManagementTabProps {
  addNotice?: (type: string, message: string) => void;
}

const VersionManagementTab: React.FC<VersionManagementTabProps> = ({ addNotice }) => {
  const [currentVersion, setCurrentVersion] = useState<string>('');
  const [serviceMessage, setServiceMessage] = useState<string>('');
  const [settings, setSettings] = useState<VersionSettings>({
    auto_update: false,
  });
  const [isLoading, setIsLoading] = useState(true);
  const [isCreatingBackup, setIsCreatingBackup] = useState(false);
  const [isSavingSettings, setIsSavingSettings] = useState(false);
  const [error, setError] = useState<string>('');
  const [backupCreated, setBackupCreated] = useState(false);
  const [backupInfo, setBackupInfo] = useState<BackupInfo | null>(null);

  // Fetch versions and settings on mount
  useEffect(() => {
    fetchVersions();
    fetchSettings();
  }, []);

  const fetchVersions = async () => {
    try {
      const response = await apiFetch<{
        success: boolean;
        current_version: string;
        message?: string;
        latest_backup?: {
          backup_name?: string;
          backup_path?: string;
          download_url?: string;
          created_at?: string;
          size?: number;
        } | null;
      }>({
        path: '/prorank-seo/v1/versions',
      });

      if (response.success) {
        setCurrentVersion(response.current_version || '');
        setServiceMessage(response.message || '');
        if (response.latest_backup?.backup_name || response.latest_backup?.backup_path) {
          setBackupInfo({
            path: response.latest_backup.backup_path || '',
            name: response.latest_backup.backup_name || '',
            downloadUrl: response.latest_backup.download_url || '',
            createdAt: response.latest_backup.created_at || '',
            size: response.latest_backup.size || 0,
          });
        }
      } else {
        setError(response.message || __('Failed to fetch versions', 'prorank-seo'));
      }
    } catch (err: any) {
      setError(err.message || __('Failed to fetch versions', 'prorank-seo'));
    } finally {
      setIsLoading(false);
    }
  };

  const fetchSettings = async () => {
    try {
      const response = await apiFetch<{
        success: boolean;
        settings: VersionSettings;
      }>({
        path: '/prorank-seo/v1/versions/settings',
      });

      if (response.success) {
        setSettings({
          auto_update: Boolean(response.settings?.auto_update),
        });
      }
    } catch (err) {
      console.error('Failed to fetch settings:', err);
    }
  };

  const handleSaveSettings = async () => {
    setIsSavingSettings(true);
    try {
      const response = await apiFetch<{
        success: boolean;
        message?: string;
      }>({
        path: '/prorank-seo/v1/versions/settings',
        method: 'POST',
        data: settings,
      });

      if (response.success) {
        addNotice?.('success', __('Settings saved successfully', 'prorank-seo'));
      } else {
        addNotice?.('error', response.message || __('Failed to save settings', 'prorank-seo'));
      }
    } catch (err: any) {
      addNotice?.('error', err.message || __('Failed to save settings', 'prorank-seo'));
    } finally {
      setIsSavingSettings(false);
    }
  };

  const handleCreateBackup = async () => {
    setIsCreatingBackup(true);
    try {
      const response = await apiFetch<{
        success: boolean;
        message?: string;
        backup_path?: string;
        backup_name?: string;
        download_url?: string;
      }>({
        path: '/prorank-seo/v1/versions/backup',
        method: 'POST',
      });

      if (response.success) {
        setBackupCreated(true);
        setBackupInfo({
          path: response.backup_path || '',
          name: response.backup_name || (response.backup_path ? response.backup_path.split('/').pop() || '' : ''),
          downloadUrl: response.download_url || '',
        });
        addNotice?.('success', __('Backup created successfully', 'prorank-seo'));
      } else {
        addNotice?.('error', response.message || __('Failed to create backup', 'prorank-seo'));
      }
    } catch (err: any) {
      addNotice?.('error', err.message || __('Failed to create backup', 'prorank-seo'));
    } finally {
      setIsCreatingBackup(false);
    }
  };

  const handleDownloadBackup = () => {
    if (!backupInfo?.downloadUrl) {
      return;
    }

    window.location.assign(backupInfo.downloadUrl);
  };

  if (isLoading) {
    return (
      <Card>
        <div className="pr:p-6 pr:text-center">
          <div className="pr:animate-spin pr:inline-block pr:w-6 pr:h-6 pr:border-2 pr:border-gray-300 pr:border-t-blue-600 pr:rounded-full" />
          <p className="pr:mt-2 pr:text-gray-600">{__('Loading version information...', 'prorank-seo')}</p>
        </div>
      </Card>
    );
  }

  return (
    <div className="pr:space-y-6">
      {/* Current Version */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-lg pr:font-semibold pr:mb-4">{__('Current Version', 'prorank-seo')}</h3>
          <div className="pr:flex pr:items-center pr:gap-4">
            <div className="pr:text-3xl pr:font-bold pr:text-blue-600">{currentVersion}</div>
            <Badge variant="success">{__('Installed', 'prorank-seo')}</Badge>
          </div>
          <p className="pr:mt-2 pr:text-green-600">
            {__('You are using the latest installed version of this free build', 'prorank-seo')}
          </p>
          <div className="pr:mt-4">
            <Button
              variant="secondary"
              href={CHANGELOG_URL}
              target="_blank"
              rel="noopener noreferrer"
            >
              {__('View Changelog on WordPress.org', 'prorank-seo')}
            </Button>
          </div>
          {serviceMessage && (
            <Alert type="info" className="pr:mt-4">
              {serviceMessage}
            </Alert>
          )}
        </div>
      </Card>

      {/* Version History & Backup */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-lg pr:font-semibold pr:mb-4">{__('Backup & Restore Guidance', 'prorank-seo')}</h3>

          <Alert type="info" className="pr:mb-4">
            {__(
              'This free build uses the standard WordPress updater. Create a backup before manual updates or before installing another approved package.',
              'prorank-seo'
            )}
          </Alert>

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

          <div className="pr:space-y-3 pr:mb-4">
            <div className="pr:p-4 pr:bg-gray-50 pr:rounded-lg">
              <div className="pr:font-medium pr:text-gray-900">{__('Recommended workflow', 'prorank-seo')}</div>
              <ol className="pr:mt-3 pr:space-y-2 pr:text-sm pr:text-gray-700 pr:list-decimal pr:list-inside">
                <li>{__('Create a secure backup of the plugin files from this screen.', 'prorank-seo')}</li>
                <li>{__('Use the WordPress Plugins screen for normal updates.', 'prorank-seo')}</li>
                <li>{__('If you need to restore another approved build, replace the plugin package manually after backing up.', 'prorank-seo')}</li>
              </ol>
            </div>
          </div>

          <div className="pr:flex pr:gap-3">
            <Button
              variant="secondary"
              onClick={handleCreateBackup}
              disabled={isCreatingBackup}
              isLoading={isCreatingBackup}
            >
              {backupCreated ? __('Backup Created', 'prorank-seo') : __('Create Backup', 'prorank-seo')}
            </Button>
            {backupInfo?.downloadUrl && (
              <Button
                variant="primary"
                onClick={handleDownloadBackup}
              >
                {__('Download Backup', 'prorank-seo')}
              </Button>
            )}
          </div>

          {backupInfo && (
            <Alert type="success" className="pr:mt-4">
              <div className="pr:space-y-2">
                <div className="pr:font-medium">
                  {__('Backup stored securely on the server.', 'prorank-seo')}
                </div>
                {backupInfo.name && (
                  <div className="pr:text-sm">
                    <strong>{__('File:', 'prorank-seo')}</strong>{' '}
                    <code>{backupInfo.name}</code>
                  </div>
                )}
                {backupInfo.path && (
                  <div className="pr:text-sm">
                    <strong>{__('Path:', 'prorank-seo')}</strong>{' '}
                    <code>{backupInfo.path}</code>
                  </div>
                )}
                <div className="pr:text-sm pr:text-gray-700">
                  {backupInfo.downloadUrl
                    ? __('Download it directly from this screen while logged into wp-admin, or use the server path if you need to retrieve it manually.', 'prorank-seo')
                    : __('Retrieve it with your host file manager, SFTP, or SSH if you need the archive itself.', 'prorank-seo')}
                </div>
              </div>
            </Alert>
          )}
        </div>
      </Card>

      {/* Auto Update Settings */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-lg pr:font-semibold pr:mb-4">{__('Automatic Updates', 'prorank-seo')}</h3>

          <Alert type="info" className="pr:mb-4">
            {__('This setting controls the standard WordPress auto-update behavior for the ProRank SEO plugin.', 'prorank-seo')}
          </Alert>

          <div className="pr:space-y-4">
            <div className="pr:flex pr:items-center pr:justify-between pr:py-3">
              <div>
                <span className="pr:font-medium">{__('Auto Update Plugin', 'prorank-seo')}</span>
                <p className="pr:text-sm pr:text-gray-500">{__('Automatically install stable updates when available', 'prorank-seo')}</p>
              </div>
              <Toggle
                checked={settings.auto_update}
                onChange={(checked: boolean) => setSettings({ ...settings, auto_update: checked })}
              />
            </div>
          </div>

          <div className="pr:mt-4 pr:pt-4 pr:border-t pr:border-gray-100">
            <Button
              variant="primary"
              onClick={handleSaveSettings}
              disabled={isSavingSettings}
              isLoading={isSavingSettings}
            >
              {__('Save Settings', 'prorank-seo')}
            </Button>
          </div>
        </div>
      </Card>
    </div>
  );
};

export default VersionManagementTab;
