/**
 * Settings component - Configure plugin defaults and behavior.
 *
 * Implements US9: Settings Configuration page.
 * Implements US10: Automatic Cleanup configuration.
 *
 * @package GetMD
 * @since   1.0.0
 */

import { useState, useEffect } from 'react';
import { ChevronDown } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Switch } from './ui/switch';
import { RadioGroup, RadioGroupItem } from './ui/radio-group';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from './ui/collapsible';
import { DatabaseSettings } from './DatabaseSettings';
import { Toast } from './ui/toast';
import { getAPI } from '../lib/api';

/**
 * Render the Settings UI for configuring default export structure and automatic cleanup.
 *
 * Renders controls to choose the default file structure (single or multiple files), enable or disable automatic cleanup, select a retention period when cleanup is enabled, and save the current settings. Settings are persisted to WordPress user meta via the REST API.
 *
 * @returns The settings panel as a JSX element
 */
export function Settings() {
  const { i18n } = window.summixGetmdData || {};

  // 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);

  // Default Export Settings
  const [defaultFileStructure, setDefaultFileStructure] = useState<'single' | 'multiple'>('multiple');

  // Cleanup Settings
  const [autoCleanup, setAutoCleanup] = useState(false);
  const [retentionDays, setRetentionDays] = useState<'7' | '14' | '30' | '60' | '90'>('30');

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

    const loadSettings = async () => {
      setIsLoading(true);
      try {
        // Load user settings
        const userSettings = await getAPI().getSettings();

        if (!abortController.signal.aborted) {
          // User settings
          setDefaultFileStructure(userSettings.defaultFileStructure);
          setAutoCleanup(userSettings.autoCleanup);
          setRetentionDays(userSettings.retentionDays);
        }
      } catch (error) {
        if (!abortController.signal.aborted) {
          console.error('Failed to load settings:', error);
          // Set safe defaults
          setDefaultFileStructure('multiple');
          setAutoCleanup(false);
          setRetentionDays('30');
          setToast({
            message: i18n?.settingsLoadFailed || "Loaded defaults—couldn't reach saved settings.",
            variant: 'destructive',
          });
        }
      } finally {
        if (!abortController.signal.aborted) {
          setIsLoading(false);
        }
      }
    };

    loadSettings();

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

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

    try {
      // Save user settings
      const userSettingsResponse = await getAPI().saveSettings({
        defaultFileStructure,
        autoCleanup,
        retentionDays,
      });

      // Sync state with server-confirmed settings
      setDefaultFileStructure(userSettingsResponse.settings.defaultFileStructure as 'single' | 'multiple');
      setAutoCleanup(Boolean(userSettingsResponse.settings.autoCleanup));
      setRetentionDays(String(userSettingsResponse.settings.retentionDays) as '7' | '14' | '30' | '60' | '90');

      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>
    );
  }

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

      {/* Advanced Section (Database Health) */}
      <Collapsible defaultOpen={false}>
        <Card>
          <CollapsibleTrigger asChild>
            <CardHeader className="smx-cursor-pointer hover:smx-bg-muted/50 smx-transition-colors smx-select-none">
              <div className="smx-flex smx-items-center smx-justify-between">
                <div>
                  <CardTitle className="smx-text-base">{i18n?.advancedTitle || 'Advanced'}</CardTitle>
                  <CardDescription>{i18n?.advancedDesc || 'Database health and tools'}</CardDescription>
                </div>
                <ChevronDown className="smx-h-4 smx-w-4 smx-text-muted-foreground smx-transition-transform [[data-state=open]_&]:smx-rotate-180" />
              </div>
            </CardHeader>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <CardContent className="smx-pt-0">
              <DatabaseSettings inline />
            </CardContent>
          </CollapsibleContent>
        </Card>
      </Collapsible>

      {/* Default Export Settings */}
      <Card>
        <CardHeader>
          <CardTitle>{i18n?.exportDefaultsTitle || 'Export Defaults'}</CardTitle>
          <CardDescription>
            {i18n?.exportDefaultsDesc || 'These settings apply to new exports.'}
          </CardDescription>
        </CardHeader>
        <CardContent className="smx-space-y-4">
          {/* Default File Structure */}
          <div className="smx-space-y-2">
            <label className="smx-text-sm smx-font-medium">
              {i18n?.defaultFileStructure || 'Default file structure'}
            </label>
            <RadioGroup
              value={defaultFileStructure}
              onValueChange={(value) => setDefaultFileStructure(value as 'single' | 'multiple')}
              disabled={isLoading}
            >
              <div className="smx-flex smx-items-center smx-space-x-2">
                <RadioGroupItem value="multiple" id="default-multiple" />
                <label htmlFor="default-multiple" className="smx-text-sm smx-cursor-pointer">
                  {i18n?.separateFilesOption || 'Separate files (one per item)'}
                </label>
              </div>
              <div className="smx-flex smx-items-center smx-space-x-2">
                <RadioGroupItem value="single" id="default-single" />
                <label htmlFor="default-single" className="smx-text-sm smx-cursor-pointer">
                  {i18n?.singleFileOption || 'Single file (all content combined)'}
                </label>
              </div>
            </RadioGroup>
          </div>
        </CardContent>
      </Card>

      {/* Automatic Cleanup Settings */}
      <Card>
        <CardHeader>
          <CardTitle>{i18n?.autoCleanupTitle || 'Auto-cleanup'}</CardTitle>
          <CardDescription>
            {i18n?.autoCleanupDesc || 'Free up space by removing old exports.'}
          </CardDescription>
        </CardHeader>
        <CardContent className="smx-space-y-4">
          {/* Enable Auto Cleanup */}
          <div className="smx-flex smx-items-center smx-justify-between">
            <div className="smx-space-y-0.5">
              <label htmlFor="auto-cleanup-toggle" className="smx-text-sm smx-font-medium">
                {i18n?.enableAutoCleanup || 'Enable auto-cleanup'}
              </label>
            </div>
            <Switch
              id="auto-cleanup-toggle"
              checked={autoCleanup}
              onCheckedChange={setAutoCleanup}
              disabled={isLoading}
            />
          </div>

          {/* Retention Period */}
          {autoCleanup && (
            <div className="smx-space-y-2">
              <label className="smx-text-sm smx-font-medium">
                {i18n?.keepExportsFor || 'Keep exports for'}
              </label>
              <Select
                value={retentionDays}
                onValueChange={(value) => setRetentionDays(value as '7' | '14' | '30' | '60' | '90')}
                disabled={isLoading}
              >
                <SelectTrigger className="smx-w-full">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="7">{i18n?.oneWeek || '1 week'}</SelectItem>
                  <SelectItem value="14">{i18n?.twoWeeks || '2 weeks'}</SelectItem>
                  <SelectItem value="30">{i18n?.oneMonth || '1 month'}</SelectItem>
                  <SelectItem value="60">{i18n?.twoMonths || '2 months'}</SelectItem>
                  <SelectItem value="90">{i18n?.threeMonths || '3 months'}</SelectItem>
                </SelectContent>
              </Select>
              <p className="smx-text-sm smx-text-muted-foreground">
                {i18n?.olderExportsDeleted || 'Older exports will be deleted automatically.'}
              </p>
            </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>

      {/* Info Message */}
      <Card className="smx-bg-muted">
        <CardContent className="smx-pt-6">
          <p className="smx-text-sm smx-text-muted-foreground">
            {i18n?.settingsNote || 'Your settings. Other admins have their own.'}
          </p>
        </CardContent>
      </Card>
    </div>
  );
}