"use client";

import { useEffect, useMemo, useState } from "react";
import {
  PauseCircle,
  PlayCircle,
  Plus,
  RefreshCcw,
  Trash2,
  Workflow,
  Wand2,
  Zap,
} from "lucide-react";
import { useAutomations } from "@/hooks/use-automations";
import { useIntegrations } from "@/hooks/use-integrations";
import { useGoals } from "@/hooks/use-goals";
import { useNoteFolders } from "@/hooks/use-note-folders";
import { useProjects } from "@/hooks/use-projects";
import { useTags } from "@/hooks/use-tags";
import { useTeams } from "@/hooks/use-teams";
import {
  AUTOMATION_ACTION_OPTIONS,
  AUTOMATION_TRIGGER_OPTIONS,
  getAutomationActionLabel,
} from "@/lib/automations/catalog";
import {
  AUTOMATION_TEMPLATES,
  type AutomationTemplateDefinition,
} from "@/lib/automations/templates";
import type {
  AutomationActionConfig,
  AutomationActionType,
  AutomationRule,
  AutomationStep,
  AutomationTaskDeadlineState,
  Priority,
  ProjectHealth,
  TaskStatus,
} from "@/types";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";

type StepDraft = {
  enabled: boolean;
  actionType: AutomationActionType;
  connectionId: string;
  taskTitleTemplate: string;
  taskDescriptionTemplate: string;
  assigneeId: string;
  reviewerId: string;
  noteTitleTemplate: string;
  noteContentTemplate: string;
  noteFolderId: string;
  emailToTemplate: string;
  emailSubjectTemplate: string;
  emailBodyTemplate: string;
  promptTemplate: string;
  taskPriority: Priority;
};

const TASK_STATUS_OPTIONS: Array<{ value: TaskStatus; label: string }> = [
  { value: "todo", label: "Todo" },
  { value: "in_progress", label: "In progress" },
  { value: "done", label: "Done" },
  { value: "cancelled", label: "Cancelled" },
];

const PRIORITY_OPTIONS: Array<{ value: Priority; label: string }> = [
  { value: "urgent", label: "Urgent" },
  { value: "high", label: "High" },
  { value: "medium", label: "Medium" },
  { value: "low", label: "Low" },
  { value: "none", label: "None" },
];

const PROJECT_HEALTH_OPTIONS: Array<{ value: ProjectHealth; label: string }> = [
  { value: "on_track", label: "On track" },
  { value: "at_risk", label: "At risk" },
  { value: "stuck", label: "Stuck" },
];

const TASK_DEADLINE_STATE_OPTIONS: Array<{
  value: AutomationTaskDeadlineState;
  label: string;
}> = [
  { value: "has_deadline", label: "Has deadline" },
  { value: "no_deadline", label: "No deadline" },
  { value: "overdue", label: "Overdue" },
];

const WEEKDAY_OPTIONS = [
  { value: 1, label: "Monday" },
  { value: 2, label: "Tuesday" },
  { value: 3, label: "Wednesday" },
  { value: 4, label: "Thursday" },
  { value: 5, label: "Friday" },
  { value: 6, label: "Saturday" },
  { value: 0, label: "Sunday" },
];

const MAX_AUTOMATION_STEPS = 3;

