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, FileText } from 'lucide-react';
import { DocumentUploadSettings } from './DocumentUploadSettings';
import { AllowedFileTypes } from './AllowedFileTypes';
import { getAllConfigurations, updateConfiguration, AdminConfiguration } from '@/services/adminApi';
import { toast } from 'sonner';

interface DocumentConfigData {
  maxFileSizeMB: number;
  retentionDays: number;
  allowedFileTypes: string;
}

export function DocumentConfig() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [config, setConfig] = useState<DocumentConfigData>({
    maxFileSizeMB: 10,
    retentionDays: 365,
    allowedFileTypes: 'pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif'
  });

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

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

      setConfig({
        maxFileSizeMB: parseInt(configMap['MAX_FILE_SIZE_MB'] || '10'),
        retentionDays: parseInt(configMap['DOCUMENT_RETENTION_DAYS'] || '365'),
        allowedFileTypes: configMap['ALLOWED_FILE_TYPES'] || 'pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif'
      });
    } catch (error: any) {
      console.error('Failed to load document configurations:', error);
      toast.error('Failed to load document configurations');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      
      // Save all configurations
      await Promise.all([
        updateConfiguration('MAX_FILE_SIZE_MB', config.maxFileSizeMB.toString()),
        updateConfiguration('DOCUMENT_RETENTION_DAYS', config.retentionDays.toString()),
        updateConfiguration('ALLOWED_FILE_TYPES', config.allowedFileTypes)
      ]);

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

  const updateConfig = (updates: Partial<DocumentConfigData>) => {
    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 document policy 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">
            <FileText className="h-5 w-5 text-white" />
          </div>
          <div>
            <CardTitle className="text-lg font-semibold text-gray-900">Document Upload Policy</CardTitle>
            <CardDescription className="text-sm text-gray-600">
              Configure file upload limits, allowed types, and retention policies
            </CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        <DocumentUploadSettings
          maxFileSizeMB={config.maxFileSizeMB}
          retentionDays={config.retentionDays}
          onMaxFileSizeChange={(size) => updateConfig({ maxFileSizeMB: size })}
          onRetentionDaysChange={(days) => updateConfig({ retentionDays: days })}
        />

        <Separator />

        <AllowedFileTypes
          allowedFileTypes={config.allowedFileTypes}
          onAllowedFileTypesChange={(types) => updateConfig({ allowedFileTypes: types })}
        />

        <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 Document Policy
              </>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
