/**
 * Platform Settings Page
 * Allows superusers to configure platform-wide settings including Stripe credentials and tiers
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Settings,
  CreditCard,
  Shield,
  CheckCircle,
  AlertCircle,
  Loader2,
  Eye,
  EyeOff,
  Lock,
  Users,
  ExternalLink,
  Mail,
  RefreshCw,
} from 'lucide-react';
import {
  usePlatformSettings,
  useUpdateStripeKeys,
  useValidateStripeKeys,
  useUpdateGeneralSettings,
} from '../../hooks/usePlatformSettings';
import {
  usePlatformOAuthSettings,
  useUpdatePlatformOAuthSettings,
} from '../../hooks/usePlatformOAuth';
import { Link } from 'react-router-dom';

type TabType = 'general' | 'stripe' | 'oauth';

const PlatformSettings: React.FC = () => {
  const { t } = useTranslation();
  const [activeTab, setActiveTab] = useState<TabType>('general');

  const tabs: { id: TabType; label: string; icon: React.ElementType }[] = [
    { id: 'general', label: t('platform.settings.general', 'General'), icon: Settings },
    { id: 'stripe', label: 'Stripe', icon: CreditCard },
    { id: 'oauth', label: t('platform.settings.oauthProviders'), icon: Users },
  ];

  return (
    <div className="p-6 max-w-6xl mx-auto">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
          <Settings className="w-7 h-7" />
          {t('platform.settings.title')}
        </h1>
        <p className="mt-2 text-gray-600 dark:text-gray-400">
          {t('platform.settings.description')}
        </p>
      </div>

      {/* Tabs */}
      <div className="border-b border-gray-200 dark:border-gray-700 mb-6">
        <nav className="-mb-px flex space-x-8">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`
                  flex items-center gap-2 py-4 px-1 border-b-2 font-medium text-sm transition-colors
                  ${
                    activeTab === tab.id
                      ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
                  }
                `}
              >
                <Icon className="w-5 h-5" />
                {tab.label}
              </button>
            );
          })}
        </nav>
      </div>

      {/* Tab Content */}
      {activeTab === 'general' && <GeneralSettingsTab />}
      {activeTab === 'stripe' && <StripeSettingsTab />}
      {activeTab === 'oauth' && <OAuthSettingsTab />}
    </div>
  );
};

