import React, { useState, useEffect } from 'react';
import { Monitor, Sun, Moon } from 'lucide-react';
import { Label } from '../components/ui/label';
import { Switch } from '../components/ui/switch';
import { Input } from '../components/ui/input';
import { ThemeProvider, useTheme } from '../contexts/ThemeContext';
import { Settings } from '../types';
import type { Theme } from '../lib/theme-manager';

const SettingsContent: React.FC = () => {
  const { theme, setTheme } = useTheme();
  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 handleThemeChange = async (newTheme: Theme) => {
    try {
      await window.settingsAPI.setSetting('theme', newTheme);
      setTheme(newTheme);
      setSettings(prev => prev ? { ...prev, theme: newTheme } : null);
    } catch (error) {
      console.error('Failed to update theme setting:', error);
    }
  };

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

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

      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="h-screen w-screen bg-background flex items-center justify-center">
        <div className="text-muted-foreground">Loading settings...</div>
      </div>
    );
  }

  return (
    <div className="h-screen w-screen bg-background flex flex-col overflow-hidden">
      {/* Header - matching Canvas Settings style */}
      <div
        className="border-b border-border bg-secondary px-6"
        style={{
          WebkitAppRegion: 'drag'
        } as React.CSSProperties}
      >
        <h1
          className="text-base font-semibold text-center py-2 text-foreground select-none"
          style={{
            WebkitAppRegion: 'no-drag'
          } as React.CSSProperties}
        >
          Instructure Agent Settings
        </h1>
      </div>

      {/* Main Content */}
      <div className="flex-1 overflow-y-auto p-8">
        <div className="max-w-2xl mx-auto">

          {/* Appearance Section */}
          <div className="bg-card rounded-lg shadow-sm border border-border p-6 mb-6">
            <div className="mb-4">
              <Label className="text-base font-semibold text-foreground">
                Appearance
              </Label>
              <p className="text-sm text-muted-foreground mt-1">
                Choose how Instructure Agent looks on your device
              </p>
            </div>

            <div className="flex gap-3">
              <button
                onClick={() => handleThemeChange('light')}
                className={`flex-1 flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-colors ${
                  theme === 'light'
                    ? 'border-blue-600 bg-blue-50 dark:bg-blue-950'
                    : 'border-border bg-card hover:bg-accent'
                }`}
              >
                <Sun className={`h-6 w-6 ${theme === 'light' ? 'text-blue-600' : 'text-foreground'}`} />
                <div className="text-center">
                  <div className={`text-sm font-medium ${theme === 'light' ? 'text-blue-600' : 'text-foreground'}`}>
                    Light
                  </div>
                  <div className="text-xs text-muted-foreground">
                    Always light
                  </div>
                </div>
              </button>

              <button
                onClick={() => handleThemeChange('dark')}
                className={`flex-1 flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-colors ${
                  theme === 'dark'
                    ? 'border-blue-600 bg-blue-50 dark:bg-blue-950'
                    : 'border-border bg-card hover:bg-accent'
                }`}
              >
                <Moon className={`h-6 w-6 ${theme === 'dark' ? 'text-blue-600' : 'text-foreground'}`} />
                <div className="text-center">
                  <div className={`text-sm font-medium ${theme === 'dark' ? 'text-blue-600' : 'text-foreground'}`}>
                    Dark
                  </div>
                  <div className="text-xs text-muted-foreground">
                    Always dark
                  </div>
                </div>
              </button>

              <button
                onClick={() => handleThemeChange('system')}
                className={`flex-1 flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-colors ${
                  theme === 'system'
                    ? 'border-blue-600 bg-blue-50 dark:bg-blue-950'
                    : 'border-border bg-card hover:bg-accent'
                }`}
              >
                <Monitor className={`h-6 w-6 ${theme === 'system' ? 'text-blue-600' : 'text-foreground'}`} />
                <div className="text-center">
                  <div className={`text-sm font-medium ${theme === 'system' ? 'text-blue-600' : 'text-foreground'}`}>
                    System
                  </div>
                  <div className="text-xs text-muted-foreground">
                    Match OS
                  </div>
                </div>
              </button>
            </div>
          </div>

          {/* Auto-Update Toggle */}
          <div className="bg-card rounded-lg shadow-sm border border-border 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-foreground">
                  Automatic Updates
                </Label>
                <p className="text-sm text-muted-foreground 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-card rounded-lg shadow-sm border border-border p-6">
            <div className="mb-4">
              <Label htmlFor="github-token" className="text-base font-semibold text-foreground">
                GitHub Personal Access Token
              </Label>
              <p className="text-sm text-muted-foreground 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="font-mono pr-16"
                  disabled={isSaving}
                />
                <button
                  type="button"
                  onClick={() => setShowToken(!showToken)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground hover:text-foreground transition-colors"
                >
                  {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:opacity-50 disabled:cursor-not-allowed text-sm font-medium transition-colors"
                >
                  Save Token
                </button>
                {settings.githubToken && (
                  <button
                    onClick={handleTokenClear}
                    disabled={isSaving}
                    className="px-4 py-2 bg-secondary text-foreground rounded-md hover:bg-accent disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium border border-border transition-colors"
                  >
                    Clear Token
                  </button>
                )}
              </div>
            </div>

            {/* Help Text */}
            <div className="mt-6 p-4 bg-secondary rounded-md border border-border">
              <h4 className="text-sm font-semibold text-foreground mb-2">How to create a GitHub token:</h4>
              <ol className="text-sm text-muted-foreground space-y-1 list-decimal list-inside">
                <li>Go to <a href="https://github.com/settings/tokens/new" target="_blank" rel="noopener noreferrer" className="text-blue-600 dark:text-blue-400 underline hover:opacity-80 transition-opacity">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-accent px-1 rounded text-foreground">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 dark:bg-green-400 rounded-full"></div>
                <span className="text-green-700 dark:text-green-400 font-medium">Token configured</span>
                <span className="text-muted-foreground">• 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 dark:bg-yellow-400 rounded-full"></div>
                <span className="text-yellow-700 dark:text-yellow-400 font-medium">No token configured</span>
                <span className="text-muted-foreground">• Updates from private repos will fail</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

const App: React.FC = () => (
  <ThemeProvider>
    <SettingsContent />
  </ThemeProvider>
);

export default App;
