/**
 * AI Discovery component - Configure AI and LLM-related features.
 *
 * @package GetMD
 * @since   1.0.0
 */

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Switch } from './ui/switch';
import { Toast } from './ui/toast';
import { getAPI } from '../lib/api';

/**
 * Render the AI Discovery UI for configuring AI and LLM-related features.
 *
 * Currently includes the Public Markdown View feature which enables visitors
 * to view posts as Markdown by adding ?view=md to the URL - useful for AI agents
 * and LLMs that need to consume content in a clean format.
 *
 * @returns The AI Discovery panel as a JSX element
 */
export function AIDiscovery() {
  const { i18n, canManageOptions } = window.summixGetmdData || {};
  const isAdmin = Boolean(canManageOptions);

  // Loading and notification states
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [toast, setToast] = useState<{ message: string; variant: 'default' | 'destructive' } | null>(null);

  // Global Settings (admin only)
  const [frontendViewEnabled, setFrontendViewEnabled] = useState(false);

  // Load settings on mount
  useEffect(() => {
    const abortController = new AbortController();

    const loadSettings = async () => {
      setIsLoading(true);
      try {
        if (isAdmin && !abortController.signal.aborted) {
          const globalSettings = await getAPI().getGlobalSettings();
          if (!abortController.signal.aborted) {
            setFrontendViewEnabled(globalSettings.frontendViewEnabled);
          }
        }
      } catch (error) {
        if (!abortController.signal.aborted) {
          console.error('Failed to load global settings:', error);
          setFrontendViewEnabled(false);
          setToast({
            message: i18n?.settingsLoadFailed || "Loaded defaults—couldn't reach saved settings.",
            variant: 'destructive',
          });
        }
      } finally {
        if (!abortController.signal.aborted) {
          setIsLoading(false);
        }
      }
    };

    loadSettings();

    return () => {
      abortController.abort();
    };
  }, [isAdmin]);

  const handleSave = async () => {
    setIsSaving(true);
    setToast(null);

    try {
      const globalSettingsResponse = await getAPI().saveGlobalSettings({
        frontendViewEnabled,
      });
      setFrontendViewEnabled(globalSettingsResponse.settings.frontendViewEnabled);

      setToast({
        message: i18n?.settingsSaved || 'Settings saved',
        variant: 'default',
      });
    } catch (error) {
      console.error('Failed to save settings:', error);
      setToast({
        message: error instanceof Error ? error.message : (i18n?.settingsSaveFailed || "Couldn't save. Try again?"),
        variant: 'destructive',
      });
    } finally {
      setIsSaving(false);
    }
  };

  // Show loading UI while fetching settings
  if (isLoading) {
    return (
      <div className="smx-flex smx-items-center smx-justify-center smx-py-12">
        <div className="smx-text-center">
          <div className="smx-inline-block smx-h-8 smx-w-8 smx-animate-spin smx-rounded-full smx-border-4 smx-border-solid smx-border-current smx-border-r-transparent smx-align-[-0.125em] smx-motion-reduce:animate-[spin_1.5s_linear_infinite]" role="status">
            <span className="smx-sr-only">{i18n?.loading || 'Loading...'}</span>
          </div>
          <p className="smx-mt-4 smx-text-sm smx-text-muted-foreground">{i18n?.loading || 'Loading...'}</p>
        </div>
      </div>
    );
  }

  // Non-admin users see a message
  if (!isAdmin) {
    return (
      <div className="smx-space-y-6">
        <Card className="smx-bg-muted">
          <CardContent className="smx-pt-6">
            <p className="smx-text-sm smx-text-muted-foreground">
              {i18n?.adminOnlyFeatures || 'These features are only available to administrators.'}
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="smx-space-y-6">
      {/* Toast Notification */}
      {toast && (
        <Toast
          message={toast.message}
          variant={toast.variant}
          onClose={() => setToast(null)}
        />
      )}

      {/* Public Markdown View */}
      <Card>
        <CardHeader>
          <CardTitle>{i18n?.publicViewTitle || 'Public Markdown View'}</CardTitle>
          <CardDescription>
            {i18n?.publicViewDesc || 'Let visitors view any post as Markdown by adding ?view=md to the URL.'}
          </CardDescription>
        </CardHeader>
        <CardContent className="smx-space-y-4">
          {/* Enable Frontend View Toggle */}
          <div className="smx-flex smx-items-center smx-justify-between">
            <div className="smx-space-y-0.5">
              <label htmlFor="frontend-view-toggle" className="smx-text-sm smx-font-medium">
                {i18n?.enablePublicView || 'Enable public view'}
              </label>
              <p className="smx-text-sm smx-text-muted-foreground">
                {i18n?.publicViewDesc || 'Let visitors view any post as Markdown by adding ?view=md to the URL.'}
              </p>
            </div>
            <Switch
              id="frontend-view-toggle"
              checked={frontendViewEnabled}
              onCheckedChange={setFrontendViewEnabled}
              disabled={isLoading}
            />
          </div>

          {/* Example URL */}
          {frontendViewEnabled && (
            <div className="smx-rounded-md smx-bg-muted smx-p-4">
              <p className="smx-text-xs smx-font-medium smx-text-muted-foreground smx-mb-2">{i18n?.tryIt || 'Try it:'}</p>
              <code className="smx-text-xs smx-text-foreground">
                {window.location.origin}/your-post-slug/?view=md
              </code>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Save Button */}
      <div className="smx-flex smx-justify-end">
        <Button onClick={handleSave} disabled={isSaving || isLoading} aria-busy={isSaving}>
          {isSaving ? (
            <>
              <div className="smx-mr-2 smx-h-4 smx-w-4 smx-border-2 smx-border-white smx-border-t-transparent smx-rounded-full smx-animate-spin" />
              {i18n?.saving || 'Saving...'}
            </>
          ) : (
            i18n?.save || 'Save'
          )}
        </Button>
      </div>
    </div>
  );
}