const GeneralSettingsTab: React.FC = () => {
  const { t } = useTranslation();
  const { data: settings, isLoading } = usePlatformSettings();
  const updateGeneralSettings = useUpdateGeneralSettings();
  const [emailCheckInterval, setEmailCheckInterval] = useState(5);
  const [hasChanges, setHasChanges] = useState(false);

  // Sync local state with settings when loaded
  React.useEffect(() => {
    if (settings?.email_check_interval_minutes) {
      setEmailCheckInterval(settings.email_check_interval_minutes);
    }
  }, [settings]);

  const handleIntervalChange = (value: number) => {
    setEmailCheckInterval(value);
    setHasChanges(value !== settings?.email_check_interval_minutes);
  };

  const handleSaveInterval = async () => {
    await updateGeneralSettings.mutateAsync({ email_check_interval_minutes: emailCheckInterval });
    setHasChanges(false);
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Email Settings Card */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              <Mail className="w-5 h-5" />
              {t('platform.settings.emailAddresses', 'Platform Email Addresses')}
            </h2>
            <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
              Platform email addresses are now managed on a dedicated page with direct integration
              to the mail server.
            </p>
          </div>
          <Link
            to="/platform/email-addresses"
            className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Mail className="w-4 h-4" />
            Manage Email Addresses
          </Link>
        </div>
      </div>

      {/* Email Check Interval */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-4">
          <Mail className="w-5 h-5" />
          Email Polling Settings
        </h2>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Check for new emails every
            </label>
            <div className="flex items-center gap-3">
              <select
                value={emailCheckInterval}
                onChange={(e) => handleIntervalChange(parseInt(e.target.value))}
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value={1}>1 minute</option>
                <option value={2}>2 minutes</option>
                <option value={5}>5 minutes</option>
                <option value={10}>10 minutes</option>
                <option value={15}>15 minutes</option>
                <option value={30}>30 minutes</option>
                <option value={60}>60 minutes</option>
              </select>
              {hasChanges && (
                <button
                  onClick={handleSaveInterval}
                  disabled={updateGeneralSettings.isPending}
                  className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
                >
                  {updateGeneralSettings.isPending ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <CheckCircle className="w-4 h-4" />
                  )}
                  Save
                </button>
              )}
            </div>
            <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
              This controls how often the system checks for incoming emails to create support tickets.
            </p>
          </div>
        </div>
        {updateGeneralSettings.isSuccess && (
          <div className="mt-4 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
            <p className="text-sm text-green-700 dark:text-green-400 flex items-center gap-2">
              <CheckCircle className="w-4 h-4" />
              Email polling interval updated
            </p>
          </div>
        )}
      </div>

      {/* Platform Info */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-4">
          <Settings className="w-5 h-5" />
          {t('platform.settings.platformInfo', 'Platform Information')}
        </h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            <p className="text-sm font-medium text-gray-700 dark:text-gray-300">{t('platform.settings.mailServer')}</p>
            <p className="text-lg font-semibold text-gray-900 dark:text-white">mail.talova.net</p>
          </div>
          <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            <p className="text-sm font-medium text-gray-700 dark:text-gray-300">{t('platform.settings.emailDomain')}</p>
            <p className="text-lg font-semibold text-gray-900 dark:text-white">smoothschedule.com</p>
          </div>
        </div>
      </div>
    </div>
  );
};

const StripeSettingsTab: React.FC = () => {
  const { t } = useTranslation();
  const { data: settings, isLoading, error } = usePlatformSettings();
  const updateKeysMutation = useUpdateStripeKeys();
  const validateKeysMutation = useValidateStripeKeys();

  const [secretKey, setSecretKey] = useState('');
  const [publishableKey, setPublishableKey] = useState('');
  const [webhookSecret, setWebhookSecret] = useState('');
  const [showSecretKey, setShowSecretKey] = useState(false);
  const [showWebhookSecret, setShowWebhookSecret] = useState(false);

  const handleSaveKeys = async () => {
    const keys: Record<string, string> = {};
    if (secretKey) keys.stripe_secret_key = secretKey;
    if (publishableKey) keys.stripe_publishable_key = publishableKey;
    if (webhookSecret) keys.stripe_webhook_secret = webhookSecret;

    if (Object.keys(keys).length === 0) return;

    await updateKeysMutation.mutateAsync(keys);
    setSecretKey('');
    setPublishableKey('');
    setWebhookSecret('');
  };

  const handleValidate = async () => {
    await validateKeysMutation.mutateAsync();
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
        <div className="flex items-center gap-2 text-red-700 dark:text-red-400">
          <AlertCircle className="w-5 h-5" />
          <span>{t('platform.settings.failedToLoadSettings')}</span>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Status Card */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
          <Shield className="w-5 h-5" />
          {t('platform.settings.stripeConfigStatus')}
        </h2>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            {settings?.has_stripe_keys ? (
              <CheckCircle className="w-5 h-5 text-green-500" />
            ) : (
              <AlertCircle className="w-5 h-5 text-yellow-500" />
            )}
            <div>
              <p className="text-sm font-medium text-gray-900 dark:text-white">API Keys</p>
              <p className="text-xs text-gray-500 dark:text-gray-400">
                {settings?.has_stripe_keys ? 'Configured' : 'Not configured'}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            {settings?.stripe_keys_validated_at ? (
              <CheckCircle className="w-5 h-5 text-green-500" />
            ) : (
              <AlertCircle className="w-5 h-5 text-yellow-500" />
            )}
            <div>
              <p className="text-sm font-medium text-gray-900 dark:text-white">{t('platform.settings.validation')}</p>
              <p className="text-xs text-gray-500 dark:text-gray-400">
                {settings?.stripe_keys_validated_at
                  ? `Validated ${new Date(settings.stripe_keys_validated_at).toLocaleDateString()}`
                  : 'Not validated'}
              </p>
            </div>
          </div>
        </div>

        {settings?.stripe_account_id && (
          <div className="mt-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
            <p className="text-sm text-blue-700 dark:text-blue-400">
              <span className="font-medium">{t('platform.settings.accountId')}:</span> {settings.stripe_account_id}
              {settings.stripe_account_name && (
                <span className="ml-2">({settings.stripe_account_name})</span>
              )}
            </p>
          </div>
        )}

        {settings?.stripe_validation_error && (
          <div className="mt-4 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
            <p className="text-sm text-red-700 dark:text-red-400">
              <span className="font-medium">Error:</span> {settings.stripe_validation_error}
            </p>
          </div>
        )}
      </div>

      {/* Current Keys Card */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          Current API Keys
        </h2>

        <div className="space-y-3">
          <div className="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
            <span className="text-sm text-gray-600 dark:text-gray-400">{t('platform.settings.secretKey')}</span>
            <code className="text-sm font-mono text-gray-900 dark:text-white">
              {settings?.stripe_secret_key_masked || 'Not configured'}
            </code>
          </div>
          <div className="flex justify-between items-center py-2 border-b border-gray-100 dark:border-gray-700">
            <span className="text-sm text-gray-600 dark:text-gray-400">{t('platform.settings.publishableKey')}</span>
            <code className="text-sm font-mono text-gray-900 dark:text-white">
              {settings?.stripe_publishable_key_masked || 'Not configured'}
            </code>
          </div>
          <div className="flex justify-between items-center py-2">
            <span className="text-sm text-gray-600 dark:text-gray-400">{t('platform.settings.webhookSecret')}</span>
            <code className="text-sm font-mono text-gray-900 dark:text-white">
              {settings?.stripe_webhook_secret_masked || 'Not configured'}
            </code>
          </div>
        </div>

        {settings?.has_stripe_keys && (
          <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
            <button
              onClick={handleValidate}
              disabled={validateKeysMutation.isPending}
              className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-colors disabled:opacity-50"
            >
              {validateKeysMutation.isPending ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <RefreshCw className="w-4 h-4" />
              )}
              Validate Keys
            </button>
          </div>
        )}
      </div>

      {/* Update Keys Form - Only show if keys are NOT from environment variables */}
      {settings?.stripe_keys_from_env ? (
        <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800 p-6">
          <div className="flex items-start gap-3">
            <Shield className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5" />
            <div>
              <h3 className="font-medium text-blue-800 dark:text-blue-300">
                Stripe Keys Configured via Environment Variables
              </h3>
              <p className="text-sm text-blue-700 dark:text-blue-400 mt-1">
                Your Stripe API keys are configured through environment variables (.env file).
                To update them, modify your environment configuration and restart the server.
              </p>
              <p className="text-xs text-blue-600 dark:text-blue-500 mt-2">
                Environment variables take priority over database-stored keys for security.
              </p>
            </div>
          </div>
        </div>
      ) : (
        <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Update API Keys
          </h2>
          <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
            Enter new keys to update. Leave fields empty to keep existing values.
          </p>

          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Secret Key
              </label>
              <div className="relative">
                <input
                  type={showSecretKey ? 'text' : 'password'}
                  value={secretKey}
                  onChange={(e) => setSecretKey(e.target.value)}
                  placeholder="sk_live_... or sk_test_..."
                  className="w-full px-4 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                <button
                  type="button"
                  onClick={() => setShowSecretKey(!showSecretKey)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                  {showSecretKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Publishable Key
              </label>
              <input
                type="text"
                value={publishableKey}
                onChange={(e) => setPublishableKey(e.target.value)}
                placeholder="pk_live_... or pk_test_..."
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Webhook Secret
              </label>
              <div className="relative">
                <input
                  type={showWebhookSecret ? 'text' : 'password'}
                  value={webhookSecret}
                  onChange={(e) => setWebhookSecret(e.target.value)}
                  placeholder="whsec_..."
                  className="w-full px-4 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                <button
                  type="button"
                  onClick={() => setShowWebhookSecret(!showWebhookSecret)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                  {showWebhookSecret ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>

            <div className="pt-2">
              <button
                onClick={handleSaveKeys}
                disabled={
                  updateKeysMutation.isPending || (!secretKey && !publishableKey && !webhookSecret)
                }
                className="inline-flex items-center gap-2 px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {updateKeysMutation.isPending ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Saving...
                  </>
                ) : (
                  'Save Keys'
                )}
              </button>
            </div>
          </div>

          {updateKeysMutation.isError && (
            <div className="mt-4 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
              <p className="text-sm text-red-700 dark:text-red-400">
                Failed to update keys. Please check the format and try again.
              </p>
            </div>
          )}

          {updateKeysMutation.isSuccess && (
            <div className="mt-4 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
              <p className="text-sm text-green-700 dark:text-green-400 flex items-center gap-2">
                <CheckCircle className="w-4 h-4" />
                Keys updated successfully
              </p>
            </div>
          )}
        </div>
      )}
    </div>
  );
};
const OAuthSettingsTab: React.FC = () => {
  const { data: settings, isLoading, error } = usePlatformOAuthSettings();
  const updateMutation = useUpdatePlatformOAuthSettings();

  const [allowRegistration, setAllowRegistration] = useState(false);

  // Provider states
  const [providers, setProviders] = useState<{
    [key: string]: {
      enabled: boolean;
      client_id: string;
      client_secret: string;
      team_id?: string;
      key_id?: string;
      tenant_id?: string;
    };
  }>({});

  const [showSecrets, setShowSecrets] = useState<{ [key: string]: boolean }>({});

  // Update local state when settings load
  React.useEffect(() => {
    if (settings) {
      setAllowRegistration(settings.oauth_allow_registration);
      setProviders({
        google: settings.google,
        apple: settings.apple,
        facebook: settings.facebook,
        linkedin: settings.linkedin,
        microsoft: settings.microsoft,
        twitter: settings.twitter,
        twitch: settings.twitch,
      });
    }
  }, [settings]);

  const handleSave = async () => {
    const updateData: any = {
      oauth_allow_registration: allowRegistration,
    };

    // Add all provider settings
    Object.entries(providers).forEach(([provider, config]) => {
      const prefix = `oauth_${provider}`;
      updateData[`${prefix}_enabled`] = config.enabled;
      updateData[`${prefix}_client_id`] = config.client_id;
      updateData[`${prefix}_client_secret`] = config.client_secret;

      // Apple-specific
      if (provider === 'apple') {
        updateData[`${prefix}_team_id`] = config.team_id || '';
        updateData[`${prefix}_key_id`] = config.key_id || '';
      }

      // Microsoft-specific
      if (provider === 'microsoft') {
        updateData[`${prefix}_tenant_id`] = config.tenant_id || '';
      }
    });

    await updateMutation.mutateAsync(updateData);
  };

  const updateProvider = (provider: string, field: string, value: any) => {
    setProviders((prev) => ({
      ...prev,
      [provider]: {
        ...prev[provider],
        [field]: value,
      },
    }));
  };

  const toggleShowSecret = (key: string) => {
    setShowSecrets((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
        <div className="flex items-center gap-2 text-red-700 dark:text-red-400">
          <AlertCircle className="w-5 h-5" />
          <span>Failed to load OAuth settings</span>
        </div>
      </div>
    );
  }

  const providerList = [
    {
      key: 'google',
      name: 'Google',
      hasExtra: false,
      docsUrl: 'https://console.cloud.google.com/apis/credentials',
      docsLabel: 'Google Cloud Console',
    },
    {
      key: 'apple',
      name: 'Apple',
      hasExtra: true,
      extraFields: ['team_id', 'key_id'],
      docsUrl: 'https://developer.apple.com/account/resources/identifiers/list/serviceId',
      docsLabel: 'Apple Developer Portal',
    },
    {
      key: 'facebook',
      name: 'Facebook',
      hasExtra: false,
      docsUrl: 'https://developers.facebook.com/apps/',
      docsLabel: 'Meta for Developers',
    },
    {
      key: 'linkedin',
      name: 'LinkedIn',
      hasExtra: false,
      docsUrl: 'https://www.linkedin.com/developers/apps',
      docsLabel: 'LinkedIn Developer Portal',
    },
    {
      key: 'microsoft',
      name: 'Microsoft',
      hasExtra: true,
      extraFields: ['tenant_id'],
      docsUrl: 'https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade',
      docsLabel: 'Azure App Registrations',
    },
    {
      key: 'twitter',
      name: 'X (Twitter)',
      hasExtra: false,
      docsUrl: 'https://developer.twitter.com/en/portal/dashboard',
      docsLabel: 'X Developer Portal',
    },
    {
      key: 'twitch',
      name: 'Twitch',
      hasExtra: false,
      docsUrl: 'https://dev.twitch.tv/console/apps',
      docsLabel: 'Twitch Developer Console',
    },
  ];

  return (
    <div className="space-y-6">
      {/* Global Settings */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
          <Shield className="w-5 h-5" />
          Global OAuth Settings
        </h2>

        <label className="flex items-center gap-3">
          <input
            type="checkbox"
            checked={allowRegistration}
            onChange={(e) => setAllowRegistration(e.target.checked)}
            className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
          />
          <div>
            <span className="text-sm font-medium text-gray-900 dark:text-white">
              Allow OAuth Registration
            </span>
            <p className="text-xs text-gray-500 dark:text-gray-400">
              Enable new users to register via OAuth providers on the platform
            </p>
          </div>
        </label>
      </div>

      {/* OAuth Providers */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
          <Users className="w-5 h-5" />
          OAuth Providers
        </h2>

        <div className="space-y-6">
          {providerList.map((provider) => (
            <div
              key={provider.key}
              className="border border-gray-200 dark:border-gray-700 rounded-lg p-4"
            >
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="font-medium text-gray-900 dark:text-white">{provider.name}</h3>
                  <a
                    href={provider.docsUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1 text-xs text-blue-600 dark:text-blue-400 hover:underline mt-1"
                  >
                    <ExternalLink className="w-3 h-3" />
                    {provider.docsLabel}
                  </a>
                </div>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={providers[provider.key]?.enabled || false}
                    onChange={(e) => updateProvider(provider.key, 'enabled', e.target.checked)}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="text-sm text-gray-700 dark:text-gray-300">Enabled</span>
                </label>
              </div>

              <div className="space-y-3">
                {/* Client ID */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Client ID
                  </label>
                  <input
                    type="text"
                    value={providers[provider.key]?.client_id || ''}
                    onChange={(e) => updateProvider(provider.key, 'client_id', e.target.value)}
                    placeholder="Enter client ID"
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                  />
                </div>

                {/* Client Secret */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Client Secret
                  </label>
                  <div className="relative">
                    <input
                      type={showSecrets[`${provider.key}_secret`] ? 'text' : 'password'}
                      value={providers[provider.key]?.client_secret || ''}
                      onChange={(e) =>
                        updateProvider(provider.key, 'client_secret', e.target.value)
                      }
                      placeholder="Enter client secret"
                      className="w-full px-3 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                    />
                    <button
                      type="button"
                      onClick={() => toggleShowSecret(`${provider.key}_secret`)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      {showSecrets[`${provider.key}_secret`] ? (
                        <EyeOff className="w-4 h-4" />
                      ) : (
                        <Eye className="w-4 h-4" />
                      )}
                    </button>
                  </div>
                </div>

                {/* Apple-specific fields */}
                {provider.key === 'apple' && (
                  <>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        Team ID
                      </label>
                      <input
                        type="text"
                        value={providers[provider.key]?.team_id || ''}
                        onChange={(e) => updateProvider(provider.key, 'team_id', e.target.value)}
                        placeholder="Enter Apple Team ID"
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        Key ID
                      </label>
                      <input
                        type="text"
                        value={providers[provider.key]?.key_id || ''}
                        onChange={(e) => updateProvider(provider.key, 'key_id', e.target.value)}
                        placeholder="Enter Apple Key ID"
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                      />
                    </div>
                  </>
                )}

                {/* Microsoft-specific field */}
                {provider.key === 'microsoft' && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Tenant ID <span className="text-gray-400">(optional, default: common)</span>
                    </label>
                    <input
                      type="text"
                      value={providers[provider.key]?.tenant_id || ''}
                      onChange={(e) => updateProvider(provider.key, 'tenant_id', e.target.value)}
                      placeholder="common"
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                    />
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>

        {/* Save Button */}
        <div className="mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={handleSave}
            disabled={updateMutation.isPending}
            className="inline-flex items-center gap-2 px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {updateMutation.isPending ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Lock className="w-4 h-4" />
                Save OAuth Settings
              </>
            )}
          </button>
        </div>

        {updateMutation.isError && (
          <div className="mt-4 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
            <p className="text-sm text-red-700 dark:text-red-400">
              Failed to update OAuth settings. Please try again.
            </p>
          </div>
        )}

        {updateMutation.isSuccess && (
          <div className="mt-4 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
            <p className="text-sm text-green-700 dark:text-green-400 flex items-center gap-2">
              <CheckCircle className="w-4 h-4" />
              OAuth settings updated successfully
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default PlatformSettings;
