import { useState, useEffect, useRef } from 'react';
import { useUser } from '@/features/auth/hooks/useUser';
import { usersApi } from '@/services/api/users';
import { UserSettings } from '../types/settings';
import { SettingsTabs } from '../components/SettingsTabs';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import toast from '@/utils/toast';
import { settingsSchema } from '../schemas/settingsSchema';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';
import { Save, Shield, Sliders } from 'lucide-react';

export function SettingsPage() {
  const { data: user } = useUser();
  const [settings, setSettings] = useState<UserSettings | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [queryError, setQueryError] = useState<Error | null>(null);
  const [mutationError, setMutationError] = useState<Error | null>(null);
  const [retryCount, setRetryCount] = useState(0);
  const lastMutationRef = useRef<(() => Promise<void>) | null>(null);

  const loadSettings = async () => {
    if (!user?.id) {
      setQueryError(new Error('Authentication required for system access.'));
      setIsLoading(false);
      return;
    }
    try {
      setIsLoading(true);
      setQueryError(null);
      const userSettings = await usersApi.getSettings(user.id);
      setSettings(userSettings);
    } catch (err) {
      setQueryError(new Error(err instanceof Error ? err.message : 'Failed to load system configuration.'));
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => { loadSettings(); }, [user?.id]);

  const handleSave = async () => {
    if (!user?.id || !settings) return;
    const validationResult = settingsSchema.safeParse(settings);
    if (!validationResult.success) {
      toast.error(`Configuration Error: ${validationResult.error.errors.map(e => e.message).join(', ')}`);
      return;
    }

    const performMutation = async () => {
      await usersApi.updateSettings(user.id, settings);
      toast.success('System configuration updated.');
      setMutationError(null);
      setRetryCount(0);
      lastMutationRef.current = null;
    };

    lastMutationRef.current = performMutation;
    setIsSaving(true);
    try { await performMutation(); }
    catch (err) { setMutationError(new Error(err instanceof Error ? err.message : 'Save failed.')); }
    finally { setIsSaving(false); }
  };

  const handleRetry = async () => {
    if (!lastMutationRef.current || retryCount >= 3) return;
    setRetryCount(prev => prev + 1);
    setIsSaving(true);
    try { await lastMutationRef.current(); } catch (error) { } finally { setIsSaving(false); }
  };

  if (isLoading) return <div className="flex items-center justify-center min-h-screen"><LoadingSpinner /></div>;

  if (queryError && !settings) {
    return (
      <div className="container mx-auto px-4 py-8 flex items-center justify-center min-h-[600px]">
        <ErrorDisplay error={queryError} variant="card" severity="error" onRetry={loadSettings} />
      </div>
    );
  }

  if (!settings) return <div className="flex items-center justify-center min-h-screen"><LoadingSpinner /></div>;

  return (
    <div className="container mx-auto px-4 py-8 pb-24 max-w-5xl">
      {mutationError && (
        <ErrorDisplay
          error={mutationError}
          variant="banner"
          severity="error"
          onRetry={retryCount < 3 ? handleRetry : undefined}
          onDismiss={() => { setMutationError(null); setRetryCount(0); lastMutationRef.current = null; }}
        />
      )}

      <div className="mb-8 flex items-end justify-between">
        <div>
          <h1 className="text-4xl font-display font-bold text-white mb-2">System Config</h1>
          <p className="text-muted-foreground flex items-center gap-2">
            <Shield className="w-4 h-4 text-primary" />
            Manage your neural link and interface preferences.
          </p>
        </div>
        <Button onClick={handleSave} disabled={isSaving} className="shadow-glow-cyan min-w-[140px]" size="lg">
          {isSaving ? <><LoadingSpinner className="mr-2 h-4 w-4" /> Saving...</> : <><Save className="mr-2 h-4 w-4" /> Save Config</>}
        </Button>
      </div>

      <Card variant="glass" className="overflow-hidden border-white/5 bg-black/40 backdrop-blur-xl">
        <div className="p-6 border-b border-white/5 bg-black/20 flex items-center gap-2">
          <Sliders className="w-5 h-5 text-primary" />
          <h2 className="font-bold text-lg">Global Preferences</h2>
        </div>
        <div className="p-6">
          <SettingsTabs settings={settings} onChange={setSettings} />
        </div>
      </Card>
    </div>
  );
}
