import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '@/store';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Clock, Plus, Pen, Bell, AlertTriangle, CheckCircle, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';
import { masterService } from '@/services/master.service';
import { setMasterData } from '@/store/slices/masterSlice';
import { SLADialog } from '@/features/master/components/SLADialog';

export const SLAConfigPage: React.FC = () => {
  const dispatch = useDispatch();
  const { slaConfigs, loading } = useSelector((state: RootState) => state.master);
  const [showSLADialog, setShowSLADialog] = useState(false);
  const [selectedSLA, setSelectedSLA] = useState<any>(null);

  const fetchConfigs = async () => {
    try {
      const res = await masterService.getSlaConfigs() as any;
      if (res && res.success) {
        dispatch(setMasterData({ slaConfigs: res.data }));
      }
    } catch (error) {
      toast.error('Failed to fetch SLA configurations');
    }
  };

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

  const handleInitialize = async () => {
    try {
      setLoadingMore(true);
      const res = await masterService.initializeDefaultSlas() as any;
      if (res && res.success) {
        toast.success('Default SLAs initialized successfully');
        fetchConfigs();
      }
    } catch (error) {
      toast.error('Failed to initialize default SLAs');
    } finally {
      setLoadingMore(false);
    }
  };

  const handleEdit = (sla: any) => {
    setSelectedSLA(sla);
    setShowSLADialog(true);
  };

  const handleAddSLA = () => {
    setSelectedSLA(null);
    setShowSLADialog(true);
  };

  const [loadingMore, setLoadingMore] = useState(false);

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 flex items-center gap-2">
            <Clock className="w-6 h-6 text-amber-600" />
            SLA & Escalation Matrix
          </h1>
          <p className="text-slate-500">Configure Turn Around Time (TAT) and escalation rules for each process stage</p>
        </div>
        <div className="flex items-center gap-3">
          <Button variant="outline" onClick={handleInitialize} disabled={loading || loadingMore}>
            <RefreshCw className={`w-4 h-4 mr-2 ${loadingMore ? 'animate-spin' : ''}`} />
            Initialize Defaults
          </Button>
          <Button onClick={handleAddSLA} disabled={loading} className="bg-re-red hover:bg-re-red-hover text-white">
            <Plus className="w-4 h-4 mr-2" />
            Add Manual SLA
          </Button>
          <Button variant="ghost" size="icon" onClick={fetchConfigs} disabled={loading}>
            <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {slaConfigs.map((sla) => (
          <Card key={sla.id} className="border-slate-200 hover:shadow-md transition-shadow group overflow-hidden">
            <CardHeader className="pb-3 bg-gradient-to-br from-white to-slate-50/50">
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-amber-50 border border-amber-100 flex items-center justify-center">
                    <Clock className="w-5 h-5 text-amber-600" />
                  </div>
                  <div>
                    <CardTitle className="text-lg">{sla.activityName}</CardTitle>
                    <CardDescription className="flex items-center gap-1.5 mt-0.5">
                      <span className="font-semibold text-amber-700">Target TAT: {sla.tatHours} {sla.tatUnit}</span>
                    </CardDescription>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant={sla.isActive ? "default" : "secondary"} className={sla.isActive ? "bg-emerald-600" : "bg-slate-400"}>
                    {sla.isActive ? (
                      <><CheckCircle className="w-3 h-3 mr-1" /> Active</>
                    ) : (
                      'Disabled'
                    )}
                  </Badge>
                  <Button variant="ghost" size="icon" onClick={() => handleEdit(sla)} className="h-8 w-8 text-slate-400 hover:text-amber-600">
                    <Pen className="w-4 h-4" />
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent className="pt-4 grid grid-cols-2 gap-4">
              <div className="border-l-2 border-blue-400 pl-3">
                <div className="flex items-center gap-2 mb-2">
                  <Bell className="w-4 h-4 text-blue-600" />
                  <span className="text-xs font-bold text-slate-700 uppercase tracking-wider">Reminders ({sla.reminders?.length || 0})</span>
                </div>
                <div className="space-y-1.5">
                  {(sla.reminders || []).map((reminder: any, idx: number) => (
                    <div key={idx} className="text-xs text-slate-600 flex items-center gap-1">
                      <Badge variant="outline" className="text-[10px] h-4.5 bg-blue-50 border-blue-200">
                        {reminder.timeValue} {reminder.timeUnit}
                      </Badge>
                      <span>before SLA</span>
                    </div>
                  ))}
                  {(!sla.reminders || sla.reminders.length === 0) && (
                    <p className="text-[10px] text-slate-400 italic">None configured</p>
                  )}
                </div>
              </div>

              <div className="border-l-2 border-red-400 pl-3">
                <div className="flex items-center gap-2 mb-2">
                  <AlertTriangle className="w-4 h-4 text-re-red" />
                  <span className="text-xs font-bold text-slate-700 uppercase tracking-wider">Escalations ({sla.escalationConfigs?.length || 0})</span>
                </div>
                <div className="space-y-2">
                  {(sla.escalationConfigs || []).map((esc: any, idx: number) => (
                    <div key={idx} className="text-[11px]">
                      <div className="flex items-center gap-1.5 text-slate-900 font-medium">
                        <Badge variant="outline" className="text-[9px] h-4 px-1 bg-red-50 border-red-200 text-re-red-hover">
                          L{esc.level}
                        </Badge>
                        <span>after {esc.timeValue} {esc.timeUnit}</span>
                      </div>
                      <p className="text-slate-500 ml-8 font-mono truncate">{esc.notifyEmail}</p>
                    </div>
                  ))}
                  {(!sla.escalationConfigs || sla.escalationConfigs.length === 0) && (
                    <p className="text-[10px] text-slate-400 italic">None configured</p>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}

        {slaConfigs.length === 0 && !loading && (
          <div className="lg:col-span-2 py-20 text-center border-2 border-dashed rounded-2xl bg-slate-50/50">
            <Clock className="w-12 h-12 text-slate-200 mx-auto mb-4" />
            <h3 className="text-slate-600 font-medium">No SLA Workflows found</h3>
            <p className="text-slate-400 text-sm">Please initialize default configurations from the admin tools</p>
          </div>
        )}
      </div>

      <SLADialog 
        isOpen={showSLADialog}
        onClose={() => setShowSLADialog(false)}
        sla={selectedSLA}
        onSave={fetchConfigs}
      />
    </div>
  );
};