function formatDate(value: string | null) {
  if (!value) return "Never";
  return new Intl.DateTimeFormat(undefined, {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(new Date(value));
}

function createStepDraft(
  overrides?: Partial<StepDraft>
): StepDraft {
  return {
    enabled: false,
    actionType: "create_task",
    connectionId: "",
    taskTitleTemplate: "Follow up: {{task.title}}",
    taskDescriptionTemplate: 'Generated by automation from {{event.type}}.',
    assigneeId: "",
    reviewerId: "",
    noteContentTemplate: 'Captured by automation from {{event.type}}.',
    noteTitleTemplate: "AI summary: {{project.name}}",
    noteFolderId: "",
    emailToTemplate: "",
    emailSubjectTemplate: "Mindavio update: {{task.title}}",
    emailBodyTemplate: "A Mindavio automation noticed {{event.type}} for {{task.title}}.",
    promptTemplate: "Summarize this workspace event into a practical next step.",
    taskPriority: "none",
    ...overrides,
  };
}

function createStepsFromTemplate(template: AutomationTemplateDefinition) {
  const seeded = template.steps.slice(0, MAX_AUTOMATION_STEPS).map((step) =>
    createStepDraft({
      enabled: true,
      actionType: step.actionType,
      taskTitleTemplate: step.taskTitleTemplate || "Follow up: {{task.title}}",
      taskDescriptionTemplate:
        step.taskDescriptionTemplate || 'Generated by automation from {{event.type}}.',
      assigneeId: step.assigneeId || "",
      reviewerId: step.reviewerId || "",
      noteTitleTemplate: step.noteTitleTemplate || "AI summary: {{project.name}}",
      noteContentTemplate:
        step.noteContentTemplate || 'Captured by automation from {{event.type}}.',
      noteFolderId: step.noteFolderId || "",
      emailToTemplate: step.emailToTemplate || "",
      emailSubjectTemplate:
        step.emailSubjectTemplate || "Mindavio update: {{task.title}}",
      emailBodyTemplate:
        step.emailBodyTemplate ||
        "A Mindavio automation noticed {{event.type}} for {{task.title}}.",
      promptTemplate:
        step.promptTemplate || "Summarize this workspace event into a practical next step.",
      taskPriority: step.taskPriority || "none",
    })
  );

  while (seeded.length < MAX_AUTOMATION_STEPS) {
    seeded.push(createStepDraft());
  }

  return seeded;
}

function getRuleSteps(rule: AutomationRule) {
  if (Array.isArray(rule.steps) && rule.steps.length > 0) {
    return rule.steps;
  }

  return [
    {
      id: "step_1",
      action_type: rule.action_type,
      action_config: rule.action_config,
    },
  ] as AutomationStep[];
}

function summarizeConditions(rule: AutomationRule) {
  const parts: string[] = [];
  const { conditions } = rule;

  if (conditions.title_contains) parts.push(`title contains "${conditions.title_contains}"`);
  if (conditions.task_status_is) parts.push(`task status is ${conditions.task_status_is}`);
  if (conditions.task_status_changed_to) {
    parts.push(`task status changes to ${conditions.task_status_changed_to}`);
  }
  if (conditions.task_priority_is) parts.push(`task priority is ${conditions.task_priority_is}`);
  if (conditions.project_health_is) parts.push(`project health is ${conditions.project_health_is}`);
  if (conditions.task_deadline_state) {
    parts.push(`deadline is ${conditions.task_deadline_state.replaceAll("_", " ")}`);
  }
  if (conditions.task_tag_id) parts.push("task tag is selected");
  if (conditions.project_id) parts.push("project is selected");
  if (conditions.goal_id) parts.push("goal is selected");
  if (conditions.assignee_id) parts.push("assignee is selected");
  if (conditions.reviewer_id) parts.push("reviewer is selected");

  return parts.length > 0 ? parts.join(" • ") : "No extra filters";
}

function summarizeTrigger(rule: AutomationRule) {
  if (rule.trigger_mode === "schedule") {
    const weekday =
      rule.schedule_frequency === "weekly" && typeof rule.schedule_day_of_week === "number"
        ? WEEKDAY_OPTIONS.find((option) => option.value === rule.schedule_day_of_week)?.label
        : null;
    return [
      rule.schedule_frequency === "weekly" ? "Weekly" : "Daily",
      weekday,
      rule.schedule_time,
      rule.schedule_timezone,
    ]
      .filter(Boolean)
      .join(" • ");
  }

  return rule.trigger_event;
}

function summarizeStep(step: AutomationStep, connectionNameById: Map<string, string>) {
  if (step.action_config.connection_id) {
    return `${getAutomationActionLabel(step.action_type)} • ${
      connectionNameById.get(step.action_config.connection_id) || "Selected connection"
    }`;
  }

  if (step.action_type === "ai_create_task" || step.action_type === "ai_create_note") {
    return `${getAutomationActionLabel(step.action_type)} • prompt-based`;
  }

  if (step.action_type === "create_note") {
    return `${getAutomationActionLabel(step.action_type)} • workspace note`;
  }

  return getAutomationActionLabel(step.action_type);
}

function formatIntegrationLabel(value: string) {
  return value
    .split("_")
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");
}

function buildActionConfig(step: StepDraft): AutomationActionConfig {
  if (step.actionType === "create_task") {
    return {
      task_title_template: step.taskTitleTemplate || null,
      task_description_template: step.taskDescriptionTemplate || null,
      assignee_id: step.assigneeId || null,
      reviewer_id: step.reviewerId || null,
      task_priority: step.taskPriority,
    };
  }

  if (step.actionType === "create_note") {
    return {
      note_title_template: step.noteTitleTemplate || null,
      note_content_template: step.noteContentTemplate || null,
      note_folder_id: step.noteFolderId || null,
    };
  }

  if (step.actionType === "create_gmail_draft") {
    return {
      connection_id: step.connectionId || null,
      email_to_template: step.emailToTemplate || null,
      email_subject_template: step.emailSubjectTemplate || null,
      email_body_template: step.emailBodyTemplate || null,
    };
  }

  if (step.actionType === "ai_create_task") {
    return {
      task_title_template: step.taskTitleTemplate || null,
      prompt_template: step.promptTemplate || null,
      assignee_id: step.assigneeId || null,
      reviewer_id: step.reviewerId || null,
      task_priority: step.taskPriority,
    };
  }

  if (step.actionType === "ai_create_note") {
    return {
      note_title_template: step.noteTitleTemplate || null,
      prompt_template: step.promptTemplate || null,
    };
  }

  return {
    connection_id: step.connectionId || null,
  };
}

function StepCard(props: {
  index: number;
  step: StepDraft;
  onChange: (patch: Partial<StepDraft>) => void;
  onRemove?: () => void;
  connectionOptions: Array<{ id: string; name: string }>;
  memberOptions: Array<{ id: string; name: string }>;
  folderOptions: Array<{ id: string; name: string }>;
}) {
  const { index, step, onChange, onRemove, connectionOptions, memberOptions, folderOptions } = props;
  const isAi = step.actionType === "ai_create_task" || step.actionType === "ai_create_note";
  const isTaskAction = step.actionType === "create_task" || step.actionType === "ai_create_task";
  const isNoteAction = step.actionType === "create_note" || step.actionType === "ai_create_note";
  const isGmailDraftAction = step.actionType === "create_gmail_draft";
  const needsConnection =
    step.actionType === "send_slack" ||
    step.actionType === "send_telegram" ||
    step.actionType === "send_google_sheets" ||
    step.actionType === "send_notion" ||
    step.actionType === "create_gmail_draft";

  return (
    <div className="rounded-xl bg-white/[0.03] ring-1 ring-white/[0.07] p-4 space-y-4 relative overflow-hidden">
      {/* Step number accent */}
      <div className="absolute top-0 left-0 w-1 h-full rounded-l-xl bg-gradient-to-b from-indigo-500/60 to-violet-500/40" />
      <div className="flex items-center justify-between gap-3 pl-3">
        <div className="flex items-center gap-3">
          <div className="flex items-center justify-center w-7 h-7 rounded-lg bg-gradient-to-br from-indigo-500/20 to-violet-500/10 ring-1 ring-indigo-500/30 shrink-0">
            <span className="text-xs font-bold text-indigo-400">{index + 1}</span>
          </div>
          <div>
            <p className="text-sm font-semibold text-gray-200">Step {index + 1}</p>
            <p className="text-xs text-gray-500">
              {AUTOMATION_ACTION_OPTIONS.find((option) => option.value === step.actionType)?.description}
            </p>
          </div>
        </div>
        {onRemove && (
          <Button variant="outline" size="sm" onClick={onRemove} className="border-white/[0.08] bg-white/[0.03] hover:bg-white/[0.06] text-gray-400 hover:text-gray-200">
            <Trash2 className="h-4 w-4" />
            Remove
          </Button>
        )}
      </div>

      <div className="space-y-2 pl-3">
        <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Action type</Label>
        <Select
          value={step.actionType}
          onChange={(event) =>
            onChange({
              actionType: event.target.value as AutomationActionType,
              connectionId: "",
            })
          }
        >
          {AUTOMATION_ACTION_OPTIONS.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </Select>
      </div>

      {needsConnection && (
        <div className="space-y-2 pl-3">
          <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Connection</Label>
          <Select
            value={step.connectionId}
            onChange={(event) => onChange({ connectionId: event.target.value })}
          >
            <option value="">Select a connection</option>
            {connectionOptions.map((option) => (
              <option key={option.id} value={option.id}>
                {option.name}
              </option>
            ))}
          </Select>
        </div>
      )}

      {isAi && (
        <div className="space-y-2 pl-3">
          <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">AI prompt</Label>
          <Textarea
            value={step.promptTemplate}
            onChange={(event) => onChange({ promptTemplate: event.target.value })}
            rows={4}
            placeholder="Summarize this event and suggest the next practical step."
          />
          <p className="text-xs text-gray-500">
            Supports tokens like{" "}
            <code className="px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-400 ring-1 ring-indigo-500/20 font-mono text-[10px]">{"{{task.title}}"}</code>,{" "}
            <code className="px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-400 ring-1 ring-indigo-500/20 font-mono text-[10px]">{"{{project.name}}"}</code>,{" "}
            <code className="px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-400 ring-1 ring-indigo-500/20 font-mono text-[10px]">{"{{note.title}}"}</code>,{" "}
            <code className="px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-400 ring-1 ring-indigo-500/20 font-mono text-[10px]">{"{{event.type}}"}</code>, and{" "}
            <code className="px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-400 ring-1 ring-indigo-500/20 font-mono text-[10px]">{"{{schedule.frequency}}"}</code>.
          </p>
        </div>
      )}

      {isTaskAction && (
        <div className="grid gap-4 md:grid-cols-2 pl-3">
          <div className="space-y-2 md:col-span-2">
            <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">{isAi ? "Task title template" : "Follow-up task title"}</Label>
            <Input
              value={step.taskTitleTemplate}
              onChange={(event) => onChange({ taskTitleTemplate: event.target.value })}
              placeholder="Follow up: {{task.title}}"
            />
          </div>
          {!isAi && (
            <div className="space-y-2 md:col-span-2">
              <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Task description template</Label>
              <Textarea
                value={step.taskDescriptionTemplate}
                onChange={(event) => onChange({ taskDescriptionTemplate: event.target.value })}
                rows={3}
                placeholder='Generated by automation from {{event.type}}.'
              />
            </div>
          )}
          <div className="space-y-2">
            <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Priority</Label>
            <Select
              value={step.taskPriority}
              onChange={(event) => onChange({ taskPriority: event.target.value as Priority })}
            >
              {PRIORITY_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </Select>
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Assign to</Label>
            <Select
              value={step.assigneeId}
              onChange={(event) => onChange({ assigneeId: event.target.value })}
              disabled={memberOptions.length === 0}
            >
              <option value="">
                {memberOptions.length === 0 ? "Available in team workspace" : "No assignee"}
              </option>
              {memberOptions.map((option) => (
                <option key={option.id} value={option.id}>
                  {option.name}
                </option>
              ))}
            </Select>
          </div>
          {!isAi && (
            <div className="space-y-2">
              <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Reviewer</Label>
              <Select
                value={step.reviewerId}
                onChange={(event) => onChange({ reviewerId: event.target.value })}
                disabled={memberOptions.length === 0}
              >
                <option value="">
                  {memberOptions.length === 0 ? "Available in team workspace" : "No reviewer"}
                </option>
                {memberOptions.map((option) => (
                  <option key={option.id} value={option.id}>
                    {option.name}
                  </option>
                ))}
              </Select>
            </div>
          )}
        </div>
      )}

      {isNoteAction && (
        <div className="grid gap-4 pl-3">
          <div className="space-y-2">
            <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Note title template</Label>
            <Input
              value={step.noteTitleTemplate}
              onChange={(event) => onChange({ noteTitleTemplate: event.target.value })}
              placeholder="AI summary: {{project.name}}"
            />
          </div>
          {step.actionType === "create_note" && (
            <div className="space-y-2">
              <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Note content template</Label>
              <Textarea
                value={step.noteContentTemplate}
                onChange={(event) => onChange({ noteContentTemplate: event.target.value })}
                rows={4}
                placeholder='Captured by automation from {{event.type}}.'
              />
            </div>
          )}
          {step.actionType === "create_note" && (
            <div className="space-y-2">
              <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Folder</Label>
              <Select
                value={step.noteFolderId}
                onChange={(event) => onChange({ noteFolderId: event.target.value })}
              >
                <option value="">No folder</option>
                {folderOptions.map((option) => (
                  <option key={option.id} value={option.id}>
                    {option.name}
                  </option>
                ))}
              </Select>
            </div>
          )}
        </div>
      )}

      {isGmailDraftAction && (
        <div className="grid gap-4 pl-3">
          <div className="space-y-2">
            <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">To template</Label>
            <Input
              value={step.emailToTemplate}
              onChange={(event) => onChange({ emailToTemplate: event.target.value })}
              placeholder="client@example.com or {{task.assignee_email}}"
            />
            <p className="text-xs text-gray-500">
              Leave empty to draft to the connected Gmail address.
            </p>
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Subject template</Label>
            <Input
              value={step.emailSubjectTemplate}
              onChange={(event) => onChange({ emailSubjectTemplate: event.target.value })}
              placeholder="Mindavio update: {{task.title}}"
            />
          </div>
          <div className="space-y-2">
            <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Body template</Label>
            <Textarea
              value={step.emailBodyTemplate}
              onChange={(event) => onChange({ emailBodyTemplate: event.target.value })}
              rows={5}
              placeholder="A Mindavio automation noticed {{event.type}} for {{task.title}}."
            />
          </div>
        </div>
      )}
    </div>
  );
}

export default function AutomationsPage() {
  const { activeTeam, activeMembers } = useTeams();
  const { rules, runs, loading, createAutomation, updateAutomation, deleteAutomation, refetch } =
    useAutomations();
  const { slackConnections, telegramConnections, sheetsConnections, notionConnections, gmailConnections } =
    useIntegrations();
  const { folders } = useNoteFolders();
  const { projects } = useProjects();
  const { goals } = useGoals();
  const { tags } = useTags();

  const workspaceLabel = activeTeam?.name || "Personal workspace";
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [triggerMode, setTriggerMode] = useState<"event" | "schedule">("event");
  const [triggerEvent, setTriggerEvent] = useState<AutomationRule["trigger_event"]>("task.updated");
  const [scheduleFrequency, setScheduleFrequency] = useState<"daily" | "weekly">("daily");
  const [scheduleTime, setScheduleTime] = useState("09:00");
  const [scheduleDayOfWeek, setScheduleDayOfWeek] = useState("1");
  const [scheduleTimezone, setScheduleTimezone] = useState("UTC");
  const [titleContains, setTitleContains] = useState("");
  const [taskStatusIs, setTaskStatusIs] = useState("");
  const [taskStatusChangedTo, setTaskStatusChangedTo] = useState("");
  const [taskPriorityIs, setTaskPriorityIs] = useState("");
  const [projectHealthIs, setProjectHealthIs] = useState("");
  const [taskDeadlineState, setTaskDeadlineState] = useState("");
  const [taskTagId, setTaskTagId] = useState("");
  const [projectId, setProjectId] = useState("");
  const [goalId, setGoalId] = useState("");
  const [assigneeId, setAssigneeId] = useState("");
  const [reviewerId, setReviewerId] = useState("");
  const [steps, setSteps] = useState<StepDraft[]>([
    createStepDraft({ enabled: true }),
    createStepDraft(),
    createStepDraft(),
  ]);
  const [submitting, setSubmitting] = useState(false);
  const [showTemplates, setShowTemplates] = useState(false);
  const [feedback, setFeedback] = useState<string | null>(null);

  useEffect(() => {
    try {
      const browserTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
      if (browserTimeZone) {
        setScheduleTimezone(browserTimeZone);
      }
    } catch {}
  }, []);

  const activeRuleCount = useMemo(
    () => rules.filter((rule) => rule.is_active).length,
    [rules]
  );
  const failedRunCount = useMemo(
    () => runs.filter((run) => !run.success).length,
    [runs]
  );

  const recentRunsByRule = useMemo(() => {
    const next: Record<string, typeof runs> = {};

    for (const run of runs) {
      const list = next[run.rule_id] || [];
      if (list.length < 4) {
        list.push(run);
      }
      next[run.rule_id] = list;
    }

    return next;
  }, [runs]);

  const connectionNameById = useMemo(() => {
    const entries: Array<[string, string]> = [
      ...slackConnections,
      ...telegramConnections,
      ...sheetsConnections,
      ...notionConnections,
      ...gmailConnections,
    ].map((connection) => [connection.id, connection.name]);
    return new Map(entries);
  }, [gmailConnections, notionConnections, sheetsConnections, slackConnections, telegramConnections]);

  const memberOptions = useMemo(
    () =>
      activeMembers.map((member) => ({
        id: member.user_id,
        name: member.profile?.full_name || member.profile?.email || member.user_id,
      })),
    [activeMembers]
  );

  const folderOptions = useMemo(
    () =>
      folders.map((folder) => ({
        id: folder.id,
        name: folder.name,
      })),
    [folders]
  );

  function getConnectionOptions(actionType: AutomationActionType) {
    if (actionType === "send_slack") {
      return slackConnections
        .filter((connection) => connection.is_active)
        .map((connection) => ({ id: connection.id, name: connection.name }));
    }

    if (actionType === "send_telegram") {
      return telegramConnections
        .filter((connection) => connection.is_active)
        .map((connection) => ({ id: connection.id, name: connection.name }));
    }

    if (actionType === "send_google_sheets") {
      return sheetsConnections
        .filter((connection) => connection.is_active)
        .map((connection) => ({ id: connection.id, name: connection.name }));
    }

    if (actionType === "send_notion") {
      return notionConnections
        .filter((connection) => connection.is_active)
        .map((connection) => ({ id: connection.id, name: connection.name }));
    }

    if (actionType === "create_gmail_draft") {
      return gmailConnections
        .filter((connection) => connection.is_active)
        .map((connection) => ({ id: connection.id, name: connection.name }));
    }

    return [];
  }

  function updateStep(index: number, patch: Partial<StepDraft>) {
    setSteps((prev) =>
      prev.map((step, currentIndex) =>
        currentIndex === index ? { ...step, ...patch } : step
      )
    );
  }

  function enableNextStep() {
    const nextIndex = steps.findIndex((step, index) => index > 0 && !step.enabled);
    if (nextIndex >= 0) {
      updateStep(nextIndex, { enabled: true });
    }
  }

  function removeStep(index: number) {
    setSteps((prev) =>
      prev.map((step, currentIndex) =>
        currentIndex === index ? createStepDraft() : step
      )
    );
  }

  function buildStepsPayload() {
    return steps
      .map((step, index) => {
        if (!step.enabled) return null;

        return {
          id: `step_${index + 1}`,
          action_type: step.actionType,
          action_config: buildActionConfig(step),
        } satisfies AutomationStep;
      })
      .filter((step): step is AutomationStep => Boolean(step));
  }

  function applyTemplate(template: AutomationTemplateDefinition) {
    setName(template.name);
    setDescription(template.description);
    setTriggerMode(template.triggerMode);
    setTriggerEvent(
      template.triggerMode === "event"
        ? template.triggerEvent || "task.updated"
        : "schedule.triggered"
    );
    setScheduleFrequency(template.scheduleFrequency || "daily");
    setScheduleTime(template.scheduleTime || "09:00");
    setScheduleDayOfWeek(String(template.scheduleDayOfWeek ?? 1));
    setTitleContains(template.conditions.title_contains || "");
    setTaskStatusIs(template.conditions.task_status_is || "");
    setTaskStatusChangedTo(template.conditions.task_status_changed_to || "");
    setTaskPriorityIs(template.conditions.task_priority_is || "");
    setProjectHealthIs(template.conditions.project_health_is || "");
    setTaskDeadlineState(template.conditions.task_deadline_state || "");
    setTaskTagId(template.conditions.task_tag_id || "");
    setProjectId(template.conditions.project_id || "");
    setGoalId(template.conditions.goal_id || "");
    setAssigneeId(template.conditions.assignee_id || "");
    setReviewerId(template.conditions.reviewer_id || "");
    setSteps(createStepsFromTemplate(template));
    setFeedback(`Template "${template.name}" loaded. Finish connections and adjust anything you want.`);
  }

  async function handleCreateAutomation() {
    setSubmitting(true);
    setFeedback(null);

    try {
      const nextSteps = buildStepsPayload();
      await createAutomation({
        name: name || "New automation",
        description,
        triggerMode,
        triggerEvent: triggerMode === "event" ? triggerEvent : undefined,
        scheduleFrequency: triggerMode === "schedule" ? scheduleFrequency : null,
        scheduleTime: triggerMode === "schedule" ? scheduleTime : null,
        scheduleDayOfWeek:
          triggerMode === "schedule" && scheduleFrequency === "weekly"
            ? Number(scheduleDayOfWeek)
            : null,
        scheduleTimezone: triggerMode === "schedule" ? scheduleTimezone : null,
        conditions: {
          title_contains: titleContains || null,
          task_status_is: (taskStatusIs as TaskStatus) || null,
          task_status_changed_to: (taskStatusChangedTo as TaskStatus) || null,
          task_priority_is: (taskPriorityIs as Priority) || null,
          project_health_is: (projectHealthIs as ProjectHealth) || null,
          task_deadline_state: (taskDeadlineState as AutomationTaskDeadlineState) || null,
          task_tag_id: taskTagId || null,
          project_id: projectId || null,
          goal_id: goalId || null,
          assignee_id: assigneeId || null,
          reviewer_id: reviewerId || null,
        },
        actionType: nextSteps[0]?.action_type,
        actionConfig: nextSteps[0]?.action_config,
        steps: nextSteps,
      });

      setName("");
      setDescription("");
      setTriggerMode("event");
      setTriggerEvent("task.updated");
      setScheduleFrequency("daily");
      setScheduleTime("09:00");
      setScheduleDayOfWeek("1");
      setTitleContains("");
      setTaskStatusIs("");
      setTaskStatusChangedTo("");
      setTaskPriorityIs("");
      setProjectHealthIs("");
      setTaskDeadlineState("");
      setTaskTagId("");
      setProjectId("");
      setGoalId("");
      setAssigneeId("");
      setReviewerId("");
      setSteps([
        createStepDraft({ enabled: true }),
        createStepDraft(),
        createStepDraft(),
      ]);
      setFeedback("Automation created.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Automation could not be created.");
    } finally {
      setSubmitting(false);
    }
  }

  async function handleToggleRule(rule: AutomationRule) {
    try {
      await updateAutomation(rule.id, { isActive: !rule.is_active });
      setFeedback(rule.is_active ? "Automation paused." : "Automation resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Automation could not be updated.");
    }
  }

  async function handleDeleteRule(id: string) {
    try {
      await deleteAutomation(id);
      setFeedback("Automation deleted.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Automation could not be deleted.");
    }
  }

  const visibleSteps = steps.filter((step) => step.enabled).length;

  return (
    <div className="min-h-screen bg-gradient-to-b from-[#1e2028] to-[#1a1c22]">
      <div className="mx-auto max-w-[1200px] px-6 py-8 space-y-6">
        {/* Header */}
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <div className="flex items-center gap-3 mb-1.5">
              <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-indigo-500/20 to-violet-500/10 flex items-center justify-center ring-1 ring-indigo-500/25 shadow-lg shadow-indigo-500/10">
                <Workflow className="h-4.5 w-4.5 text-indigo-400" />
              </div>
              <h1 className="text-[22px] font-bold tracking-tight bg-gradient-to-r from-white to-gray-400 bg-clip-text text-transparent">
                Automations
              </h1>
            </div>
            <p className="text-[13px] text-gray-500 ml-[48px]">
              Event-basierte, geplante und AI-gestützte Workflows für{" "}
              <span className="font-semibold text-gray-300">{workspaceLabel}</span>.
            </p>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={() => void refetch()}
            className="rounded-lg border-white/[0.08] bg-white/[0.03] hover:bg-white/[0.06] text-gray-400 hover:text-gray-200 transition-colors"
          >
            <RefreshCcw className="h-3.5 w-3.5" />
            Aktualisieren
          </Button>
        </div>

        {feedback && (
          <div className="rounded-xl bg-indigo-500/10 ring-1 ring-indigo-500/20 px-4 py-3 text-[13px] text-indigo-300">
            {feedback}
          </div>
        )}

        {/* Stats */}
        <div className="grid gap-4 md:grid-cols-3">
          <div className="rounded-2xl bg-white/[0.03] ring-1 ring-white/[0.06] p-5 relative overflow-hidden group hover:bg-white/[0.04] transition-colors">
            <div className="absolute inset-0 bg-gradient-to-br from-indigo-500/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
            <p className="text-[10px] font-semibold uppercase tracking-widest text-gray-500">Aktive Regeln</p>
            <p className="mt-2 text-3xl font-bold tabular-nums bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
              {loading ? "–" : activeRuleCount}
            </p>
          </div>
          <div className="rounded-2xl bg-white/[0.03] ring-1 ring-white/[0.06] p-5 relative overflow-hidden group hover:bg-white/[0.04] transition-colors">
            <div className="absolute inset-0 bg-gradient-to-br from-violet-500/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
            <p className="text-[10px] font-semibold uppercase tracking-widest text-gray-500">Gesamt</p>
            <p className="mt-2 text-3xl font-bold tabular-nums bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
              {loading ? "–" : rules.length}
            </p>
          </div>
          <div className="rounded-2xl bg-white/[0.03] ring-1 ring-white/[0.06] p-5 relative overflow-hidden group hover:bg-white/[0.04] transition-colors">
            <div className={`absolute inset-0 bg-gradient-to-br ${failedRunCount > 0 ? "from-red-500/5" : "from-emerald-500/5"} to-transparent opacity-0 group-hover:opacity-100 transition-opacity`} />
            <p className="text-[10px] font-semibold uppercase tracking-widest text-gray-500">Fehlgeschlagen</p>
            <p className={`mt-2 text-3xl font-bold tabular-nums ${failedRunCount > 0 ? "text-red-400" : "bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent"}`}>
              {loading ? "–" : failedRunCount}
            </p>
          </div>
        </div>

        <div className="grid gap-6 xl:grid-cols-[1.2fr,0.8fr]">
          {/* Automation Builder */}
          <Card className="rounded-2xl bg-white/[0.03] ring-1 ring-white/[0.06] border-0 shadow-none">
            <CardHeader className="pb-4">
              <CardTitle className="flex items-center gap-2.5 text-[15px] font-semibold text-gray-100">
                <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-indigo-500/20 to-violet-500/10 flex items-center justify-center ring-1 ring-indigo-500/25">
                  <Zap className="h-3.5 w-3.5 text-indigo-400" />
                </div>
                Automation erstellen
              </CardTitle>
              <CardDescription className="text-[12px] text-gray-500 mt-1">
                Wähle ob die Regel auf Workspace-Events oder einen Zeitplan reagiert, dann verkette bis zu drei Schritte.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Templates toggle */}
              <div>
                <button
                  onClick={() => setShowTemplates((v) => !v)}
                  className="flex w-full items-center justify-between rounded-xl bg-gradient-to-r from-indigo-500/[0.07] to-violet-500/[0.04] px-4 py-3 ring-1 ring-indigo-500/15 transition-all hover:ring-indigo-500/30"
                >
                  <div className="flex items-center gap-3">
                    <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-gradient-to-br from-indigo-500/20 to-violet-500/10 ring-1 ring-indigo-500/25">
                      <Wand2 className="h-4 w-4 text-indigo-400" />
                    </div>
                    <div className="text-left">
                      <p className="text-sm font-semibold text-gray-200">Vorlagen</p>
                      <p className="text-[11px] text-gray-500">{AUTOMATION_TEMPLATES.length} fertige Flows als Startpunkt</p>
                    </div>
                  </div>
                  <svg className={`h-4 w-4 text-gray-500 transition-transform duration-200 ${showTemplates ? "rotate-180" : ""}`} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6" /></svg>
                </button>

                {showTemplates && (
                  <div className="mt-3 grid gap-3 md:grid-cols-2">
                    {AUTOMATION_TEMPLATES.map((template) => (
                      <div
                        key={template.id}
                        className="rounded-xl bg-white/[0.02] ring-1 ring-white/[0.06] p-4 space-y-3 hover:bg-white/[0.04] hover:ring-indigo-500/20 transition-all cursor-pointer group"
                      >
                        <div className="space-y-1.5">
                          <div className="flex flex-wrap items-center gap-2">
                            <p className="text-sm font-semibold text-gray-200 group-hover:text-white transition-colors">{template.name}</p>
                            <span className="px-2 py-0.5 rounded-full text-[10px] font-medium bg-indigo-500/15 text-indigo-400 ring-1 ring-indigo-500/20">
                              {template.category}
                            </span>
                            <span className="px-2 py-0.5 rounded-full text-[10px] font-medium bg-violet-500/15 text-violet-400 ring-1 ring-violet-500/20">
                              {template.triggerMode === "schedule" ? "Geplant" : "Event"}
                            </span>
                          </div>
                          <p className="text-xs text-gray-500">{template.description}</p>
                        </div>
                        {template.requiredIntegrations.length > 0 && (
                          <div className="flex flex-wrap gap-1.5">
                            {template.requiredIntegrations.map((integration) => (
                              <span
                                key={`${template.id}-${integration}`}
                                className="px-2 py-0.5 rounded text-[10px] font-medium bg-white/[0.05] text-gray-400 ring-1 ring-white/[0.08]"
                              >
                                {formatIntegrationLabel(integration)}
                              </span>
                            ))}
                          </div>
                        )}
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => { applyTemplate(template); setShowTemplates(false); }}
                          className="border-white/[0.08] bg-white/[0.03] hover:bg-gradient-to-r hover:from-indigo-500/10 hover:to-violet-500/5 hover:border-indigo-500/30 text-gray-400 hover:text-indigo-300 transition-all"
                        >
                          Vorlage verwenden
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* Divider */}
              <div className="border-t border-white/[0.06]" />

              {/* Name + Trigger mode */}
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Name</Label>
                  <Input
                    value={name}
                    onChange={(event) => setName(event.target.value)}
                    placeholder="Done tasks -> Telegram + AI note"
                  />
                </div>
                <div className="space-y-2">
                  <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Trigger mode</Label>
                  <Select
                    value={triggerMode}
                    onChange={(event) =>
                      setTriggerMode(event.target.value as "event" | "schedule")
                    }
                  >
                    <option value="event">Workspace event</option>
                    <option value="schedule">Scheduled</option>
                  </Select>
                </div>
              </div>

              <div className="space-y-2">
                <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Description</Label>
                <Textarea
                  value={description}
                  onChange={(event) => setDescription(event.target.value)}
                  placeholder="Optional note for your future self."
                  rows={3}
                />
              </div>

              {triggerMode === "event" ? (
                <div className="space-y-2">
                  <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Trigger event</Label>
                  <Select
                    value={triggerEvent}
                    onChange={(event) =>
                      setTriggerEvent(event.target.value as AutomationRule["trigger_event"])
                    }
                  >
                    {AUTOMATION_TRIGGER_OPTIONS.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </Select>
                </div>
              ) : (
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Frequency</Label>
                    <Select
                      value={scheduleFrequency}
                      onChange={(event) =>
                        setScheduleFrequency(event.target.value as "daily" | "weekly")
                      }
                    >
                      <option value="daily">Daily</option>
                      <option value="weekly">Weekly</option>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Time</Label>
                    <Input
                      type="time"
                      value={scheduleTime}
                      onChange={(event) => setScheduleTime(event.target.value)}
                    />
                  </div>
                  {scheduleFrequency === "weekly" && (
                    <div className="space-y-2">
                      <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Day of week</Label>
                      <Select
                        value={scheduleDayOfWeek}
                        onChange={(event) => setScheduleDayOfWeek(event.target.value)}
                      >
                        {WEEKDAY_OPTIONS.map((option) => (
                          <option key={option.value} value={String(option.value)}>
                            {option.label}
                          </option>
                        ))}
                      </Select>
                    </div>
                  )}
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Timezone</Label>
                    <Input
                      value={scheduleTimezone}
                      onChange={(event) => setScheduleTimezone(event.target.value)}
                      placeholder="Europe/Berlin"
                    />
                  </div>
                </div>
              )}

              {/* Divider */}
              <div className="border-t border-white/[0.06]" />

              {/* Optional filters */}
              <div className="space-y-3">
                <div>
                  <h2 className="text-sm font-semibold text-gray-200">Optional filters</h2>
                  <p className="text-xs text-gray-500 mt-0.5">
                    These are especially useful for event-based rules. Scheduled rules can usually
                    leave them empty.
                  </p>
                </div>
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Title contains</Label>
                    <Input
                      value={titleContains}
                      onChange={(event) => setTitleContains(event.target.value)}
                      placeholder="launch, invoice, urgent"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Task status is</Label>
                    <Select
                      value={taskStatusIs}
                      onChange={(event) => setTaskStatusIs(event.target.value)}
                    >
                      <option value="">Any status</option>
                      {TASK_STATUS_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Task status changes to</Label>
                    <Select
                      value={taskStatusChangedTo}
                      onChange={(event) => setTaskStatusChangedTo(event.target.value)}
                    >
                      <option value="">No change filter</option>
                      {TASK_STATUS_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Task priority is</Label>
                    <Select
                      value={taskPriorityIs}
                      onChange={(event) => setTaskPriorityIs(event.target.value)}
                    >
                      <option value="">Any priority</option>
                      {PRIORITY_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Deadline state</Label>
                    <Select
                      value={taskDeadlineState}
                      onChange={(event) => setTaskDeadlineState(event.target.value)}
                    >
                      <option value="">Any deadline state</option>
                      {TASK_DEADLINE_STATE_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Task tag is</Label>
                    <Select value={taskTagId} onChange={(event) => setTaskTagId(event.target.value)}>
                      <option value="">Any tag</option>
                      {tags.map((tag) => (
                        <option key={tag.id} value={tag.id}>
                          {tag.name}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="space-y-2 md:col-span-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Project health is</Label>
                    <Select
                      value={projectHealthIs}
                      onChange={(event) => setProjectHealthIs(event.target.value)}
                    >
                      <option value="">Any project health</option>
                      {PROJECT_HEALTH_OPTIONS.map((option) => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Project is</Label>
                    <Select value={projectId} onChange={(event) => setProjectId(event.target.value)}>
                      <option value="">Any project</option>
                      {projects.map((project) => (
                        <option key={project.id} value={project.id}>
                          {project.name}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Goal is</Label>
                    <Select value={goalId} onChange={(event) => setGoalId(event.target.value)}>
                      <option value="">Any goal</option>
                      {goals.map((goal) => (
                        <option key={goal.id} value={goal.id}>
                          {goal.title}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Assignee is</Label>
                    <Select
                      value={assigneeId}
                      onChange={(event) => setAssigneeId(event.target.value)}
                      disabled={activeMembers.length === 0}
                    >
                      <option value="">
                        {activeMembers.length === 0 ? "Available in team workspace" : "Any assignee"}
                      </option>
                      {activeMembers.map((member) => (
                        <option key={member.user_id} value={member.user_id}>
                          {member.profile?.full_name || member.profile?.email || member.user_id}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-gray-500">Reviewer is</Label>
                    <Select
                      value={reviewerId}
                      onChange={(event) => setReviewerId(event.target.value)}
                      disabled={activeMembers.length === 0}
                    >
                      <option value="">
                        {activeMembers.length === 0 ? "Available in team workspace" : "Any reviewer"}
                      </option>
                      {activeMembers.map((member) => (
                        <option key={member.user_id} value={member.user_id}>
                          {member.profile?.full_name || member.profile?.email || member.user_id}
                        </option>
                      ))}
                    </Select>
                  </div>
                </div>
              </div>

              {/* Divider */}
              <div className="border-t border-white/[0.06]" />

              {/* Flow steps */}
              <div className="space-y-3">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <h2 className="text-sm font-semibold text-gray-200">Flow steps</h2>
                    <p className="text-xs text-gray-500 mt-0.5">
                      Chain multiple actions in order, including AI-generated tasks or notes.
                    </p>
                  </div>
                  {visibleSteps < MAX_AUTOMATION_STEPS && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={enableNextStep}
                      className="border-indigo-500/30 bg-indigo-500/10 hover:bg-indigo-500/20 text-indigo-400 hover:text-indigo-300 transition-all"
                    >
                      <Plus className="h-4 w-4" />
                      Add step
                    </Button>
                  )}
                </div>
                <div className="space-y-3">
                  {steps.map((step, index) =>
                    step.enabled ? (
                      <StepCard
                        key={`step_${index + 1}`}
                        index={index}
                        step={step}
                        onChange={(patch) => updateStep(index, patch)}
                        onRemove={index === 0 ? undefined : () => removeStep(index)}
                        connectionOptions={getConnectionOptions(step.actionType)}
                        memberOptions={memberOptions}
                        folderOptions={folderOptions}
                      />
                    ) : null
                  )}
                </div>
              </div>

              <Button
                onClick={() => void handleCreateAutomation()}
                disabled={submitting}
                className="w-full bg-gradient-to-r from-indigo-500 to-violet-600 hover:from-indigo-400 hover:to-violet-500 text-white font-semibold shadow-lg shadow-indigo-500/30 border-0 transition-all"
              >
                {submitting ? "Creating..." : "Create automation"}
              </Button>
            </CardContent>
          </Card>

          {/* Recent Runs panel */}
          <Card className="rounded-2xl bg-white/[0.03] ring-1 ring-white/[0.06] border-0 shadow-none">
            <CardHeader className="pb-4">
              <CardTitle className="text-[15px] font-semibold text-gray-100">Recent runs</CardTitle>
              <CardDescription className="text-[12px] text-gray-500 mt-1">
                The latest event-driven and scheduled executions in this workspace.
              </CardDescription>
            </CardHeader>
            <CardContent>
              {runs.length === 0 ? (
                <EmptyState
                  title="No runs yet"
                  description="As soon as a rule matches or a schedule becomes due, its executions will appear here."
                />
              ) : (
                <div className="space-y-2.5">
                  {runs.slice(0, 12).map((run) => {
                    const rule = rules.find((candidate) => candidate.id === run.rule_id);

                    return (
                      <div
                        key={run.id}
                        className={`rounded-xl ring-1 p-3 space-y-1.5 transition-colors ${
                          run.success
                            ? "bg-emerald-500/[0.05] ring-emerald-500/15 hover:bg-emerald-500/[0.08]"
                            : "bg-red-500/[0.05] ring-red-500/15 hover:bg-red-500/[0.08]"
                        }`}
                      >
                        <div className="flex items-center justify-between gap-3">
                          <div>
                            <p className="text-sm font-semibold text-gray-200">
                              {rule?.name || "Deleted automation"}
                            </p>
                            <p className="text-xs text-gray-500">
                              {run.trigger_mode === "schedule" ? "Scheduled" : run.trigger_event} •{" "}
                              {formatDate(run.created_at)}
                            </p>
                          </div>
                          <span
                            className={`px-2.5 py-1 rounded-full text-[10px] font-semibold ring-1 shrink-0 ${
                              run.success
                                ? "bg-emerald-500/15 text-emerald-400 ring-emerald-500/25"
                                : "bg-red-500/15 text-red-400 ring-red-500/25"
                            }`}
                          >
                            {run.success ? "Success" : "Failed"}
                          </span>
                        </div>
                        {run.result_summary && (
                          <p className="text-xs text-gray-500">{run.result_summary}</p>
                        )}
                        {run.error && <p className="text-xs text-red-400">{run.error}</p>}
                      </div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Rules list */}
        <Card className="rounded-2xl bg-white/[0.03] ring-1 ring-white/[0.06] border-0 shadow-none">
          <CardHeader className="pb-4">
            <CardTitle className="text-[15px] font-semibold text-gray-100">Rules</CardTitle>
            <CardDescription className="text-[12px] text-gray-500 mt-1">
              Pause, resume, and review your current automation flows.
            </CardDescription>
          </CardHeader>
          <CardContent>
            {rules.length === 0 ? (
              <EmptyState
                title="No automations yet"
                description="Create your first rule to turn repeated work into a reusable flow."
              />
            ) : (
              <div className="space-y-4">
                {rules.map((rule) => (
                  <div
                    key={rule.id}
                    className={`rounded-2xl ring-1 p-5 space-y-4 transition-all ${
                      rule.is_active
                        ? "bg-gradient-to-br from-indigo-500/[0.06] to-violet-500/[0.03] ring-indigo-500/20 hover:from-indigo-500/[0.08] hover:to-violet-500/[0.05]"
                        : "bg-white/[0.02] ring-white/[0.06] hover:bg-white/[0.03]"
                    }`}
                  >
                    <div className="flex flex-wrap items-start justify-between gap-3">
                      <div className="space-y-1.5">
                        <div className="flex items-center gap-2.5 flex-wrap">
                          <p className="font-semibold text-gray-100">{rule.name}</p>
                          <span
                            className={`px-2.5 py-0.5 rounded-full text-[10px] font-semibold ring-1 ${
                              rule.is_active
                                ? "bg-emerald-500/15 text-emerald-400 ring-emerald-500/25"
                                : "bg-gray-500/15 text-gray-400 ring-gray-500/20"
                            }`}
                          >
                            {rule.is_active ? "Active" : "Paused"}
                          </span>
                          <span className="px-2.5 py-0.5 rounded-full text-[10px] font-semibold bg-indigo-500/15 text-indigo-400 ring-1 ring-indigo-500/20">
                            {rule.trigger_mode === "schedule" ? "Scheduled" : "Event"}
                          </span>
                        </div>
                        <p className="text-sm text-gray-500">
                          {rule.description || "No description"}
                        </p>
                      </div>

                      <div className="flex items-center gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => void handleToggleRule(rule)}
                          className="border-white/[0.08] bg-white/[0.03] hover:bg-white/[0.06] text-gray-400 hover:text-gray-200 transition-colors"
                        >
                          {rule.is_active ? (
                            <PauseCircle className="h-4 w-4" />
                          ) : (
                            <PlayCircle className="h-4 w-4" />
                          )}
                          {rule.is_active ? "Pause" : "Resume"}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => void handleDeleteRule(rule.id)}
                          className="border-red-500/20 bg-red-500/[0.05] hover:bg-red-500/10 text-red-400/70 hover:text-red-400 transition-colors"
                        >
                          <Trash2 className="h-4 w-4" />
                          Delete
                        </Button>
                      </div>
                    </div>

                    <div className="grid gap-3 md:grid-cols-3">
                      <div className="rounded-xl bg-white/[0.03] ring-1 ring-white/[0.06] p-3">
                        <p className="text-[10px] uppercase tracking-widest font-semibold text-gray-500 mb-1.5">
                          Trigger
                        </p>
                        <p className="text-sm text-gray-300">{summarizeTrigger(rule)}</p>
                      </div>
                      <div className="rounded-xl bg-white/[0.03] ring-1 ring-white/[0.06] p-3">
                        <p className="text-[10px] uppercase tracking-widest font-semibold text-gray-500 mb-1.5">
                          Filters
                        </p>
                        <p className="text-sm text-gray-300">{summarizeConditions(rule)}</p>
                      </div>
                      <div className="rounded-xl bg-white/[0.03] ring-1 ring-white/[0.06] p-3">
                        <p className="text-[10px] uppercase tracking-widest font-semibold text-gray-500 mb-1.5">
                          Last run
                        </p>
                        <p className="text-sm text-gray-300">
                          {formatDate(rule.last_run_at)} • {rule.last_run_status || "Never run"}
                        </p>
                        {rule.last_error && (
                          <p className="mt-1 text-xs text-red-400">{rule.last_error}</p>
                        )}
                      </div>
                    </div>

                    <div className="space-y-2">
                      <p className="text-[10px] uppercase tracking-widest font-semibold text-gray-500">
                        Flow
                      </p>
                      <div className="grid gap-2.5 md:grid-cols-3">
                        {getRuleSteps(rule).map((step, index) => (
                          <div
                            key={step.id || `step_${index + 1}`}
                            className="rounded-xl bg-white/[0.02] ring-1 ring-white/[0.06] px-3 py-3 hover:bg-white/[0.04] transition-colors relative overflow-hidden"
                          >
                            <div className="absolute top-0 left-0 w-0.5 h-full bg-gradient-to-b from-indigo-500/50 to-violet-500/30 rounded-l-xl" />
                            <div className="flex items-center gap-2 pl-1.5">
                              <div className="flex items-center justify-center w-5 h-5 rounded bg-indigo-500/15 ring-1 ring-indigo-500/25 shrink-0">
                                {step.action_type.startsWith("ai_") ? (
                                  <Wand2 className="h-3 w-3 text-indigo-400" />
                                ) : (
                                  <Zap className="h-3 w-3 text-indigo-400" />
                                )}
                              </div>
                              <span className="text-xs font-semibold text-gray-400">Step {index + 1}</span>
                            </div>
                            <p className="mt-2 text-sm text-gray-400 pl-1.5">
                              {summarizeStep(step, connectionNameById)}
                            </p>
                          </div>
                        ))}
                      </div>
                    </div>

                    {(recentRunsByRule[rule.id] || []).length > 0 && (
                      <div className="space-y-2">
                        <p className="text-[10px] uppercase tracking-widest font-semibold text-gray-500">
                          Recent executions
                        </p>
                        <div className="space-y-1.5">
                          {(recentRunsByRule[rule.id] || []).map((run) => (
                            <div
                              key={run.id}
                              className={`flex flex-wrap items-center justify-between gap-3 rounded-xl ring-1 px-3 py-2.5 text-sm transition-colors ${
                                run.success
                                  ? "bg-emerald-500/[0.04] ring-emerald-500/15 hover:bg-emerald-500/[0.07]"
                                  : "bg-red-500/[0.04] ring-red-500/15 hover:bg-red-500/[0.07]"
                              }`}
                            >
                              <div>
                                <p className="text-gray-300">{run.result_summary || run.error || "Run finished"}</p>
                                <p className="text-xs text-gray-500 mt-0.5">
                                  {formatDate(run.created_at)}
                                </p>
                              </div>
                              <span
                                className={`px-2.5 py-0.5 rounded-full text-[10px] font-semibold ring-1 shrink-0 ${
                                  run.success
                                    ? "bg-emerald-500/15 text-emerald-400 ring-emerald-500/25"
                                    : "bg-red-500/15 text-red-400 ring-red-500/25"
                                }`}
                              >
                                {run.success ? "Success" : "Failed"}
                              </span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
