import React, { useState, useEffect } from 'react';
import { masterService } from '@/services/master.service';
import { Switch } from '@/components/ui/switch';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/components/ui/utils';
import { toast } from 'sonner';
import { 
  Settings2, 
  Info, 
  RefreshCcw, 
  ClipboardList, 
  Truck, 
  FileX, 
  Gavel, 
  FileText, 
  Banknote,
} from 'lucide-react';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';

interface SystemConfig {
  id: string;
  key: string;
  value: { enabled: boolean };
  category: string;
  description: string;
  isActive: boolean;
}

export const AutoAssignmentSettings: React.FC = () => {
  const [configs, setConfigs] = useState<SystemConfig[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchConfigs = async () => {
    setLoading(true);
    try {
      const res: any = await masterService.getSystemConfigs({ category: 'ASSIGNMENT' });
      if (res.success) {
        setConfigs(res.data);
      }
    } catch (error) {
      toast.error('Failed to load assignment configurations');
    } finally {
      setLoading(false);
    }
  };

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

  const handleToggle = (key: string, enabled: boolean) => {
    setConfigs(prev => prev.map(c => 
      c.key === key ? { ...c, value: { ...c.value, enabled } } : c
    ));
  };

  const handleSave = async (config: SystemConfig) => {
    try {
      const res: any = await masterService.saveSystemConfig({
          key: config.key,
          value: config.value,
          category: config.category,
          description: config.description
      });
      if (res.success) {
        toast.success(`${config.key.replace('AUTO_ASSIGN_', '')} setting updated`);
      }
    } catch (error) {
      toast.error('Failed to save configuration');
    }
  };

  const modules = [
    { key: 'AUTO_ASSIGN_ONBOARDING', label: 'Onboarding', icon: ClipboardList, color: 'text-slate-500', bg: 'bg-slate-100' },
    { key: 'AUTO_ASSIGN_RELOCATION', label: 'Relocation', icon: Truck, color: 'text-slate-500', bg: 'bg-slate-100' },
    { key: 'AUTO_ASSIGN_TERMINATION', label: 'Termination', icon: FileX, color: 'text-slate-500', bg: 'bg-slate-100' },
    { key: 'AUTO_ASSIGN_CONSTITUTIONAL', label: 'Constitutional', icon: Gavel, color: 'text-slate-500', bg: 'bg-slate-100' },
    { key: 'AUTO_ASSIGN_RESIGNATION', label: 'Resignation', icon: FileText, color: 'text-slate-500', bg: 'bg-slate-100' },
    { key: 'AUTO_ASSIGN_FNF', label: 'F&F Settlement', icon: Banknote, color: 'text-slate-500', bg: 'bg-slate-100' },
  ];

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center p-12 space-y-4">
        <RefreshCcw className="w-8 h-8 animate-spin text-re-red" />
        <p className="text-slate-500 font-medium">Loading governance controls...</p>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <Card className="border-none shadow-md overflow-hidden bg-white/50 backdrop-blur-sm">
        <CardHeader className="bg-gradient-to-r from-slate-900 to-slate-800 text-white p-6">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-red-500/20 rounded-lg">
              <Settings2 className="w-6 h-6 text-red-400" />
            </div>
            <div>
              <CardTitle className="text-xl font-bold">Auto-Assignment Governance</CardTitle>
              <CardDescription className="text-slate-300">
                Control the automated mapping of participants across different business modules
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {modules.map((mod) => {
              const config = configs.find(c => c.key === mod.key);
              const isEnabled = config?.value?.enabled ?? false;

              return (
                <div 
                  key={mod.key}
                  className="flex items-center justify-between p-4 rounded-xl border bg-white transition-all group"
                >
                  <div className="flex items-center gap-4">
                    <div className={cn(
                      "w-12 h-12 flex items-center justify-center rounded-full transition-colors",
                      mod.bg,
                      mod.color
                    )}>
                      <mod.icon className="w-6 h-6" />
                    </div>
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="font-semibold text-slate-900">{mod.label}</span>
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger>
                              <Info className="w-3.5 h-3.5 text-slate-400" />
                            </TooltipTrigger>
                            <TooltipContent className="max-w-xs">
                              <p>When OFF, all participants for new {mod.label} requests must be assigned manually by authorized administrators.</p>
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </div>
                      <div className="flex items-center gap-2">
                         <Badge variant={isEnabled ? "default" : "secondary"} className={isEnabled ? "bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-100" : "bg-slate-50 text-slate-500 border-slate-200"}>
                           {isEnabled ? 'Auto-Assign ON' : 'Manual Mode'}
                         </Badge>
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-4">
                    <Switch 
                      className="data-[state=checked]:bg-re-red"
                      checked={isEnabled}
                      onCheckedChange={(val) => {
                        handleToggle(mod.key, val);
                        // Save immediately for better UX
                        const updatedConfig = configs.find(c => c.key === mod.key);
                        if (updatedConfig) {
                          handleSave({ ...updatedConfig, value: { enabled: val } });
                        }
                      }}
                    />
                  </div>
                </div>
              );
            })}
          </div>

          <div className="mt-8 p-4 bg-red-50 border border-red-100 rounded-lg flex items-start gap-3">
             <Info className="w-5 h-5 text-re-red shrink-0 mt-0.5" />
             <div className="text-sm text-red-800">
                <p className="font-semibold mb-1">Impact of Manual Mode:</p>
                <p>Turning OFF auto-assignment will ONLY affect new requests. Existing requests will retain their current participant mappings. You will need to use the "Add Participant" button in the worknotes or application details to grant access to stakeholders.</p>
             </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};
