import React, { useState, useEffect } from 'react';
import { Label } from '../components/ui/label';
import { Switch } from '../components/ui/switch';
import { Settings } from '../types';

const UpdatesTab: React.FC = () => {
  const [settings, setSettings] = useState<Settings | null>(null);
  const [githubToken, setGithubToken] = useState('');
  const [showToken, setShowToken] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

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

  const loadSettings = async () => {
    try {
      const loadedSettings = await window.settingsAPI.getSettings();
      setSettings(loadedSettings);
      setGithubToken(loadedSettings.githubToken || '');
    } catch (error) {
      console.error('Failed to load settings:', error);
    }
  };

  const handleAutoUpdateToggle = async (enabled: boolean) => {
    try {
      await window.settingsAPI.setSetting('autoUpdate', enabled);
      setSettings(prev => prev ? { ...prev, autoUpdate: enabled } : null);
    } catch (error) {
      console.error('Failed to update autoUpdate setting:', error);
    }
  };

  const handleTokenSave = async () => {
    if (!githubToken.trim() && !settings?.githubToken) {
      // Nothing to save
      return;
    }

    setIsSaving(true);
    try {
      await window.settingsAPI.setSetting('githubToken', githubToken.trim());
      setSettings(prev => prev ? { ...prev, githubToken: githubToken.trim() } : null);

      // Show success feedback
      const saveButton = document.getElementById('save-token-btn');
      if (saveButton) {
        saveButton.textContent = 'Saved!';
        setTimeout(() => {
          saveButton.textContent = 'Save Token';
        }, 2000);
      }
    } catch (error) {
      console.error('Failed to save GitHub token:', error);
      alert('Failed to save GitHub token. Please try again.');
    } finally {
      setIsSaving(false);
    }
  };

  const handleTokenClear = async () => {
    setIsSaving(true);
    try {
      await window.settingsAPI.setSetting('githubToken', '');
      setGithubToken('');
      setSettings(prev => prev ? { ...prev, githubToken: '' } : null);
    } catch (error) {
      console.error('Failed to clear GitHub token:', error);
      alert('Failed to clear GitHub token. Please try again.');
    } finally {
      setIsSaving(false);
    }
  };

  if (!settings) {
    return (
      <div className="flex-1 flex items-center justify-center p-8">
        <div className="text-gray-500">Loading settings...</div>
      </div>
    );
  }

  return (
    <div className="flex-1 overflow-y-auto p-8">
      <div className="max-w-2xl">
        <h2 className="text-2xl font-bold mb-6 text-gray-800">Updates</h2>

        {/* Auto-Update Toggle */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <Label htmlFor="auto-update" className="text-base font-semibold text-gray-800">
                Automatic Updates
              </Label>
              <p className="text-sm text-gray-600 mt-1">
                Automatically check for and download updates when available
              </p>
            </div>
            <Switch
              id="auto-update"
              checked={settings.autoUpdate}
              onCheckedChange={handleAutoUpdateToggle}
            />
          </div>
        </div>

        {/* GitHub Token Section */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="mb-4">
            <Label htmlFor="github-token" className="text-base font-semibold text-gray-800">
              GitHub Personal Access Token
            </Label>
            <p className="text-sm text-gray-600 mt-1">
              Required for updating from private repositories. This token is stored securely on your computer and is only used to check for and download updates.
            </p>
          </div>

          {/* Token Input */}
          <div className="space-y-4">
            <div className="relative">
              <input
                id="github-token"
                type={showToken ? 'text' : 'password'}
                value={githubToken}
                onChange={(e) => setGithubToken(e.target.value)}
                placeholder="ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono text-sm"
                disabled={isSaving}
              />
              <button
                type="button"
                onClick={() => setShowToken(!showToken)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-sm text-gray-500 hover:text-gray-700"
              >
                {showToken ? 'Hide' : 'Show'}
              </button>
            </div>

            <div className="flex gap-2">
              <button
                id="save-token-btn"
                onClick={handleTokenSave}
                disabled={isSaving || githubToken === settings.githubToken}
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-sm font-medium"
              >
                Save Token
              </button>
              {settings.githubToken && (
                <button
                  onClick={handleTokenClear}
                  disabled={isSaving}
                  className="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 disabled:bg-gray-100 disabled:cursor-not-allowed text-sm font-medium"
                >
                  Clear Token
                </button>
              )}
            </div>
          </div>

          {/* Help Text */}
          <div className="mt-6 p-4 bg-blue-50 rounded-md border border-blue-200">
            <h4 className="text-sm font-semibold text-blue-900 mb-2">How to create a GitHub token:</h4>
            <ol className="text-sm text-blue-800 space-y-1 list-decimal list-inside">
              <li>Go to <a href="https://github.com/settings/tokens/new" target="_blank" rel="noopener noreferrer" className="underline hover:text-blue-600">GitHub Settings → Tokens</a></li>
              <li>Click "Generate new token (classic)"</li>
              <li>Give it a name like "Instructure Agent Updates"</li>
              <li>Select scope: <code className="bg-blue-100 px-1 rounded">repo</code> (Full control of private repositories)</li>
              <li>Click "Generate token" and copy the token</li>
              <li>Paste it here and click "Save Token"</li>
            </ol>
          </div>

          {/* Token Status */}
          {settings.githubToken && (
            <div className="mt-4 flex items-center gap-2 text-sm">
              <div className="w-2 h-2 bg-green-500 rounded-full"></div>
              <span className="text-green-700 font-medium">Token configured</span>
              <span className="text-gray-500">• Updates will use this token for authentication</span>
            </div>
          )}
          {!settings.githubToken && (
            <div className="mt-4 flex items-center gap-2 text-sm">
              <div className="w-2 h-2 bg-yellow-500 rounded-full"></div>
              <span className="text-yellow-700 font-medium">No token configured</span>
              <span className="text-gray-500">• Updates from private repos will fail</span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default UpdatesTab;
