import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Slider } from '@/components/ui/slider';
import { 
  Settings, 
  Save, 
  RotateCcw, 
  AlertCircle, 
  CheckCircle,
  Clock,
  FileText,
  Bell,
  Sparkles,
  Share2,
  Loader2
} from 'lucide-react';
import { getAllConfigurations, updateConfiguration, resetConfiguration, AdminConfiguration } from '@/services/adminApi';

interface ConfigurationManagerProps {
  onConfigUpdate?: () => void;
}

export function ConfigurationManager({ onConfigUpdate }: ConfigurationManagerProps) {
  const [configurations, setConfigurations] = useState<AdminConfiguration[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [editedValues, setEditedValues] = useState<Record<string, string>>({});
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

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

  const loadConfigurations = async () => {
    try {
      setLoading(true);
      setError(null);
      const configs = await getAllConfigurations();
      setConfigurations(configs);
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to load configurations');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async (config: AdminConfiguration) => {
    try {
      setSaving(config.configKey);
      setError(null);
      
      const newValue = editedValues[config.configKey] ?? config.configValue;
      
      // Validate
      if (config.validationRules) {
        const numValue = parseFloat(newValue);
        if (config.valueType === 'NUMBER') {
          if (config.validationRules.min !== undefined && numValue < config.validationRules.min) {
            throw new Error(`Value must be at least ${config.validationRules.min}`);
          }
          if (config.validationRules.max !== undefined && numValue > config.validationRules.max) {
            throw new Error(`Value must be at most ${config.validationRules.max}`);
          }
        }
      }
      
      await updateConfiguration(config.configKey, newValue);
      
      // Update local state
      setConfigurations(prev => 
        prev.map(c => 
          c.configKey === config.configKey 
            ? { ...c, configValue: newValue }
            : c
        )
      );
      
      // Clear edited value
      setEditedValues(prev => {
        const newValues = { ...prev };
        delete newValues[config.configKey];
        return newValues;
      });
      
      setSuccessMessage(`${config.displayName} updated successfully`);
      setTimeout(() => setSuccessMessage(null), 3000);
      
      if (onConfigUpdate) {
        onConfigUpdate();
      }
    } catch (err: any) {
      setError(err.message || err.response?.data?.error || 'Failed to save configuration');
    } finally {
      setSaving(null);
    }
  };

  const handleReset = async (config: AdminConfiguration) => {
    if (!confirm(`Reset "${config.displayName}" to default value?`)) {
      return;
    }
    
    try {
      setSaving(config.configKey);
      setError(null);
      
      await resetConfiguration(config.configKey);
      
      // Update local state
      setConfigurations(prev => 
        prev.map(c => 
          c.configKey === config.configKey 
            ? { ...c, configValue: c.defaultValue || '' }
            : c
        )
      );
      
      // Clear edited value
      setEditedValues(prev => {
        const newValues = { ...prev };
        delete newValues[config.configKey];
        return newValues;
      });
      
      setSuccessMessage(`${config.displayName} reset to default`);
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to reset configuration');
    } finally {
      setSaving(null);
    }
  };

  const handleValueChange = (configKey: string, value: string) => {
    setEditedValues(prev => ({ ...prev, [configKey]: value }));
  };

  const getCurrentValue = (config: AdminConfiguration): string => {
    return editedValues[config.configKey] ?? config.configValue;
  };

  const hasChanges = (config: AdminConfiguration): boolean => {
    return editedValues[config.configKey] !== undefined && 
           editedValues[config.configKey] !== config.configValue;
  };

  const renderConfigInput = (config: AdminConfiguration) => {
    const currentValue = getCurrentValue(config);
    const isSaving = saving === config.configKey;

    if (!config.isEditable) {
      return (
        <div className="p-3 bg-slate-100 border border-slate-200 rounded-md">
          <p className="text-sm text-slate-700 font-mono">{config.configValue}</p>
          <p className="text-xs text-slate-500 mt-1.5 flex items-center gap-1">
            <AlertCircle className="w-3 h-3" />
            This setting cannot be modified
          </p>
        </div>
      );
    }

    switch (config.uiComponent || config.valueType.toLowerCase()) {
      case 'toggle':
        return (
          <div className="flex items-center justify-between p-3 bg-slate-50 border border-slate-200 rounded-md hover:bg-slate-100 transition-colors">
            <div className="flex items-center gap-2">
              <div className={`w-2 h-2 rounded-full ${currentValue === 'true' ? 'bg-green-500' : 'bg-slate-400'}`}></div>
              <span className={`text-sm font-medium ${currentValue === 'true' ? 'text-green-700' : 'text-slate-600'}`}>
                {currentValue === 'true' ? 'Enabled' : 'Disabled'}
              </span>
            </div>
            <Switch
              checked={currentValue === 'true'}
              onCheckedChange={(checked) => 
                handleValueChange(config.configKey, checked ? 'true' : 'false')
              }
              disabled={isSaving}
            />
          </div>
        );

      case 'slider':
        const numValue = parseInt(currentValue) || 0;
        const min = config.validationRules?.min || 0;
        const max = config.validationRules?.max || 100;
        return (
          <div className="space-y-3 p-3 bg-slate-50 border border-slate-200 rounded-md">
            <div className="flex items-center justify-between">
              <span className="text-lg font-semibold text-slate-900">{numValue}%</span>
              <span className="text-xs text-slate-500 bg-slate-100 px-2 py-1 rounded-sm border border-slate-200">Range: {min}-{max}</span>
            </div>
            <Slider
              value={[numValue]}
              min={min}
              max={max}
              step={1}
              onValueChange={([value]) => {
                if (value !== undefined) {
                  handleValueChange(config.configKey, value.toString());
                }
              }}
              disabled={isSaving}
              className="w-full"
            />
          </div>
        );

      case 'number':
        return (
          <Input
            type="number"
            value={currentValue}
            onChange={(e) => handleValueChange(config.configKey, e.target.value)}
            disabled={isSaving}
            min={config.validationRules?.min}
            max={config.validationRules?.max}
            className="font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"
          />
        );

      case 'text':
      case 'input':
      default:
        return (
          <Input
            type="text"
            value={currentValue}
            onChange={(e) => handleValueChange(config.configKey, e.target.value)}
            disabled={isSaving}
            className="font-mono border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 rounded-md transition-all shadow-sm"
          />
        );
    }
  };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'TAT_SETTINGS':
        return <Clock className="w-5 h-5" />;
      case 'DOCUMENT_POLICY':
        return <FileText className="w-5 h-5" />;
      case 'NOTIFICATION_RULES':
        return <Bell className="w-5 h-5" />;
      case 'AI_CONFIGURATION':
        return <Sparkles className="w-5 h-5" />;
      case 'WORKFLOW_SHARING':
        return <Share2 className="w-5 h-5" />;
      default:
        return <Settings className="w-5 h-5" />;
    }
  };

  // Filter out dashboard layout category and specific config keys
  const excludedCategories = ['DASHBOARD_LAYOUT'];
  const excludedConfigKeys = ['ALLOW_EXTERNAL_SHARING', 'NOTIFICATION_BATCH_DELAY_MS', 'AI_REMARK_MAX_CHARACTERS'];
  const filteredConfigurations = configurations.filter(
    config => !excludedCategories.includes(config.configCategory) && 
              !excludedConfigKeys.includes(config.configKey)
  );

  const groupedConfigs = filteredConfigurations.reduce((acc, config) => {
    if (!acc[config.configCategory]) {
      acc[config.configCategory] = [];
    }
    acc[config.configCategory]!.push(config);
    return acc;
  }, {} as Record<string, AdminConfiguration[]>);

  // Sort configs within each category by sortOrder
  Object.keys(groupedConfigs).forEach(category => {
    const categoryConfigs = groupedConfigs[category];
    if (categoryConfigs) {
      categoryConfigs.sort((a, b) => a.sortOrder - b.sortOrder);
    }
  });

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

  if (filteredConfigurations.length === 0) {
    return (
      <Card className="shadow-lg border-0 rounded-md">
        <CardContent className="p-12 text-center">
          <div className="p-4 bg-slate-100 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4">
            <Settings className="w-10 h-10 text-slate-400" />
          </div>
          <p className="text-slate-700 font-medium text-lg">No configurations found</p>
          <p className="text-sm text-slate-500 mt-2 max-w-md mx-auto">
            System configurations will appear here once they are initialized
          </p>
        </CardContent>
      </Card>
    );
  }

  const categories = Object.keys(groupedConfigs);

  return (
    <div className="space-y-6">
      {/* Success Message */}
      {successMessage && (
        <div className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300">
          <div className="p-1.5 bg-green-500 rounded-md">
            <CheckCircle className="w-4 h-4 text-white shrink-0" />
          </div>
          <p className="text-sm font-medium text-green-900">{successMessage}</p>
        </div>
      )}

      {/* Error Message */}
      {error && (
        <div className="p-4 bg-gradient-to-r from-red-50 to-rose-50 border border-red-300 rounded-md shadow-sm flex items-center gap-3 animate-in fade-in slide-in-from-top-2 duration-300">
          <div className="p-1.5 bg-red-500 rounded-md">
            <AlertCircle className="w-4 h-4 text-white shrink-0" />
          </div>
          <p className="text-sm font-medium text-red-900">{error}</p>
          <Button 
            size="sm" 
            variant="ghost" 
            onClick={() => setError(null)}
            className="ml-auto hover:bg-red-100"
          >
            Dismiss
          </Button>
        </div>
      )}

      {/* Configurations by Category */}
      <Tabs defaultValue={categories[0]} className="w-full">
        <TabsList className="flex flex-wrap w-full bg-slate-100/80 backdrop-blur-sm p-1 gap-1 rounded-md h-auto border border-slate-200 shadow-sm">
          {categories.map(category => (
            <TabsTrigger 
              key={category} 
              value={category} 
              className="flex-1 min-w-[120px] text-[10px] xs:text-xs sm:text-sm font-medium py-2 sm:py-2.5 px-2 sm:px-3 rounded-sm data-[state=active]:bg-white data-[state=active]:shadow-sm data-[state=active]:text-slate-900 transition-all"
            >
              <span className="truncate block">
                {category.replace(/_/g, ' ')}
              </span>
            </TabsTrigger>
          ))}
        </TabsList>

        {categories.map(category => (
          <TabsContent key={category} value={category} className="space-y-4 mt-6">
            <Card className="shadow-lg border-0 rounded-md">
              <CardHeader className="pb-4 border-b border-slate-100">
                <div className="flex items-center gap-3">
                  <div className="p-2.5 bg-gradient-to-br from-slate-600 to-slate-700 rounded-md shadow-md">
                    <div className="text-white">
                    {getCategoryIcon(category)}
                    </div>
                  </div>
                  <div>
                    <CardTitle className="text-lg font-semibold text-slate-900">
                      {category.replace(/_/g, ' ')}
                    </CardTitle>
                    <CardDescription className="text-sm">
                      {groupedConfigs[category]?.length || 0} setting{(groupedConfigs[category]?.length || 0) !== 1 ? 's' : ''} available
                    </CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                {groupedConfigs[category]?.map(config => (
                  <div key={config.configKey} className="space-y-3 pb-6 border-b border-slate-100 last:border-b-0 last:pb-0 hover:bg-slate-50/50 -mx-6 px-6 py-4 rounded-md transition-colors">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1.5 flex-wrap">
                          <Label className="text-sm font-semibold text-slate-900">
                            {config.displayName}
                          </Label>
                          {hasChanges(config) && (
                            <Badge variant="outline" className="text-xs bg-gradient-to-r from-yellow-50 to-amber-50 text-yellow-800 border-yellow-400 font-medium shadow-sm">
                              Modified
                            </Badge>
                          )}
                          {config.requiresRestart && (
                            <Badge variant="outline" className="text-xs bg-gradient-to-r from-orange-50 to-red-50 text-orange-800 border-orange-400 font-medium shadow-sm">
                              Requires Restart
                            </Badge>
                          )}
                        </div>
                        {config.description && (
                          <p className="text-xs text-slate-600 mt-1 leading-relaxed">{config.description}</p>
                        )}
                        {config.defaultValue && (
                          <p className="text-xs text-slate-500 mt-2">
                            Default: <code className="px-2 py-0.5 bg-slate-100 text-slate-700 rounded-sm font-mono text-xs border border-slate-200">{config.defaultValue}</code>
                          </p>
                        )}
                      </div>
                    </div>

                    {renderConfigInput(config)}

                    {config.isEditable && (
                      <div className="flex items-center gap-2 flex-wrap">
                        <Button
                          size="sm"
                          onClick={() => handleSave(config)}
                          disabled={!hasChanges(config) || saving === config.configKey}
                          className="gap-2 bg-re-green hover:bg-re-green/90 text-white shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          {saving === config.configKey ? (
                            <>
                              <Loader2 className="w-4 h-4 animate-spin" />
                              Saving...
                            </>
                          ) : (
                            <>
                              <Save className="w-4 h-4" />
                              Save Changes
                            </>
                          )}
                        </Button>
                        {config.defaultValue && (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleReset(config)}
                            disabled={saving === config.configKey}
                            className="gap-2 border-slate-300 hover:bg-slate-50 hover:border-slate-400 shadow-sm"
                          >
                            <RotateCcw className="w-4 h-4" />
                            Reset to Default
                          </Button>
                        )}
                      </div>
                    )}
                  </div>
                ))}
              </CardContent>
            </Card>
          </TabsContent>
        ))}
      </Tabs>
    </div>
  );
}

