"use client";

import { useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react";
import { ProtectedLayout } from "@/components/protected-layout";
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 { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { Progress } from "@/components/ui/progress";
import {
  Zap,
  Plus,
  Play,
  Pause,
  Settings,
  Clock,
  MessageSquare,
  Mail,
  Bell,
  RefreshCw,
  CheckCircle,
  XCircle,
  AlertTriangle,
  Trash2,
  Edit,
  Calendar,
  Target,
  History,
  Users,
  DollarSign,
  Phone,
  FileText,
  TrendingUp,
} from "lucide-react";
import { format } from "date-fns";

interface WorkflowTrigger {
  id: string;
  name: string;
  description?: string;
  triggerType: string;
  channel: string;
  conditions: string;
  messageTemplate: string;
  isActive: boolean;
  status: string;
  runTime?: string;
  lastRunAt?: string;
  executionCount: number;
  successCount: number;
  failureCount: number;
  createdAt: string;
  _count?: {
    executions: number;
  };
}

interface WorkflowExecution {
  id: string;
  collectionFileId?: string;
  targetPhone?: string;
  channel: string;
  messageContent: string;
  status: string;
  errorMessage?: string;
  executedAt: string;
}

interface Agent {
  id: string;
  name: string;
  email: string;
}

interface AgentTarget {
  id: string;
  agentId: string;
  agent: Agent;
  month: number;
  year: number;
  targetAmount: number;
  targetFiles: number;
  targetCalls: number;
  targetSms: number;
  targetPaidFiles: number;
  currentAmount: number;
  currentFiles: number;
  currentCalls: number;
  currentSms: number;
  currentPaidFiles: number;
  notes?: string;
  createdBy?: { id: string; name: string };
  createdAt: string;
}

const TRIGGER_TYPES = [
  { value: "PTP_REMINDER", label: "Promise to Pay Reminder", icon: Calendar, description: "Send reminder before PTP date" },
  { value: "OVERDUE_PAYMENT", label: "Overdue Payment", icon: AlertTriangle, description: "Alert when payment is overdue" },
  { value: "NO_CONTACT", label: "No Contact", icon: Clock, description: "Follow up after no contact" },
  { value: "WELCOME", label: "Welcome Message", icon: Bell, description: "Send welcome to new files" },
  { value: "PAYMENT_RECEIVED", label: "Payment Thank You", icon: CheckCircle, description: "Thank customer after payment" },
];

const CHANNELS = [
  { value: "SMS", label: "SMS", icon: MessageSquare },
  { value: "EMAIL", label: "Email", icon: Mail },
];

const DEFAULT_TEMPLATES: Record<string, string> = {
  PTP_REMINDER: "Dear {{customerName}}, this is a reminder of your payment commitment of KES {{promisedAmount}} due on {{promisedDate}}. Please ensure timely payment to avoid additional charges. - GRECO",
  OVERDUE_PAYMENT: "Dear {{customerName}}, your payment of KES {{amount}} is now overdue. Please make payment immediately to avoid further action. Contact us to discuss payment options. - GRECO",
  NO_CONTACT: "Dear {{customerName}}, we have been trying to reach you regarding your outstanding balance of KES {{amount}}. Please contact us urgently. - GRECO",
  WELCOME: "Dear {{customerName}}, your account has been assigned to GRECO for collection. Outstanding balance: KES {{amount}}. Please contact us to discuss payment arrangements. - GRECO",
  PAYMENT_RECEIVED: "Dear {{customerName}}, thank you for your payment. Your remaining balance is KES {{amount}}. We appreciate your cooperation. - GRECO",
};

export default function WorkflowsPage() {
  const { data: session, status } = useSession() || {};
  const { toast } = useToast();

  const [workflows, setWorkflows] = useState<WorkflowTrigger[]>([]);
  const [selectedWorkflow, setSelectedWorkflow] = useState<WorkflowTrigger | null>(null);
  const [executions, setExecutions] = useState<WorkflowExecution[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [isExecuting, setIsExecuting] = useState(false);
  const [activeTab, setActiveTab] = useState("workflows");

  // Agent Targets State
  const [agents, setAgents] = useState<Agent[]>([]);
  const [agentTargets, setAgentTargets] = useState<AgentTarget[]>([]);
  const [isTargetDialogOpen, setIsTargetDialogOpen] = useState(false);
  const [editingTarget, setEditingTarget] = useState<AgentTarget | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [selectedMonth, setSelectedMonth] = useState(new Date().getMonth() + 1);
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear());
  const [targetFormData, setTargetFormData] = useState({
    agentId: "",
    month: new Date().getMonth() + 1,
    year: new Date().getFullYear(),
    targetAmount: "",
    targetFiles: "",
    targetCalls: "",
    targetSms: "",
    targetPaidFiles: "",
    notes: "",
  });

  // Form state
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    triggerType: "PTP_REMINDER",
    channel: "SMS",
    messageTemplate: DEFAULT_TEMPLATES.PTP_REMINDER,
    runTime: "09:00",
    daysBefore: "1",
    daysAfter: "1",
    daysNoContact: "7",
    hoursAfterCreation: "24",
  });

  const fetchWorkflows = useCallback(async () => {
    try {
      const response = await fetch("/api/workflows");
      if (response.ok) {
        const data = await response.json();
        setWorkflows(data.workflows || []);
      }
    } catch (error) {
      console.error("Error fetching workflows:", error);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const fetchWorkflowDetails = useCallback(async (id: string) => {
    try {
      const response = await fetch(`/api/workflows/${id}`);
      if (response.ok) {
        const data = await response.json();
        setSelectedWorkflow(data);
        setExecutions(data.executions || []);
      }
    } catch (error) {
      console.error("Error fetching workflow details:", error);
    }
  }, []);

  const fetchAgents = useCallback(async () => {
    try {
      const response = await fetch("/api/users?role=AGENT");
      if (response.ok) {
        const data = await response.json();
        setAgents(data.users || []);
      }
    } catch (error) {
      console.error("Error fetching agents:", error);
    }
  }, []);

  const fetchAgentTargets = useCallback(async () => {
    try {
      const params = new URLSearchParams({
        month: selectedMonth.toString(),
        year: selectedYear.toString(),
      });
      const response = await fetch(`/api/agent-targets?${params}`);
      if (response.ok) {
        const data = await response.json();
        setAgentTargets(data.targets || []);
      }
    } catch (error) {
      console.error("Error fetching agent targets:", error);
    }
  }, [selectedMonth, selectedYear]);

  const handleRefreshProgress = async () => {
    setIsRefreshing(true);
    try {
      const response = await fetch("/api/agent-targets/refresh", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ month: selectedMonth, year: selectedYear }),
      });
      
      if (response.ok) {
        toast({
          title: "Progress Updated",
          description: "Agent target progress has been refreshed.",
        });
        fetchAgentTargets();
      }
    } catch (error) {
      console.error("Error refreshing progress:", error);
      toast({
        title: "Error",
        description: "Failed to refresh progress",
        variant: "destructive",
      });
    } finally {
      setIsRefreshing(false);
    }
  };

  const handleSaveTarget = async () => {
    try {
      const response = await fetch("/api/agent-targets", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(targetFormData),
      });

      if (response.ok) {
        toast({
          title: editingTarget ? "Target Updated" : "Target Created",
          description: `Agent target has been ${editingTarget ? "updated" : "created"} successfully.`,
        });
        setIsTargetDialogOpen(false);
        setEditingTarget(null);
        resetTargetForm();
        fetchAgentTargets();
      } else {
        const error = await response.json();
        throw new Error(error.error || "Failed to save target");
      }
    } catch (error) {
      console.error("Error saving target:", error);
      toast({
        title: "Error",
        description: error instanceof Error ? error.message : "Failed to save target",
        variant: "destructive",
      });
    }
  };

  const handleDeleteTarget = async (id: string) => {
    if (!confirm("Are you sure you want to delete this target?")) return;
    
    try {
      const response = await fetch(`/api/agent-targets?id=${id}`, {
        method: "DELETE",
      });

      if (response.ok) {
        toast({
          title: "Target Deleted",
          description: "Agent target has been deleted.",
        });
        fetchAgentTargets();
      }
    } catch (error) {
      console.error("Error deleting target:", error);
    }
  };

  const handleEditTarget = (target: AgentTarget) => {
    setEditingTarget(target);
    setTargetFormData({
      agentId: target.agentId,
      month: target.month,
      year: target.year,
      targetAmount: target.targetAmount.toString(),
      targetFiles: target.targetFiles.toString(),
      targetCalls: target.targetCalls.toString(),
      targetSms: target.targetSms.toString(),
      targetPaidFiles: target.targetPaidFiles.toString(),
      notes: target.notes || "",
    });
    setIsTargetDialogOpen(true);
  };

  const resetTargetForm = () => {
    setTargetFormData({
      agentId: "",
      month: selectedMonth,
      year: selectedYear,
      targetAmount: "",
      targetFiles: "",
      targetCalls: "",
      targetSms: "",
      targetPaidFiles: "",
      notes: "",
    });
    setEditingTarget(null);
  };

  const getProgressPercent = (current: number, target: number) => {
    if (target === 0) return 0;
    return Math.min(Math.round((current / target) * 100), 100);
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("en-KE", { style: "currency", currency: "KES" }).format(amount);
  };

  const MONTHS = [
    { value: 1, label: "January" },
    { value: 2, label: "February" },
    { value: 3, label: "March" },
    { value: 4, label: "April" },
    { value: 5, label: "May" },
    { value: 6, label: "June" },
    { value: 7, label: "July" },
    { value: 8, label: "August" },
    { value: 9, label: "September" },
    { value: 10, label: "October" },
    { value: 11, label: "November" },
    { value: 12, label: "December" },
  ];

  useEffect(() => {
    if (status === "authenticated") {
      fetchWorkflows();
      fetchAgents();
    }
  }, [status, fetchWorkflows, fetchAgents]);

  useEffect(() => {
    if (status === "authenticated") {
      fetchAgentTargets();
    }
  }, [status, fetchAgentTargets, selectedMonth, selectedYear]);

  const handleCreateWorkflow = async () => {
    try {
      const conditions: Record<string, number> = {};
      switch (formData.triggerType) {
        case "PTP_REMINDER":
          conditions.daysBefore = parseInt(formData.daysBefore);
          break;
        case "OVERDUE_PAYMENT":
          conditions.daysOverdue = parseInt(formData.daysAfter);
          break;
        case "NO_CONTACT":
          conditions.daysNoContact = parseInt(formData.daysNoContact);
          break;
        case "WELCOME":
          conditions.hoursAfterCreation = parseInt(formData.hoursAfterCreation);
          break;
      }

      const response = await fetch("/api/workflows", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: formData.name,
          description: formData.description,
          triggerType: formData.triggerType,
          channel: formData.channel,
          messageTemplate: formData.messageTemplate,
          runTime: formData.runTime,
          conditions,
        }),
      });

      if (response.ok) {
        toast({
          title: "Workflow Created",
          description: "Your automation workflow has been created successfully.",
        });
        setIsCreateOpen(false);
        fetchWorkflows();
        // Reset form
        setFormData({
          name: "",
          description: "",
          triggerType: "PTP_REMINDER",
          channel: "SMS",
          messageTemplate: DEFAULT_TEMPLATES.PTP_REMINDER,
          runTime: "09:00",
          daysBefore: "1",
          daysAfter: "1",
          daysNoContact: "7",
          hoursAfterCreation: "24",
        });
      } else {
        const error = await response.json();
        throw new Error(error.error || "Failed to create workflow");
      }
    } catch (error) {
      console.error("Error creating workflow:", error);
      toast({
        title: "Error",
        description: error instanceof Error ? error.message : "Failed to create workflow",
        variant: "destructive",
      });
    }
  };

  const handleToggleWorkflow = async (id: string, isActive: boolean) => {
    try {
      const response = await fetch(`/api/workflows/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isActive }),
      });

      if (response.ok) {
        setWorkflows((prev) =>
          prev.map((w) => (w.id === id ? { ...w, isActive } : w))
        );
        toast({
          title: isActive ? "Workflow Activated" : "Workflow Paused",
          description: `The workflow has been ${isActive ? "activated" : "paused"}.`,
        });
      }
    } catch (error) {
      console.error("Error toggling workflow:", error);
    }
  };

  const handleExecuteWorkflow = async (workflowId?: string) => {
    setIsExecuting(true);
    try {
      const response = await fetch("/api/workflows/execute", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ workflowId, manual: true }),
      });

      if (response.ok) {
        const data = await response.json();
        const totalSent = data.results?.reduce((sum: number, r: { sent: number }) => sum + r.sent, 0) || 0;
        const totalFailed = data.results?.reduce((sum: number, r: { failed: number }) => sum + r.failed, 0) || 0;

        toast({
          title: "Workflow Executed",
          description: `Sent: ${totalSent}, Failed: ${totalFailed}`,
        });

        fetchWorkflows();
        if (selectedWorkflow) {
          fetchWorkflowDetails(selectedWorkflow.id);
        }
      } else {
        throw new Error("Execution failed");
      }
    } catch (error) {
      console.error("Error executing workflow:", error);
      toast({
        title: "Error",
        description: "Failed to execute workflow",
        variant: "destructive",
      });
    } finally {
      setIsExecuting(false);
    }
  };

  const handleDeleteWorkflow = async (id: string) => {
    if (!confirm("Are you sure you want to delete this workflow?")) return;

    try {
      const response = await fetch(`/api/workflows/${id}`, {
        method: "DELETE",
      });

      if (response.ok) {
        toast({
          title: "Workflow Deleted",
          description: "The workflow has been deleted.",
        });
        setSelectedWorkflow(null);
        fetchWorkflows();
      }
    } catch (error) {
      console.error("Error deleting workflow:", error);
    }
  };

  const getTriggerTypeInfo = (type: string) => {
    return TRIGGER_TYPES.find((t) => t.value === type) || TRIGGER_TYPES[0];
  };

  const user = session?.user as { role?: string } | undefined;

  if (status === "loading" || isLoading) {
    return (
      <ProtectedLayout>
        <div className="flex items-center justify-center h-64">
          <RefreshCw className="h-8 w-8 animate-spin text-blue-600" />
        </div>
      </ProtectedLayout>
    );
  }

  if (user?.role === "AGENT") {
    return (
      <ProtectedLayout>
        <div className="flex items-center justify-center h-64">
          <p className="text-gray-500">You don&apos;t have permission to access this page.</p>
        </div>
      </ProtectedLayout>
    );
  }

  return (
    <ProtectedLayout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Workflow & Targets</h1>
            <p className="text-gray-600 mt-1">Manage automation workflows and agent targets</p>
          </div>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList>
            <TabsTrigger value="workflows" className="flex items-center gap-2">
              <Zap className="h-4 w-4" />
              Automation Workflows
            </TabsTrigger>
            <TabsTrigger value="targets" className="flex items-center gap-2">
              <Target className="h-4 w-4" />
              Agent Targets
            </TabsTrigger>
          </TabsList>

          {/* Automation Workflows Tab */}
          <TabsContent value="workflows" className="mt-6 space-y-6">
            <div className="flex items-center justify-end gap-2">
              <Button
                variant="outline"
                onClick={() => handleExecuteWorkflow()}
                disabled={isExecuting}
              >
                {isExecuting ? (
                  <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                ) : (
                  <Play className="h-4 w-4 mr-2" />
                )}
                Run All Active
              </Button>
              <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                <DialogTrigger asChild>
                  <Button>
                    <Plus className="h-4 w-4 mr-2" />
                    New Workflow
                  </Button>
                </DialogTrigger>
              <DialogContent className="max-w-2xl">
                <DialogHeader>
                  <DialogTitle>Create Automation Workflow</DialogTitle>
                  <DialogDescription>
                    Set up automated messages based on customer events
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Workflow Name</Label>
                      <Input
                        value={formData.name}
                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                        placeholder="e.g., PTP Reminder - 1 Day Before"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Channel</Label>
                      <Select
                        value={formData.channel}
                        onValueChange={(value) => setFormData({ ...formData, channel: value })}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {CHANNELS.map((c) => (
                            <SelectItem key={c.value} value={c.value}>
                              <div className="flex items-center gap-2">
                                <c.icon className="h-4 w-4" />
                                {c.label}
                              </div>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label>Trigger Type</Label>
                    <Select
                      value={formData.triggerType}
                      onValueChange={(value) => {
                        setFormData({
                          ...formData,
                          triggerType: value,
                          messageTemplate: DEFAULT_TEMPLATES[value] || "",
                        });
                      }}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {TRIGGER_TYPES.map((t) => (
                          <SelectItem key={t.value} value={t.value}>
                            <div className="flex items-center gap-2">
                              <t.icon className="h-4 w-4" />
                              <div>
                                <p>{t.label}</p>
                                <p className="text-xs text-gray-500">{t.description}</p>
                              </div>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Conditional fields based on trigger type */}
                  {formData.triggerType === "PTP_REMINDER" && (
                    <div className="space-y-2">
                      <Label>Days Before PTP Date</Label>
                      <Input
                        type="number"
                        value={formData.daysBefore}
                        onChange={(e) => setFormData({ ...formData, daysBefore: e.target.value })}
                        min="1"
                        max="7"
                      />
                    </div>
                  )}

                  {formData.triggerType === "OVERDUE_PAYMENT" && (
                    <div className="space-y-2">
                      <Label>Days After Due Date</Label>
                      <Input
                        type="number"
                        value={formData.daysAfter}
                        onChange={(e) => setFormData({ ...formData, daysAfter: e.target.value })}
                        min="1"
                        max="30"
                      />
                    </div>
                  )}

                  {formData.triggerType === "NO_CONTACT" && (
                    <div className="space-y-2">
                      <Label>Days Without Contact</Label>
                      <Input
                        type="number"
                        value={formData.daysNoContact}
                        onChange={(e) => setFormData({ ...formData, daysNoContact: e.target.value })}
                        min="1"
                        max="30"
                      />
                    </div>
                  )}

                  {formData.triggerType === "WELCOME" && (
                    <div className="space-y-2">
                      <Label>Hours After File Creation</Label>
                      <Input
                        type="number"
                        value={formData.hoursAfterCreation}
                        onChange={(e) => setFormData({ ...formData, hoursAfterCreation: e.target.value })}
                        min="1"
                        max="72"
                      />
                    </div>
                  )}

                  <div className="space-y-2">
                    <Label>Run Time (Daily)</Label>
                    <Input
                      type="time"
                      value={formData.runTime}
                      onChange={(e) => setFormData({ ...formData, runTime: e.target.value })}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label>Message Template</Label>
                    <Textarea
                      value={formData.messageTemplate}
                      onChange={(e) => setFormData({ ...formData, messageTemplate: e.target.value })}
                      rows={4}
                      placeholder="Use {{customerName}}, {{amount}}, {{promisedDate}}, {{promisedAmount}}"
                    />
                    <p className="text-xs text-gray-500">
                      Variables: {`{{customerName}}, {{amount}}, {{promisedDate}}, {{promisedAmount}}`}
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label>Description (Optional)</Label>
                    <Input
                      value={formData.description}
                      onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                      placeholder="Brief description of this workflow"
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsCreateOpen(false)}>
                    Cancel
                  </Button>
                  <Button onClick={handleCreateWorkflow} disabled={!formData.name || !formData.messageTemplate}>
                    Create Workflow
                  </Button>
                </DialogFooter>
              </DialogContent>
              </Dialog>
            </div>

            {/* Summary Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-blue-100 rounded-full">
                  <Zap className="h-6 w-6 text-blue-600" />
                </div>
                <div>
                  <p className="text-2xl font-bold">{workflows.length}</p>
                  <p className="text-sm text-gray-600">Total Workflows</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-green-100 rounded-full">
                  <Play className="h-6 w-6 text-green-600" />
                </div>
                <div>
                  <p className="text-2xl font-bold">
                    {workflows.filter((w) => w.isActive).length}
                  </p>
                  <p className="text-sm text-gray-600">Active</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-purple-100 rounded-full">
                  <Target className="h-6 w-6 text-purple-600" />
                </div>
                <div>
                  <p className="text-2xl font-bold">
                    {workflows.reduce((sum, w) => sum + w.executionCount, 0)}
                  </p>
                  <p className="text-sm text-gray-600">Total Executions</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-green-100 rounded-full">
                  <CheckCircle className="h-6 w-6 text-green-600" />
                </div>
                <div>
                  <p className="text-2xl font-bold">
                    {workflows.reduce((sum, w) => sum + w.successCount, 0)}
                  </p>
                  <p className="text-sm text-gray-600">Messages Sent</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Workflows List */}
          <div className="lg:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle>Automation Workflows</CardTitle>
                <CardDescription>Manage your automated engagement rules</CardDescription>
              </CardHeader>
              <CardContent>
                {workflows.length === 0 ? (
                  <div className="text-center py-8">
                    <Zap className="h-12 w-12 text-gray-300 mx-auto mb-4" />
                    <p className="text-gray-500">No workflows created yet</p>
                    <Button className="mt-4" onClick={() => setIsCreateOpen(true)}>
                      <Plus className="h-4 w-4 mr-2" />
                      Create Your First Workflow
                    </Button>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {workflows.map((workflow) => {
                      const triggerInfo = getTriggerTypeInfo(workflow.triggerType);
                      const TriggerIcon = triggerInfo.icon;
                      return (
                        <div
                          key={workflow.id}
                          className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                            selectedWorkflow?.id === workflow.id
                              ? "border-blue-500 bg-blue-50"
                              : "hover:bg-gray-50"
                          }`}
                          onClick={() => fetchWorkflowDetails(workflow.id)}
                        >
                          <div className="flex items-start justify-between">
                            <div className="flex items-start gap-3">
                              <div className={`p-2 rounded-full ${workflow.isActive ? "bg-green-100" : "bg-gray-100"}`}>
                                <TriggerIcon className={`h-5 w-5 ${workflow.isActive ? "text-green-600" : "text-gray-400"}`} />
                              </div>
                              <div>
                                <div className="flex items-center gap-2">
                                  <h3 className="font-medium">{workflow.name}</h3>
                                  <Badge variant="outline">{workflow.channel}</Badge>
                                  {workflow.isActive ? (
                                    <Badge className="bg-green-100 text-green-800">Active</Badge>
                                  ) : (
                                    <Badge variant="secondary">Paused</Badge>
                                  )}
                                </div>
                                <p className="text-sm text-gray-500 mt-1">{triggerInfo.description}</p>
                                <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                                  <span className="flex items-center gap-1">
                                    <Clock className="h-3 w-3" />
                                    {workflow.runTime || "Not scheduled"}
                                  </span>
                                  <span className="flex items-center gap-1">
                                    <Target className="h-3 w-3" />
                                    {workflow.executionCount} runs
                                  </span>
                                  <span className="flex items-center gap-1">
                                    <CheckCircle className="h-3 w-3 text-green-500" />
                                    {workflow.successCount} sent
                                  </span>
                                </div>
                              </div>
                            </div>
                            <Switch
                              checked={workflow.isActive}
                              onCheckedChange={(checked) => {
                                handleToggleWorkflow(workflow.id, checked);
                              }}
                              onClick={(e) => e.stopPropagation()}
                            />
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          {/* Workflow Details */}
          <div>
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Settings className="h-5 w-5" />
                  Workflow Details
                </CardTitle>
              </CardHeader>
              <CardContent>
                {selectedWorkflow ? (
                  <div className="space-y-4">
                    <div>
                      <Label className="text-xs text-gray-500">Message Template</Label>
                      <p className="text-sm bg-gray-50 p-3 rounded-lg mt-1">
                        {selectedWorkflow.messageTemplate}
                      </p>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label className="text-xs text-gray-500">Last Run</Label>
                        <p className="text-sm font-medium">
                          {selectedWorkflow.lastRunAt
                            ? format(new Date(selectedWorkflow.lastRunAt), "MMM d, HH:mm")
                            : "Never"}
                        </p>
                      </div>
                      <div>
                        <Label className="text-xs text-gray-500">Success Rate</Label>
                        <p className="text-sm font-medium">
                          {selectedWorkflow.executionCount > 0
                            ? Math.round(
                                (selectedWorkflow.successCount / selectedWorkflow.executionCount) * 100
                              )
                            : 0}%
                        </p>
                      </div>
                    </div>

                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        className="flex-1"
                        onClick={() => handleExecuteWorkflow(selectedWorkflow.id)}
                        disabled={isExecuting}
                      >
                        {isExecuting ? (
                          <RefreshCw className="h-4 w-4 mr-1 animate-spin" />
                        ) : (
                          <Play className="h-4 w-4 mr-1" />
                        )}
                        Run Now
                      </Button>
                      <Button
                        size="sm"
                        variant="destructive"
                        onClick={() => handleDeleteWorkflow(selectedWorkflow.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>

                    {/* Recent Executions */}
                    <div>
                      <Label className="text-xs text-gray-500 flex items-center gap-1">
                        <History className="h-3 w-3" />
                        Recent Executions
                      </Label>
                      <div className="space-y-2 mt-2 max-h-64 overflow-y-auto">
                        {executions.length === 0 ? (
                          <p className="text-sm text-gray-500">No executions yet</p>
                        ) : (
                          executions.slice(0, 10).map((exec) => (
                            <div
                              key={exec.id}
                              className="text-xs p-2 bg-gray-50 rounded flex items-center justify-between"
                            >
                              <div>
                                <p className="font-medium">{exec.targetPhone}</p>
                                <p className="text-gray-500">
                                  {format(new Date(exec.executedAt), "MMM d, HH:mm")}
                                </p>
                              </div>
                              {exec.status === "SENT" || exec.status === "DELIVERED" ? (
                                <CheckCircle className="h-4 w-4 text-green-500" />
                              ) : exec.status === "FAILED" ? (
                                <XCircle className="h-4 w-4 text-red-500" />
                              ) : (
                                <Clock className="h-4 w-4 text-yellow-500" />
                              )}
                            </div>
                          ))
                        )}
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    <Settings className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                    <p>Select a workflow to view details</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
          </TabsContent>

          {/* Agent Targets Tab */}
          <TabsContent value="targets" className="mt-6 space-y-6">
            {/* Header with filters and actions */}
            <div className="flex flex-wrap items-center justify-between gap-4">
              <div className="flex items-center gap-3">
                <Select 
                  value={selectedMonth.toString()} 
                  onValueChange={(val) => setSelectedMonth(parseInt(val))}
                >
                  <SelectTrigger className="w-36">
                    <SelectValue placeholder="Month" />
                  </SelectTrigger>
                  <SelectContent>
                    {MONTHS.map((m) => (
                      <SelectItem key={m.value} value={m.value.toString()}>
                        {m.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Select 
                  value={selectedYear.toString()} 
                  onValueChange={(val) => setSelectedYear(parseInt(val))}
                >
                  <SelectTrigger className="w-28">
                    <SelectValue placeholder="Year" />
                  </SelectTrigger>
                  <SelectContent>
                    {[2024, 2025, 2026, 2027].map((y) => (
                      <SelectItem key={y} value={y.toString()}>
                        {y}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  onClick={handleRefreshProgress}
                  disabled={isRefreshing}
                >
                  {isRefreshing ? (
                    <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                  ) : (
                    <RefreshCw className="h-4 w-4 mr-2" />
                  )}
                  Refresh Progress
                </Button>
                <Dialog 
                  open={isTargetDialogOpen} 
                  onOpenChange={(open) => {
                    setIsTargetDialogOpen(open);
                    if (!open) resetTargetForm();
                  }}
                >
                  <DialogTrigger asChild>
                    <Button>
                      <Plus className="h-4 w-4 mr-2" />
                      Set Target
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="max-w-lg">
                    <DialogHeader>
                      <DialogTitle>{editingTarget ? "Edit Target" : "Set Agent Target"}</DialogTitle>
                      <DialogDescription>
                        Set monthly performance targets for an agent
                      </DialogDescription>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                      <div className="grid grid-cols-3 gap-4">
                        <div className="space-y-2">
                          <Label>Agent</Label>
                          <Select
                            value={targetFormData.agentId}
                            onValueChange={(val) => setTargetFormData({ ...targetFormData, agentId: val })}
                            disabled={!!editingTarget}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder="Select agent" />
                            </SelectTrigger>
                            <SelectContent>
                              {agents.map((agent) => (
                                <SelectItem key={agent.id} value={agent.id}>
                                  {agent.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="space-y-2">
                          <Label>Month</Label>
                          <Select
                            value={targetFormData.month.toString()}
                            onValueChange={(val) => setTargetFormData({ ...targetFormData, month: parseInt(val) })}
                            disabled={!!editingTarget}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {MONTHS.map((m) => (
                                <SelectItem key={m.value} value={m.value.toString()}>
                                  {m.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="space-y-2">
                          <Label>Year</Label>
                          <Select
                            value={targetFormData.year.toString()}
                            onValueChange={(val) => setTargetFormData({ ...targetFormData, year: parseInt(val) })}
                            disabled={!!editingTarget}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {[2024, 2025, 2026, 2027].map((y) => (
                                <SelectItem key={y} value={y.toString()}>
                                  {y}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-2">
                          <Label className="flex items-center gap-2">
                            <DollarSign className="h-4 w-4 text-green-600" />
                            Target Amount (KES)
                          </Label>
                          <Input
                            type="number"
                            value={targetFormData.targetAmount}
                            onChange={(e) => setTargetFormData({ ...targetFormData, targetAmount: e.target.value })}
                            placeholder="e.g., 500000"
                          />
                        </div>
                        <div className="space-y-2">
                          <Label className="flex items-center gap-2">
                            <FileText className="h-4 w-4 text-blue-600" />
                            Target Paid Files
                          </Label>
                          <Input
                            type="number"
                            value={targetFormData.targetPaidFiles}
                            onChange={(e) => setTargetFormData({ ...targetFormData, targetPaidFiles: e.target.value })}
                            placeholder="e.g., 20"
                          />
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-2">
                          <Label className="flex items-center gap-2">
                            <Phone className="h-4 w-4 text-purple-600" />
                            Target Calls
                          </Label>
                          <Input
                            type="number"
                            value={targetFormData.targetCalls}
                            onChange={(e) => setTargetFormData({ ...targetFormData, targetCalls: e.target.value })}
                            placeholder="e.g., 200"
                          />
                        </div>
                        <div className="space-y-2">
                          <Label className="flex items-center gap-2">
                            <MessageSquare className="h-4 w-4 text-amber-600" />
                            Target SMS
                          </Label>
                          <Input
                            type="number"
                            value={targetFormData.targetSms}
                            onChange={(e) => setTargetFormData({ ...targetFormData, targetSms: e.target.value })}
                            placeholder="e.g., 100"
                          />
                        </div>
                      </div>

                      <div className="space-y-2">
                        <Label className="flex items-center gap-2">
                          <FileText className="h-4 w-4 text-gray-600" />
                          Target Files Worked
                        </Label>
                        <Input
                          type="number"
                          value={targetFormData.targetFiles}
                          onChange={(e) => setTargetFormData({ ...targetFormData, targetFiles: e.target.value })}
                          placeholder="e.g., 50"
                        />
                      </div>

                      <div className="space-y-2">
                        <Label>Notes (Optional)</Label>
                        <Textarea
                          value={targetFormData.notes}
                          onChange={(e) => setTargetFormData({ ...targetFormData, notes: e.target.value })}
                          placeholder="Any additional notes or context..."
                          rows={2}
                        />
                      </div>
                    </div>
                    <DialogFooter>
                      <Button variant="outline" onClick={() => setIsTargetDialogOpen(false)}>
                        Cancel
                      </Button>
                      <Button onClick={handleSaveTarget} disabled={!targetFormData.agentId}>
                        {editingTarget ? "Update Target" : "Set Target"}
                      </Button>
                    </DialogFooter>
                  </DialogContent>
                </Dialog>
              </div>
            </div>

            {/* Summary Cards */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <Card>
                <CardContent className="pt-6">
                  <div className="flex items-center gap-4">
                    <div className="p-3 bg-blue-100 rounded-full">
                      <Users className="h-6 w-6 text-blue-600" />
                    </div>
                    <div>
                      <p className="text-2xl font-bold">{agentTargets.length}</p>
                      <p className="text-sm text-gray-600">Agents with Targets</p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="pt-6">
                  <div className="flex items-center gap-4">
                    <div className="p-3 bg-green-100 rounded-full">
                      <DollarSign className="h-6 w-6 text-green-600" />
                    </div>
                    <div>
                      <p className="text-xl font-bold">
                        {formatCurrency(agentTargets.reduce((sum, t) => sum + t.targetAmount, 0))}
                      </p>
                      <p className="text-sm text-gray-600">Total Target Amount</p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="pt-6">
                  <div className="flex items-center gap-4">
                    <div className="p-3 bg-purple-100 rounded-full">
                      <TrendingUp className="h-6 w-6 text-purple-600" />
                    </div>
                    <div>
                      <p className="text-xl font-bold">
                        {formatCurrency(agentTargets.reduce((sum, t) => sum + t.currentAmount, 0))}
                      </p>
                      <p className="text-sm text-gray-600">Total Achieved</p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="pt-6">
                  <div className="flex items-center gap-4">
                    <div className="p-3 bg-amber-100 rounded-full">
                      <Target className="h-6 w-6 text-amber-600" />
                    </div>
                    <div>
                      <p className="text-2xl font-bold">
                        {agentTargets.length > 0
                          ? Math.round(
                              (agentTargets.reduce((sum, t) => sum + t.currentAmount, 0) /
                                Math.max(agentTargets.reduce((sum, t) => sum + t.targetAmount, 0), 1)) *
                                100
                            )
                          : 0}%
                      </p>
                      <p className="text-sm text-gray-600">Overall Progress</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* Agent Targets List */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Target className="h-5 w-5" />
                  Agent Targets - {MONTHS.find((m) => m.value === selectedMonth)?.label} {selectedYear}
                </CardTitle>
                <CardDescription>
                  Set and track monthly targets for each collection agent
                </CardDescription>
              </CardHeader>
              <CardContent>
                {agentTargets.length === 0 ? (
                  <div className="text-center py-12">
                    <Target className="h-12 w-12 text-gray-300 mx-auto mb-4" />
                    <p className="text-gray-500 mb-4">No targets set for this month</p>
                    <Button onClick={() => setIsTargetDialogOpen(true)}>
                      <Plus className="h-4 w-4 mr-2" />
                      Set First Target
                    </Button>
                  </div>
                ) : (
                  <div className="space-y-4">
                    {agentTargets.map((target) => (
                      <Card key={target.id} className="border-l-4 border-l-blue-500">
                        <CardContent className="pt-6">
                          <div className="flex items-start justify-between mb-4">
                            <div className="flex items-center gap-3">
                              <div className="p-2 bg-blue-100 rounded-full">
                                <Users className="h-5 w-5 text-blue-600" />
                              </div>
                              <div>
                                <h3 className="font-semibold">{target.agent.name}</h3>
                                <p className="text-sm text-gray-500">{target.agent.email}</p>
                              </div>
                            </div>
                            <div className="flex items-center gap-2">
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => handleEditTarget(target)}
                              >
                                <Edit className="h-4 w-4" />
                              </Button>
                              <Button
                                size="sm"
                                variant="destructive"
                                onClick={() => handleDeleteTarget(target.id)}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </div>
                          </div>

                          {/* Amount Target */}
                          <div className="mb-4">
                            <div className="flex justify-between items-center mb-1">
                              <span className="text-sm font-medium flex items-center gap-1">
                                <DollarSign className="h-4 w-4 text-green-600" />
                                Collection Amount
                              </span>
                              <span className="text-sm">
                                {formatCurrency(target.currentAmount)} / {formatCurrency(target.targetAmount)}
                              </span>
                            </div>
                            <Progress 
                              value={getProgressPercent(target.currentAmount, target.targetAmount)} 
                              className="h-3"
                            />
                            <p className="text-xs text-right mt-1 text-gray-500">
                              {getProgressPercent(target.currentAmount, target.targetAmount)}% achieved
                            </p>
                          </div>

                          {/* Grid of other targets */}
                          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                            <div className="bg-green-50 p-3 rounded-lg">
                              <div className="flex items-center gap-2 mb-2">
                                <CheckCircle className="h-4 w-4 text-green-600" />
                                <span className="text-xs font-medium text-green-800">Paid Files</span>
                              </div>
                              <div className="flex items-baseline gap-1">
                                <span className="text-lg font-bold">{target.currentPaidFiles}</span>
                                <span className="text-sm text-gray-500">/ {target.targetPaidFiles}</span>
                              </div>
                              <Progress 
                                value={getProgressPercent(target.currentPaidFiles, target.targetPaidFiles)} 
                                className="h-1 mt-2"
                              />
                            </div>

                            <div className="bg-purple-50 p-3 rounded-lg">
                              <div className="flex items-center gap-2 mb-2">
                                <Phone className="h-4 w-4 text-purple-600" />
                                <span className="text-xs font-medium text-purple-800">Calls Made</span>
                              </div>
                              <div className="flex items-baseline gap-1">
                                <span className="text-lg font-bold">{target.currentCalls}</span>
                                <span className="text-sm text-gray-500">/ {target.targetCalls}</span>
                              </div>
                              <Progress 
                                value={getProgressPercent(target.currentCalls, target.targetCalls)} 
                                className="h-1 mt-2"
                              />
                            </div>

                            <div className="bg-amber-50 p-3 rounded-lg">
                              <div className="flex items-center gap-2 mb-2">
                                <MessageSquare className="h-4 w-4 text-amber-600" />
                                <span className="text-xs font-medium text-amber-800">SMS Sent</span>
                              </div>
                              <div className="flex items-baseline gap-1">
                                <span className="text-lg font-bold">{target.currentSms}</span>
                                <span className="text-sm text-gray-500">/ {target.targetSms}</span>
                              </div>
                              <Progress 
                                value={getProgressPercent(target.currentSms, target.targetSms)} 
                                className="h-1 mt-2"
                              />
                            </div>

                            <div className="bg-blue-50 p-3 rounded-lg">
                              <div className="flex items-center gap-2 mb-2">
                                <FileText className="h-4 w-4 text-blue-600" />
                                <span className="text-xs font-medium text-blue-800">Files Worked</span>
                              </div>
                              <div className="flex items-baseline gap-1">
                                <span className="text-lg font-bold">{target.currentFiles}</span>
                                <span className="text-sm text-gray-500">/ {target.targetFiles}</span>
                              </div>
                              <Progress 
                                value={getProgressPercent(target.currentFiles, target.targetFiles)} 
                                className="h-1 mt-2"
                              />
                            </div>
                          </div>

                          {target.notes && (
                            <div className="mt-4 p-3 bg-gray-50 rounded-lg">
                              <p className="text-xs text-gray-500">Notes: {target.notes}</p>
                            </div>
                          )}
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </ProtectedLayout>
  );
}
