import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Save, RefreshCw, IndianRupee, Settings } from 'lucide-react';
import { masterService } from '@/services/master.service';
import { toast } from 'sonner';

export const SecurityDepositMaster: React.FC = () => {
  const [configs, setConfigs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [isSaving, setIsSaving] = useState<string | null>(null);

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

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

  const handleUpdateAmount = (id: string, newAmount: string) => {
    setConfigs(prev => prev.map(c => 
      c.id === id ? { ...c, value: { ...c.value, amount: parseInt(newAmount) || 0 } } : c
    ));
  };

  const handleSave = async (config: any) => {
    try {
      setIsSaving(config.id);
      const res = await masterService.saveSystemConfig(config) as any;
      if (res.success) {
        toast.success(`Configuration for ${config.key} updated successfully`);
      }
    } catch (error) {
      toast.error('Failed to save configuration');
    } finally {
      setIsSaving(null);
    }
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center p-20 space-y-4">
        <div className="w-10 h-10 border-4 border-re-red border-t-transparent rounded-full animate-spin"></div>
        <p className="text-slate-600 animate-pulse">Loading settings...</p>
      </div>
    );
  }

  return (
    <div className="space-y-4 animate-in fade-in duration-500 max-w-4xl">
      <Card className="border-none shadow-lg bg-white/80 backdrop-blur-md">
        <CardHeader className="py-4 border-b bg-slate-50/50">
          <div className="flex items-center gap-3">
             <div className="w-8 h-8 rounded-lg bg-red-100 flex items-center justify-center">
                <Settings className="w-5 h-5 text-re-red" />
             </div>
             <div>
                <CardTitle className="text-lg font-bold text-slate-900">
                  Global Payment Settings
                </CardTitle>
                <CardDescription className="text-xs">
                  Configure base security deposit amounts for onboarding workflows.
                </CardDescription>
             </div>
          </div>
        </CardHeader>
        <CardContent className="p-4">
          <div className="grid gap-3">
            {configs.map((config) => (
              <div key={config.id} className="p-3 border rounded-xl bg-white hover:shadow-sm transition-shadow flex items-center justify-between border-slate-100">
                <div className="space-y-0.5 max-w-md">
                  <h4 className="font-bold text-slate-800 text-sm flex items-center gap-2">
                    {config.key.replace(/_/g, ' ')}
                    <span className="text-[9px] bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded-full uppercase tracking-wider">Master</span>
                  </h4>
                  <p className="text-xs text-slate-500 leading-tight">{config.description}</p>
                </div>
                
                <div className="flex items-center gap-4">
                  <div className="space-y-1">
                    <Label htmlFor={`amount-${config.id}`} className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider block">Amount (INR)</Label>
                    <div className="relative w-40">
                      <IndianRupee className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400 font-bold" />
                      <Input
                        id={`amount-${config.id}`}
                        type="number"
                        className="pl-8 h-9 text-base font-bold bg-slate-50/50 border-slate-200 focus:ring-red-500 focus:border-red-500 rounded-lg"
                        value={config.value?.amount || ''}
                        onChange={(e) => handleUpdateAmount(config.id, e.target.value)}
                      />
                    </div>
                  </div>
                  
                  <div className="pt-4">
                    <Button 
                      onClick={() => handleSave(config)}
                      disabled={isSaving === config.id}
                      className="h-9 px-4 bg-re-red hover:bg-re-red-hover text-white rounded-lg shadow-md shadow-re-red/10 active:scale-95 transition-all flex items-center gap-1.5 group"
                    >
                      {isSaving === config.id ? (
                        <RefreshCw className="w-4 h-4 animate-spin" />
                      ) : (
                        <>
                          <Save className="w-4 h-4 group-hover:scale-110 transition-transform" />
                          <span className="font-bold text-sm">Update</span>
                        </>
                      )}
                    </Button>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {configs.length === 0 && (
            <div className="text-center py-12 bg-slate-50/50 rounded-xl border border-dashed border-slate-200">
              <div className="w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-3">
                <Settings className="w-6 h-6 text-slate-400" />
              </div>
              <p className="text-slate-500 text-sm font-medium">No configurations found.</p>
              <Button variant="outline" className="mt-4 rounded-lg h-9 text-xs" onClick={fetchConfigs}>
                <RefreshCw className="w-3.5 h-3.5 mr-1.5" /> Reload
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      <div className="bg-red-50/50 rounded-xl p-4 border border-red-100/50 flex items-start gap-3">
          <div className="w-8 h-8 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0">
             <Settings className="w-4 h-4 text-re-red-hover" />
          </div>
          <div>
            <h5 className="font-bold text-red-900 text-sm">Super Admin Notice</h5>
            <p className="text-[11px] text-red-800/80 leading-snug">
              Updates made here take immediate effect. These values define the default expected amounts for all current and future onboarding payments.
            </p>
          </div>
      </div>
    </div>
  );
};


