import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Save, Loader2, Sparkles } from 'lucide-react';
import { AIProviderSettings } from './AIProviderSettings';
import { AIFeatures } from './AIFeatures';
import { AIParameters } from './AIParameters';
import { getAllConfigurations, updateConfiguration, AdminConfiguration } from '@/services/adminApi';
import { toast } from 'sonner';

interface AIConfigData {
  aiEnabled: boolean;
  aiRemarkGeneration: boolean;
  maxRemarkChars: number;
}

export function AIConfig() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [config, setConfig] = useState<AIConfigData>({
    aiEnabled: true,
    aiRemarkGeneration: true,
    maxRemarkChars: 2000
  });

  useEffect(() => {
    loadConfigurations();
  }, []);

  const loadConfigurations = async () => {
    try {
      setLoading(true);
      const configs = await getAllConfigurations('AI_CONFIGURATION');
      
      // Map configuration values to state
      const configMap: Record<string, string> = {};
      configs.forEach((c: AdminConfiguration) => {
        configMap[c.configKey] = c.configValue;
      });

      setConfig({
        aiEnabled: configMap['AI_ENABLED'] === 'true',
        aiRemarkGeneration: configMap['AI_REMARK_GENERATION_ENABLED'] === 'true',
        maxRemarkChars: parseInt(configMap['AI_MAX_REMARK_LENGTH'] || '2000')
      });
    } catch (error: any) {
      console.error('Failed to load AI configurations:', error);
      toast.error('Failed to load AI configurations');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      
      // Save all configurations
      await Promise.all([
        updateConfiguration('AI_ENABLED', config.aiEnabled.toString()),
        updateConfiguration('AI_REMARK_GENERATION_ENABLED', config.aiRemarkGeneration.toString()),
        updateConfiguration('AI_MAX_REMARK_LENGTH', config.maxRemarkChars.toString())
      ]);

      toast.success('AI configuration saved successfully');
      
      // Reload to get updated values
      await loadConfigurations();
    } catch (error: any) {
      console.error('Failed to save AI configuration:', error);
      toast.error(error.response?.data?.error || 'Failed to save AI configuration');
    } finally {
      setSaving(false);
    }
  };

  const updateConfig = (updates: Partial<AIConfigData>) => {
    setConfig(prev => ({ ...prev, ...updates }));
  };

  if (loading) {
    return (
      <Card className="shadow-lg border-0 rounded-md">
        <CardContent className="p-12 text-center">
          <Loader2 className="w-8 h-8 animate-spin text-re-green mx-auto mb-4" />
          <p className="text-sm text-gray-600">Loading AI configuration...</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="shadow-lg border-0 rounded-md">
      <CardHeader className="pb-4">
        <div className="flex items-center gap-3">
          <div className="p-3 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md">
            <Sparkles className="h-5 w-5 text-white" />
          </div>
          <div>
            <CardTitle className="text-lg font-semibold text-gray-900">AI Features Configuration</CardTitle>
            <CardDescription className="text-sm text-gray-600">
              Configure Vertex AI Gemini settings and enable/disable AI-powered features
            </CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        <AIProviderSettings
          aiEnabled={config.aiEnabled}
          onAiEnabledChange={(enabled) => updateConfig({ aiEnabled: enabled })}
        />

        <Separator />

        <AIFeatures
          aiRemarkGeneration={config.aiRemarkGeneration}
          onRemarkGenerationChange={(enabled) => updateConfig({ aiRemarkGeneration: enabled })}
        />

        <Separator />

        <AIParameters
          maxRemarkChars={config.maxRemarkChars}
          onMaxRemarkCharsChange={(chars) => updateConfig({ maxRemarkChars: chars })}
        />

        <div className="flex justify-end pt-4">
          <Button 
            onClick={handleSave} 
            disabled={saving}
            className="bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {saving ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Save className="w-4 h-4 mr-2" />
                Save AI Configuration
              </>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
