"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  CalendarDays,
  Copy,
  ExternalLink,
  GitBranch,
  HardDrive,
  Mail,
  PauseCircle,
  PlayCircle,
  PlugZap,
  RefreshCcw,
  RotateCw,
  Trash2,
  Webhook,
} from "lucide-react";
import { useTeams } from "@/hooks/use-teams";
import { useIntegrations } from "@/hooks/use-integrations";
import { useNotes } from "@/hooks/use-notes";
import { useTasks } from "@/hooks/use-tasks";
import { SLACK_EVENT_OPTIONS } from "@/lib/integrations/catalog";
import type {
  GitHubConnectionConfig,
  GmailConnectionConfig,
  GoogleCalendarConnectionConfig,
  GoogleDriveConnectionConfig,
  GoogleSheetsConnectionConfig,
  GmailMessageSummary,
  GoogleDriveFileSummary,
  NotionConnectionConfig,
  TelegramConnectionConfig,
  WebhookEventType,
} from "@/types";
import { Badge } from "@/components/ui/badge";
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 { cn } from "@/lib/utils";

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

function parseGoogleConfig(config: Record<string, unknown>): GoogleCalendarConnectionConfig {
  return {
    calendarId: typeof config.calendarId === "string" ? config.calendarId : null,
    calendarSummary: typeof config.calendarSummary === "string" ? config.calendarSummary : null,
    connectedEmail: typeof config.connectedEmail === "string" ? config.connectedEmail : null,
  };
}

function parseGmailConfig(config: Record<string, unknown>): GmailConnectionConfig {
  return {
    connectedEmail: typeof config.connectedEmail === "string" ? config.connectedEmail : null,
  };
}

function parseDriveConfig(config: Record<string, unknown>): GoogleDriveConnectionConfig {
  return {
    connectedEmail: typeof config.connectedEmail === "string" ? config.connectedEmail : null,
  };
}

function parseGitHubConfig(config: Record<string, unknown>): GitHubConnectionConfig {
  return {
    connectedLogin: typeof config.connectedLogin === "string" ? config.connectedLogin : null,
    connectedUrl: typeof config.connectedUrl === "string" ? config.connectedUrl : null,
    repoOwner: typeof config.repoOwner === "string" ? config.repoOwner : null,
    repoName: typeof config.repoName === "string" ? config.repoName : null,
    repoFullName: typeof config.repoFullName === "string" ? config.repoFullName : null,
  };
}

function parseTelegramConfig(config: Record<string, unknown>): TelegramConnectionConfig {
  return {
    botUsername: typeof config.botUsername === "string" ? config.botUsername : null,
    chatId: typeof config.chatId === "string" ? config.chatId : null,
  };
}

function parseSheetsConfig(config: Record<string, unknown>): GoogleSheetsConnectionConfig {
  return {
    webhookUrlMasked:
      typeof config.webhookUrlMasked === "string" ? config.webhookUrlMasked : null,
  };
}

function parseNotionConfig(config: Record<string, unknown>): NotionConnectionConfig {
  return {
    parentPageId: typeof config.parentPageId === "string" ? config.parentPageId : null,
  };
}

export default function IntegrationsPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { activeTeam } = useTeams();
  const { tasks } = useTasks();
  const { notes } = useNotes();
  const {
    activeTeamId,
    slackConnections,
    googleConnections,
    gmailConnections,
    driveConnections,
    githubConnections,
    telegramConnections,
    sheetsConnections,
    notionConnections,
    calendarFeeds,
    googleCalendarsByConnection,
    githubReposByConnection,
    gmailMessagesByConnection,
    driveFilesByConnection,
    deliveriesByConnection,
    loading,
    createSlackConnection,
    updateSlackConnection,
    deleteSlackConnection,
    fetchSlackDeliveries,
    fetchGoogleCalendars,
    updateGoogleConnection,
    syncGoogleConnection,
    deleteGoogleConnection,
    fetchGmailMessages,
    updateGmailConnection,
    deleteGmailConnection,
    fetchDriveFiles,
    updateDriveConnection,
    deleteDriveConnection,
    createGitHubConnection,
    fetchGitHubRepos,
    updateGitHubConnection,
    deleteGitHubConnection,
    createTelegramConnection,
    updateTelegramConnection,
    deleteTelegramConnection,
    createSheetsConnection,
    updateSheetsConnection,
    deleteSheetsConnection,
    createNotionConnection,
    updateNotionConnection,
    deleteNotionConnection,
    createCalendarFeed,
    updateCalendarFeed,
    deleteCalendarFeed,
    refetch,
  } = useIntegrations();

  const workspaceLabel = activeTeamId ? activeTeam?.name || "Team workspace" : "Personal workspace";
  const [slackName, setSlackName] = useState("");
  const [slackWebhookUrl, setSlackWebhookUrl] = useState("");
  const [githubName, setGitHubName] = useState("");
  const [githubToken, setGitHubToken] = useState("");
  const [telegramName, setTelegramName] = useState("");
  const [telegramBotToken, setTelegramBotToken] = useState("");
  const [telegramChatId, setTelegramChatId] = useState("");
  const [telegramBotUsername, setTelegramBotUsername] = useState("");
  const [sheetsName, setSheetsName] = useState("");
  const [sheetsWebhookUrl, setSheetsWebhookUrl] = useState("");
  const [notionName, setNotionName] = useState("");
  const [notionToken, setNotionToken] = useState("");
  const [notionParentPageId, setNotionParentPageId] = useState("");
  const [calendarFeedName, setCalendarFeedName] = useState("");
  const [selectedEvents, setSelectedEvents] = useState<WebhookEventType[]>([
    "project.created",
    "task.created",
    "task.updated",
  ]);
  const [latestFeedUrl, setLatestFeedUrl] = useState<string | null>(null);
  const [feedback, setFeedback] = useState<string | null>(null);
  const [submittingSlack, setSubmittingSlack] = useState(false);
  const [submittingGitHub, setSubmittingGitHub] = useState(false);
  const [submittingTelegram, setSubmittingTelegram] = useState(false);
  const [submittingSheets, setSubmittingSheets] = useState(false);
  const [submittingNotion, setSubmittingNotion] = useState(false);
  const [submittingFeed, setSubmittingFeed] = useState(false);
  const [syncingGoogleId, setSyncingGoogleId] = useState<string | null>(null);
  const [selectedDriveTaskByConnection, setSelectedDriveTaskByConnection] = useState<
    Record<string, string>
  >({});
  const [selectedDriveNoteByConnection, setSelectedDriveNoteByConnection] = useState<
    Record<string, string>
  >({});

  const activeSlackCount = useMemo(
    () => slackConnections.filter((connection) => connection.is_active).length,
    [slackConnections]
  );
  const activeGoogleCount = useMemo(
    () => googleConnections.filter((connection) => connection.is_active).length,
    [googleConnections]
  );
  const activeGmailCount = useMemo(
    () => gmailConnections.filter((connection) => connection.is_active).length,
    [gmailConnections]
  );
  const activeDriveCount = useMemo(
    () => driveConnections.filter((connection) => connection.is_active).length,
    [driveConnections]
  );
  const activeGitHubCount = useMemo(
    () => githubConnections.filter((connection) => connection.is_active).length,
    [githubConnections]
  );
  const activeTelegramCount = useMemo(
    () => telegramConnections.filter((connection) => connection.is_active).length,
    [telegramConnections]
  );
  const activeSheetsCount = useMemo(
    () => sheetsConnections.filter((connection) => connection.is_active).length,
    [sheetsConnections]
  );
  const activeNotionCount = useMemo(
    () => notionConnections.filter((connection) => connection.is_active).length,
    [notionConnections]
  );
  const activeFeedCount = useMemo(
    () => calendarFeeds.filter((feed) => feed.is_active).length,
    [calendarFeeds]
  );

  useEffect(() => {
    const statusMap: Array<{ key: string; label: string }> = [
      { key: "googleCalendar", label: "Google Calendar" },
      { key: "gmail", label: "Gmail" },
      { key: "googleDrive", label: "Google Drive" },
    ];
    const match = statusMap.find((entry) => searchParams.get(entry.key));
    if (!match) return;

    const status = searchParams.get(match.key);
    const messages: Record<string, string> = {
      connected: `${match.label} connected.`,
      oauth_error: `${match.label} was canceled or denied.`,
      missing_code: `${match.label} callback was incomplete.`,
      state_expired: `The ${match.label} connect session expired. Start it again.`,
      session_mismatch: `${match.label} connect session did not match your account.`,
      forbidden: "You no longer have permission to connect this workspace.",
      not_configured: `${match.label} env vars are not configured yet.`,
      connect_failed: `${match.label} could not be connected.`,
    };

    setFeedback(messages[status || ""] || `${match.label} updated.`);
  }, [searchParams]);

  function toggleEvent(value: WebhookEventType) {
    setSelectedEvents((prev) =>
      prev.includes(value) ? prev.filter((event) => event !== value) : [...prev, value]
    );
  }

  async function copyText(value: string) {
    try {
      await navigator.clipboard.writeText(value);
      setFeedback("Copied to clipboard.");
    } catch {
      setFeedback("Could not copy to clipboard.");
    }
  }

  function handleConnectGoogleCalendar() {
    const query = activeTeamId ? `?teamId=${encodeURIComponent(activeTeamId)}` : "";
    window.location.href = `/api/integrations/google-calendar/connect${query}`;
  }

  function handleConnectGmail() {
    const query = activeTeamId ? `?teamId=${encodeURIComponent(activeTeamId)}` : "";
    window.location.href = `/api/integrations/gmail/connect${query}`;
  }

  function handleConnectGoogleDrive() {
    const query = activeTeamId ? `?teamId=${encodeURIComponent(activeTeamId)}` : "";
    window.location.href = `/api/integrations/google-drive/connect${query}`;
  }

  async function handleCreateSlackConnection() {
    setSubmittingSlack(true);
    setFeedback(null);

    try {
      await createSlackConnection({
        name: slackName || `${workspaceLabel} Slack alerts`,
        webhookUrl: slackWebhookUrl,
        eventTypes: selectedEvents,
      });
      setSlackName("");
      setSlackWebhookUrl("");
      setFeedback("Slack integration connected.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Slack integration could not be created.");
    } finally {
      setSubmittingSlack(false);
    }
  }

  async function handleCreateGitHubConnection() {
    setSubmittingGitHub(true);
    setFeedback(null);

    try {
      await createGitHubConnection({
        name: githubName || `${workspaceLabel} GitHub`,
        token: githubToken,
      });
      setGitHubName("");
      setGitHubToken("");
      setFeedback("GitHub integration connected.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "GitHub integration could not be created.");
    } finally {
      setSubmittingGitHub(false);
    }
  }

  async function handleCreateTelegramConnection() {
    setSubmittingTelegram(true);
    setFeedback(null);
    try {
      await createTelegramConnection({
        name: telegramName || `${workspaceLabel} Telegram`,
        botToken: telegramBotToken,
        chatId: telegramChatId,
        botUsername: telegramBotUsername,
        eventTypes: selectedEvents,
      });
      setTelegramName("");
      setTelegramBotToken("");
      setTelegramChatId("");
      setTelegramBotUsername("");
      setFeedback("Telegram integration connected.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Telegram integration could not be created.");
    } finally {
      setSubmittingTelegram(false);
    }
  }

  async function handleCreateSheetsConnection() {
    setSubmittingSheets(true);
    setFeedback(null);
    try {
      await createSheetsConnection({
        name: sheetsName || `${workspaceLabel} Sheets log`,
        webhookUrl: sheetsWebhookUrl,
        eventTypes: selectedEvents,
      });
      setSheetsName("");
      setSheetsWebhookUrl("");
      setFeedback("Google Sheets integration connected.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Sheets integration could not be created.");
    } finally {
      setSubmittingSheets(false);
    }
  }

  async function handleCreateNotionConnection() {
    setSubmittingNotion(true);
    setFeedback(null);
    try {
      await createNotionConnection({
        name: notionName || `${workspaceLabel} Notion pages`,
        token: notionToken,
        parentPageId: notionParentPageId,
        eventTypes: selectedEvents,
      });
      setNotionName("");
      setNotionToken("");
      setNotionParentPageId("");
      setFeedback("Notion integration connected.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Notion integration could not be created.");
    } finally {
      setSubmittingNotion(false);
    }
  }

  async function handleCreateCalendarFeed() {
    setSubmittingFeed(true);
    setFeedback(null);

    try {
      const result = await createCalendarFeed({
        name: calendarFeedName || `${workspaceLabel} calendar`,
      });
      setCalendarFeedName("");
      setLatestFeedUrl(result.feedUrl);
      setFeedback("Calendar feed created. Copy the subscription URL now.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Calendar feed could not be created.");
    } finally {
      setSubmittingFeed(false);
    }
  }

  async function handleToggleSlack(id: string, isActive: boolean) {
    try {
      await updateSlackConnection(id, { isActive: !isActive });
      setFeedback(isActive ? "Slack integration paused." : "Slack integration resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Slack integration could not be updated.");
    }
  }

  async function handleDeleteSlack(id: string) {
    try {
      await deleteSlackConnection(id);
      setFeedback("Slack integration deleted.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Slack integration could not be deleted.");
    }
  }

  async function handleToggleFeed(id: string, isActive: boolean) {
    try {
      await updateCalendarFeed(id, { isActive: !isActive });
      setFeedback(isActive ? "Calendar feed paused." : "Calendar feed resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Calendar feed could not be updated.");
    }
  }

  async function handleDeleteFeed(id: string) {
    try {
      await deleteCalendarFeed(id);
      setFeedback("Calendar feed deleted.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Calendar feed could not be deleted.");
    }
  }

  async function handleLoadDeliveries(id: string) {
    try {
      await fetchSlackDeliveries(id);
      setFeedback("Slack deliveries loaded.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Deliveries could not be loaded.");
    }
  }

  async function handleLoadGoogleCalendars(id: string) {
    try {
      await fetchGoogleCalendars(id);
      setFeedback("Google calendars loaded.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google calendars could not be loaded.");
    }
  }

  async function handleToggleGoogle(id: string, isActive: boolean) {
    try {
      await updateGoogleConnection(id, { isActive: !isActive });
      setFeedback(isActive ? "Google Calendar sync paused." : "Google Calendar sync resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Calendar connection could not be updated.");
    }
  }

  async function handleDeleteGoogle(id: string) {
    try {
      await deleteGoogleConnection(id);
      setFeedback("Google Calendar connection removed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Calendar connection could not be deleted.");
    }
  }

  async function handleLoadGmailMessages(id: string) {
    try {
      await fetchGmailMessages(id);
      setFeedback("Gmail messages loaded.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Gmail messages could not be loaded.");
    }
  }

  async function handleToggleGmail(id: string, isActive: boolean) {
    try {
      await updateGmailConnection(id, { isActive: !isActive });
      setFeedback(isActive ? "Gmail connection paused." : "Gmail connection resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Gmail connection could not be updated.");
    }
  }

  async function handleDeleteGmail(id: string) {
    try {
      await deleteGmailConnection(id);
      setFeedback("Gmail connection removed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Gmail connection could not be deleted.");
    }
  }

  async function handleLoadDriveFiles(id: string) {
    try {
      await fetchDriveFiles(id);
      setFeedback("Google Drive files loaded.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Drive files could not be loaded.");
    }
  }

  async function handleToggleDrive(id: string, isActive: boolean) {
    try {
      await updateDriveConnection(id, { isActive: !isActive });
      setFeedback(isActive ? "Google Drive connection paused." : "Google Drive connection resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Drive connection could not be updated.");
    }
  }

  async function handleDeleteDrive(id: string) {
    try {
      await deleteDriveConnection(id);
      setFeedback("Google Drive connection removed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Drive connection could not be deleted.");
    }
  }

  async function handleCaptureGmail(
    connectionId: string,
    message: GmailMessageSummary,
    mode: "task" | "note"
  ) {
    try {
      const res = await fetch(`/api/integrations/gmail/${connectionId}/capture`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ mode, message }),
      });
      const json = await res.json();
      if (!res.ok) {
        throw new Error(json.error || "Gmail message could not be captured");
      }

      setFeedback(mode === "task" ? "Task created from Gmail." : "Note created from Gmail.");
      if (json.link) {
        router.push(json.link);
      }
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Gmail message could not be captured.");
    }
  }

  async function handleCaptureDriveFile(
    connectionId: string,
    file: GoogleDriveFileSummary,
    mode: "task" | "note" | "existing_task" | "existing_note"
  ) {
    try {
      const targetEntityId =
        mode === "existing_task"
          ? selectedDriveTaskByConnection[connectionId] || null
          : mode === "existing_note"
          ? selectedDriveNoteByConnection[connectionId] || null
          : null;

      if ((mode === "existing_task" || mode === "existing_note") && !targetEntityId) {
        throw new Error("Please choose a target task or note first.");
      }

      const res = await fetch(`/api/integrations/google-drive/${connectionId}/capture`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ mode, file, targetEntityId }),
      });
      const json = await res.json();
      if (!res.ok) {
        throw new Error(json.error || "Google Drive file could not be captured");
      }

      setFeedback(
        mode === "task"
          ? "Task created from Google Drive."
          : mode === "note"
          ? "Note created from Google Drive."
          : mode === "existing_task"
          ? "File attached to the selected task."
          : "File attached to the selected note."
      );
      if (json.link) {
        router.push(json.link);
      }
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Drive file could not be captured.");
    }
  }

  async function handleGoogleCalendarSelect(
    id: string,
    calendarId: string,
    calendarSummary: string | null
  ) {
    try {
      await updateGoogleConnection(id, {
        calendarId,
        calendarSummary,
      });
      setFeedback("Google target calendar updated.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Target calendar could not be updated.");
    }
  }

  async function handleSyncGoogle(id: string) {
    setSyncingGoogleId(id);
    try {
      const result = await syncGoogleConnection(id);
      setFeedback(
        `Google Calendar synced. ${result.synced} event${result.synced === 1 ? "" : "s"} pushed to ${
          result.calendarSummary || "the selected calendar"
        }.`
      );
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Calendar could not be synced.");
    } finally {
      setSyncingGoogleId(null);
    }
  }

  async function handleLoadGitHubRepos(id: string) {
    try {
      await fetchGitHubRepos(id);
      setFeedback("GitHub repositories loaded.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "GitHub repositories could not be loaded.");
    }
  }

  async function handleSelectGitHubRepo(
    id: string,
    repoFullName: string
  ) {
    const [repoOwner, repoName] = repoFullName.split("/");
    try {
      await updateGitHubConnection(id, {
        repoOwner: repoOwner || null,
        repoName: repoName || null,
        repoFullName: repoFullName || null,
      });
      setFeedback("GitHub target repository updated.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "GitHub repository could not be updated.");
    }
  }

  async function handleToggleGitHub(id: string, isActive: boolean) {
    try {
      await updateGitHubConnection(id, { isActive: !isActive });
      setFeedback(isActive ? "GitHub integration paused." : "GitHub integration resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "GitHub connection could not be updated.");
    }
  }

  async function handleDeleteGitHub(id: string) {
    try {
      await deleteGitHubConnection(id);
      setFeedback("GitHub connection removed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "GitHub connection could not be deleted.");
    }
  }

  async function handleToggleTelegram(id: string, isActive: boolean) {
    try {
      await updateTelegramConnection(id, { isActive: !isActive });
      setFeedback(isActive ? "Telegram integration paused." : "Telegram integration resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Telegram connection could not be updated.");
    }
  }

  async function handleDeleteTelegram(id: string) {
    try {
      await deleteTelegramConnection(id);
      setFeedback("Telegram connection removed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Telegram connection could not be deleted.");
    }
  }

  async function handleToggleSheets(id: string, isActive: boolean) {
    try {
      await updateSheetsConnection(id, { isActive: !isActive });
      setFeedback(isActive ? "Google Sheets integration paused." : "Google Sheets integration resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Sheets connection could not be updated.");
    }
  }

  async function handleDeleteSheets(id: string) {
    try {
      await deleteSheetsConnection(id);
      setFeedback("Google Sheets connection removed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Google Sheets connection could not be deleted.");
    }
  }

  async function handleToggleNotion(id: string, isActive: boolean) {
    try {
      await updateNotionConnection(id, { isActive: !isActive });
      setFeedback(isActive ? "Notion integration paused." : "Notion integration resumed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Notion connection could not be updated.");
    }
  }

  async function handleDeleteNotion(id: string) {
    try {
      await deleteNotionConnection(id);
      setFeedback("Notion connection removed.");
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Notion connection could not be deleted.");
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-3">
            <PlugZap className="h-5 w-5 text-muted-foreground" />
            <h1 className="text-2xl font-bold tracking-tight">Integrations</h1>
          </div>
          <p className="text-sm text-muted-foreground">
            Connect GitHub, Gmail, Google Drive, Slack, Google Calendar, and calendar subscriptions for{" "}
            <span className="font-medium">{workspaceLabel}</span>.
          </p>
        </div>

        <div className="flex items-center gap-2">
          <Badge variant="outline">{workspaceLabel}</Badge>
          <Button variant="outline" size="sm" onClick={() => void refetch()}>
            <RefreshCcw className="h-4 w-4" />
            Refresh
          </Button>
        </div>
      </div>

      {feedback && (
        <div className="rounded-xl border border-border/60 bg-muted/40 px-4 py-3 text-sm">
          {feedback}
        </div>
      )}

      {latestFeedUrl && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CalendarDays className="h-4 w-4" />
              New calendar subscription URL
            </CardTitle>
            <CardDescription>
              Copy this link now. It will not be shown again after you leave this page.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <pre className="overflow-x-auto rounded-xl border border-border/60 bg-background p-4 text-xs">
              {latestFeedUrl}
            </pre>
            <Button variant="outline" size="sm" onClick={() => void copyText(latestFeedUrl)}>
              <Copy className="h-4 w-4" />
              Copy URL
            </Button>
          </CardContent>
        </Card>
      )}

      <div className="grid gap-4 md:grid-cols-4 xl:grid-cols-5">
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Active Slack channels</CardDescription>
            <CardTitle className="text-2xl">{loading ? "..." : activeSlackCount}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>GitHub repos</CardDescription>
            <CardTitle className="text-2xl">{loading ? "..." : activeGitHubCount}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Gmail inboxes</CardDescription>
            <CardTitle className="text-2xl">{loading ? "..." : activeGmailCount}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Drive connections</CardDescription>
            <CardTitle className="text-2xl">{loading ? "..." : activeDriveCount}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Telegram bots</CardDescription>
            <CardTitle className="text-2xl">{loading ? "..." : activeTelegramCount}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Sheets logs</CardDescription>
            <CardTitle className="text-2xl">{loading ? "..." : activeSheetsCount}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Notion pages</CardDescription>
            <CardTitle className="text-2xl">{loading ? "..." : activeNotionCount}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Google calendars</CardDescription>
            <CardTitle className="text-2xl">{loading ? "..." : activeGoogleCount}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Calendar feeds</CardDescription>
            <CardTitle className="text-2xl">{loading ? "..." : activeFeedCount}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Delivery logs</CardDescription>
            <CardTitle className="text-2xl">
              {loading
                ? "..."
                : Object.values(deliveriesByConnection).reduce((sum, items) => sum + items.length, 0)}
            </CardTitle>
          </CardHeader>
        </Card>
      </div>

      <div className="grid gap-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <GitBranch className="h-4 w-4" />
              GitHub
            </CardTitle>
            <CardDescription>
              Connect a personal access token, pick a repo, and turn tasks into GitHub issues.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-5">
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="github-name">Connection name</Label>
                <Input
                  id="github-name"
                  value={githubName}
                  onChange={(event) => setGitHubName(event.target.value)}
                  placeholder={`${workspaceLabel} GitHub`}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="github-token">Personal access token</Label>
                <Input
                  id="github-token"
                  type="password"
                  value={githubToken}
                  onChange={(event) => setGitHubToken(event.target.value)}
                  placeholder="github_pat_..."
                />
              </div>
            </div>

            <div className="flex flex-wrap items-center gap-2">
              <Button
                onClick={() => void handleCreateGitHubConnection()}
                disabled={submittingGitHub || !githubToken.trim()}
              >
                <GitBranch className="h-4 w-4" />
                {submittingGitHub ? "Connecting..." : "Connect GitHub"}
              </Button>
              <Badge variant="outline">Best for personal daily workflow</Badge>
              <Badge variant="outline">Task to Issue</Badge>
            </div>

            {githubConnections.length === 0 ? (
              <EmptyState
                icon={<GitBranch className="h-6 w-6" />}
                title="No GitHub connection yet"
                description="Connect a token, load your repositories, and select the default repo you want to use for task issues."
              />
            ) : (
              <div className="space-y-3">
                {githubConnections.map((connection) => {
                  const config = parseGitHubConfig(connection.config);
                  const repos = githubReposByConnection[connection.id] || [];

                  return (
                    <div
                      key={connection.id}
                      className="rounded-xl border border-border/60 bg-background p-4"
                    >
                      <div className="flex flex-wrap items-start justify-between gap-3">
                        <div className="space-y-1">
                          <div className="flex items-center gap-2">
                            <p className="font-medium">{connection.name}</p>
                            <Badge variant={connection.is_active ? "default" : "outline"}>
                              {connection.is_active ? "Active" : "Paused"}
                            </Badge>
                          </div>
                          <p className="text-xs text-muted-foreground">
                            Connected account: {config.connectedLogin || "GitHub account"}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            Target repo: {config.repoFullName || "Not selected yet"}
                          </p>
                          {config.connectedUrl ? (
                            <a
                              href={config.connectedUrl}
                              target="_blank"
                              rel="noreferrer"
                              className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
                            >
                              Open GitHub profile
                              <ExternalLink className="h-3.5 w-3.5" />
                            </a>
                          ) : null}
                        </div>

                        <div className="flex flex-wrap items-center gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => void handleLoadGitHubRepos(connection.id)}
                          >
                            <RefreshCcw className="h-4 w-4" />
                            Load repos
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => void handleToggleGitHub(connection.id, connection.is_active)}
                          >
                            {connection.is_active ? (
                              <PauseCircle className="h-4 w-4" />
                            ) : (
                              <PlayCircle className="h-4 w-4" />
                            )}
                            {connection.is_active ? "Pause" : "Resume"}
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => void handleDeleteGitHub(connection.id)}
                          >
                            <Trash2 className="h-4 w-4" />
                            Delete
                          </Button>
                        </div>
                      </div>

                      <div className="mt-4 grid gap-3 md:grid-cols-[1fr_auto]">
                        <Select
                          value={config.repoFullName || ""}
                          onChange={(event) =>
                            void handleSelectGitHubRepo(connection.id, event.target.value)
                          }
                        >
                          <option value="">Select GitHub repository...</option>
                          {repos.map((repo) => (
                            <option key={repo.id} value={repo.full_name}>
                              {repo.full_name}
                              {repo.private ? " (Private)" : ""}
                            </option>
                          ))}
                        </Select>
                        {config.repoFullName ? (
                          <Badge variant="outline">{config.repoFullName}</Badge>
                        ) : null}
                      </div>

                      {repos.length > 0 ? (
                        <div className="mt-3 flex flex-wrap gap-2">
                          {repos.slice(0, 6).map((repo) => (
                            <Badge key={repo.id} variant="outline">
                              {repo.full_name}
                            </Badge>
                          ))}
                        </div>
                      ) : null}
                    </div>
                  );
                })}
              </div>
            )}
          </CardContent>
        </Card>

        <div className="grid gap-6 xl:grid-cols-2">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Mail className="h-4 w-4" />
                Gmail
              </CardTitle>
              <CardDescription>
                Connect Gmail, review recent messages, and turn them into tasks or notes.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-5">
              <div className="flex flex-wrap items-center gap-3">
                <Button onClick={handleConnectGmail}>
                  <ExternalLink className="h-4 w-4" />
                  Connect Gmail
                </Button>
                <Badge variant="outline">Read-only inbox access</Badge>
                <Badge variant="outline">Email to Task/Note</Badge>
              </div>

              {gmailConnections.length === 0 ? (
                <EmptyState
                  icon={<Mail className="h-6 w-6" />}
                  title="No Gmail connection yet"
                  description="Connect Gmail and pull in recent messages whenever you want to turn them into structured work."
                />
              ) : (
                <div className="space-y-3">
                  {gmailConnections.map((connection) => {
                    const config = parseGmailConfig(connection.config);
                    const messages = gmailMessagesByConnection[connection.id] || [];

                    return (
                      <div
                        key={connection.id}
                        className="rounded-xl border border-border/60 bg-background p-4"
                      >
                        <div className="flex flex-wrap items-start justify-between gap-3">
                          <div className="space-y-1">
                            <div className="flex items-center gap-2">
                              <p className="font-medium">{connection.name}</p>
                              <Badge variant={connection.is_active ? "default" : "outline"}>
                                {connection.is_active ? "Active" : "Paused"}
                              </Badge>
                            </div>
                            <p className="text-xs text-muted-foreground">
                              Connected inbox: {config.connectedEmail || "Google account"}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              Last updated: {formatDate(connection.updated_at)}
                            </p>
                          </div>

                          <div className="flex flex-wrap items-center gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleLoadGmailMessages(connection.id)}
                            >
                              <RefreshCcw className="h-4 w-4" />
                              Load inbox
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleToggleGmail(connection.id, connection.is_active)}
                            >
                              {connection.is_active ? (
                                <PauseCircle className="h-4 w-4" />
                              ) : (
                                <PlayCircle className="h-4 w-4" />
                              )}
                              {connection.is_active ? "Pause" : "Resume"}
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleDeleteGmail(connection.id)}
                            >
                              <Trash2 className="h-4 w-4" />
                              Delete
                            </Button>
                          </div>
                        </div>

                        {messages.length > 0 ? (
                          <div className="mt-4 space-y-3">
                            {messages.slice(0, 8).map((message) => (
                              <div
                                key={message.id}
                                className="rounded-xl border border-border/60 bg-muted/20 p-3"
                              >
                                <div className="flex flex-wrap items-start justify-between gap-3">
                                  <div className="space-y-1">
                                    <p className="font-medium">
                                      {message.subject || "Untitled message"}
                                    </p>
                                    <p className="text-xs text-muted-foreground">
                                      {message.from || "Unknown sender"}
                                    </p>
                                    <p className="text-xs text-muted-foreground">
                                      {message.date || formatDate(message.internalDate)}
                                    </p>
                                  </div>
                                  <div className="flex flex-wrap gap-2">
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      onClick={() => window.open(message.webUrl, "_blank", "noopener,noreferrer")}
                                    >
                                      <ExternalLink className="h-4 w-4" />
                                      Open
                                    </Button>
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      onClick={() =>
                                        void handleCaptureGmail(connection.id, message, "note")
                                      }
                                    >
                                      Save note
                                    </Button>
                                    <Button
                                      size="sm"
                                      onClick={() =>
                                        void handleCaptureGmail(connection.id, message, "task")
                                      }
                                    >
                                      Create task
                                    </Button>
                                  </div>
                                </div>
                                <p className="mt-2 text-sm text-muted-foreground">{message.snippet}</p>
                              </div>
                            ))}
                          </div>
                        ) : null}
                      </div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <HardDrive className="h-4 w-4" />
                Google Drive
              </CardTitle>
              <CardDescription>
                Connect Drive, browse recent files, and capture them into tasks or notes.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-5">
              <div className="flex flex-wrap items-center gap-3">
                <Button onClick={handleConnectGoogleDrive}>
                  <ExternalLink className="h-4 w-4" />
                  Connect Google Drive
                </Button>
                <Badge variant="outline">Metadata only</Badge>
                <Badge variant="outline">File to Task/Note</Badge>
              </div>

              {driveConnections.length === 0 ? (
                <EmptyState
                  icon={<HardDrive className="h-6 w-6" />}
                  title="No Google Drive connection yet"
                  description="Connect Drive and capture file links into structured work without copying URLs around by hand."
                />
              ) : (
                <div className="space-y-3">
                  {driveConnections.map((connection) => {
                    const config = parseDriveConfig(connection.config);
                    const files = driveFilesByConnection[connection.id] || [];
                    const selectedTaskId = selectedDriveTaskByConnection[connection.id] || "";
                    const selectedNoteId = selectedDriveNoteByConnection[connection.id] || "";

                    return (
                      <div
                        key={connection.id}
                        className="rounded-xl border border-border/60 bg-background p-4"
                      >
                        <div className="flex flex-wrap items-start justify-between gap-3">
                          <div className="space-y-1">
                            <div className="flex items-center gap-2">
                              <p className="font-medium">{connection.name}</p>
                              <Badge variant={connection.is_active ? "default" : "outline"}>
                                {connection.is_active ? "Active" : "Paused"}
                              </Badge>
                            </div>
                            <p className="text-xs text-muted-foreground">
                              Connected account: {config.connectedEmail || "Google account"}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              Last updated: {formatDate(connection.updated_at)}
                            </p>
                          </div>

                          <div className="flex flex-wrap items-center gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleLoadDriveFiles(connection.id)}
                            >
                              <RefreshCcw className="h-4 w-4" />
                              Load files
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleToggleDrive(connection.id, connection.is_active)}
                            >
                              {connection.is_active ? (
                                <PauseCircle className="h-4 w-4" />
                              ) : (
                                <PlayCircle className="h-4 w-4" />
                              )}
                              {connection.is_active ? "Pause" : "Resume"}
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleDeleteDrive(connection.id)}
                            >
                              <Trash2 className="h-4 w-4" />
                              Delete
                            </Button>
                          </div>
                        </div>

                        <div className="mt-4 grid gap-3 md:grid-cols-2">
                          <div className="space-y-2">
                            <Label>Select existing task</Label>
                            <Select
                              value={selectedTaskId}
                              onChange={(event) =>
                                setSelectedDriveTaskByConnection((prev) => ({
                                  ...prev,
                                  [connection.id]: event.target.value,
                                }))
                              }
                            >
                              <option value="">Choose task...</option>
                              {tasks.slice(0, 50).map((task) => (
                                <option key={task.id} value={task.id}>
                                  {task.title}
                                </option>
                              ))}
                            </Select>
                          </div>
                          <div className="space-y-2">
                            <Label>Select existing note</Label>
                            <Select
                              value={selectedNoteId}
                              onChange={(event) =>
                                setSelectedDriveNoteByConnection((prev) => ({
                                  ...prev,
                                  [connection.id]: event.target.value,
                                }))
                              }
                            >
                              <option value="">Choose note...</option>
                              {notes.slice(0, 50).map((note) => (
                                <option key={note.id} value={note.id}>
                                  {note.title}
                                </option>
                              ))}
                            </Select>
                          </div>
                        </div>

                        {files.length > 0 ? (
                          <div className="mt-4 space-y-3">
                            {files.slice(0, 8).map((file) => (
                              <div
                                key={file.id}
                                className="rounded-xl border border-border/60 bg-muted/20 p-3"
                              >
                                <div className="flex flex-wrap items-start justify-between gap-3">
                                  <div className="space-y-1">
                                    <p className="font-medium">{file.name}</p>
                                    <p className="text-xs text-muted-foreground">{file.mimeType}</p>
                                    <p className="text-xs text-muted-foreground">
                                      Modified: {formatDate(file.modifiedTime)}
                                    </p>
                                    {file.owners.length > 0 ? (
                                      <p className="text-xs text-muted-foreground">
                                        Owners: {file.owners.join(", ")}
                                      </p>
                                    ) : null}
                                  </div>
                                  <div className="flex flex-wrap gap-2">
                                    {file.webViewLink ? (
                                      <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() =>
                                          window.open(file.webViewLink || "", "_blank", "noopener,noreferrer")
                                        }
                                      >
                                        <ExternalLink className="h-4 w-4" />
                                        Open
                                      </Button>
                                    ) : null}
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      onClick={() =>
                                        void handleCaptureDriveFile(connection.id, file, "note")
                                      }
                                    >
                                      New note
                                    </Button>
                                    <Button
                                      size="sm"
                                      onClick={() =>
                                        void handleCaptureDriveFile(connection.id, file, "task")
                                      }
                                    >
                                      New task
                                    </Button>
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      disabled={!selectedTaskId}
                                      onClick={() =>
                                        void handleCaptureDriveFile(connection.id, file, "existing_task")
                                      }
                                    >
                                      Attach to task
                                    </Button>
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      disabled={!selectedNoteId}
                                      onClick={() =>
                                        void handleCaptureDriveFile(connection.id, file, "existing_note")
                                      }
                                    >
                                      Attach to note
                                    </Button>
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>
                        ) : null}
                      </div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        <div className="grid gap-6 xl:grid-cols-3">
          <Card>
            <CardHeader>
              <CardTitle>Telegram Bot</CardTitle>
              <CardDescription>
                Send selected workspace events into a Telegram chat with your bot.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <Input
                value={telegramName}
                onChange={(event) => setTelegramName(event.target.value)}
                placeholder={`${workspaceLabel} Telegram`}
              />
              <Input
                type="password"
                value={telegramBotToken}
                onChange={(event) => setTelegramBotToken(event.target.value)}
                placeholder="Bot token"
              />
              <Input
                value={telegramChatId}
                onChange={(event) => setTelegramChatId(event.target.value)}
                placeholder="Chat id"
              />
              <Input
                value={telegramBotUsername}
                onChange={(event) => setTelegramBotUsername(event.target.value)}
                placeholder="@botusername (optional)"
              />
              <Button
                onClick={() => void handleCreateTelegramConnection()}
                disabled={submittingTelegram || !telegramBotToken.trim() || !telegramChatId.trim()}
              >
                {submittingTelegram ? "Connecting..." : "Connect Telegram"}
              </Button>
              {telegramConnections.map((connection) => {
                const config = parseTelegramConfig(connection.config);
                return (
                  <div key={connection.id} className="rounded-xl border border-border/60 bg-background p-3">
                    <div className="flex items-start justify-between gap-3">
                      <div className="space-y-1">
                        <p className="font-medium">{connection.name}</p>
                        <p className="text-xs text-muted-foreground">
                          {config.botUsername || "Telegram bot"} · chat {config.chatId || "configured"}
                        </p>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => void handleToggleTelegram(connection.id, connection.is_active)}
                        >
                          {connection.is_active ? "Pause" : "Resume"}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => void handleDeleteTelegram(connection.id)}
                        >
                          Delete
                        </Button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Google Sheets</CardTitle>
              <CardDescription>
                Push events into a Sheet through an Apps Script webhook URL.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <Input
                value={sheetsName}
                onChange={(event) => setSheetsName(event.target.value)}
                placeholder={`${workspaceLabel} Sheets log`}
              />
              <Input
                value={sheetsWebhookUrl}
                onChange={(event) => setSheetsWebhookUrl(event.target.value)}
                placeholder="Apps Script webhook URL"
              />
              <Button
                onClick={() => void handleCreateSheetsConnection()}
                disabled={submittingSheets || !sheetsWebhookUrl.trim()}
              >
                {submittingSheets ? "Connecting..." : "Connect Google Sheets"}
              </Button>
              {sheetsConnections.map((connection) => {
                const config = parseSheetsConfig(connection.config);
                return (
                  <div key={connection.id} className="rounded-xl border border-border/60 bg-background p-3">
                    <div className="flex items-start justify-between gap-3">
                      <div className="space-y-1">
                        <p className="font-medium">{connection.name}</p>
                        <p className="text-xs text-muted-foreground">
                          {config.webhookUrlMasked || "Webhook configured"}
                        </p>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => void handleToggleSheets(connection.id, connection.is_active)}
                        >
                          {connection.is_active ? "Pause" : "Resume"}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => void handleDeleteSheets(connection.id)}
                        >
                          Delete
                        </Button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Notion</CardTitle>
              <CardDescription>
                Create child pages under a Notion page when selected events happen.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <Input
                value={notionName}
                onChange={(event) => setNotionName(event.target.value)}
                placeholder={`${workspaceLabel} Notion pages`}
              />
              <Input
                type="password"
                value={notionToken}
                onChange={(event) => setNotionToken(event.target.value)}
                placeholder="Notion integration token"
              />
              <Input
                value={notionParentPageId}
                onChange={(event) => setNotionParentPageId(event.target.value)}
                placeholder="Parent page id"
              />
              <Button
                onClick={() => void handleCreateNotionConnection()}
                disabled={submittingNotion || !notionToken.trim() || !notionParentPageId.trim()}
              >
                {submittingNotion ? "Connecting..." : "Connect Notion"}
              </Button>
              {notionConnections.map((connection) => {
                const config = parseNotionConfig(connection.config);
                return (
                  <div key={connection.id} className="rounded-xl border border-border/60 bg-background p-3">
                    <div className="flex items-start justify-between gap-3">
                      <div className="space-y-1">
                        <p className="font-medium">{connection.name}</p>
                        <p className="text-xs text-muted-foreground">
                          Parent page: {config.parentPageId || "Configured"}
                        </p>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => void handleToggleNotion(connection.id, connection.is_active)}
                        >
                          {connection.is_active ? "Pause" : "Resume"}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => void handleDeleteNotion(connection.id)}
                        >
                          Delete
                        </Button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </CardContent>
          </Card>
        </div>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CalendarDays className="h-4 w-4" />
              Google Calendar
            </CardTitle>
            <CardDescription>
              Connect a Google account, choose a writable calendar, and sync Mindavio events into it.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-5">
            <div className="flex flex-wrap items-center gap-3">
              <Button onClick={handleConnectGoogleCalendar}>
                <ExternalLink className="h-4 w-4" />
                Connect Google Calendar
              </Button>
              <Badge variant="outline">Syncs workspace events</Badge>
              <Badge variant="outline">One-way push to Google</Badge>
            </div>

            {googleConnections.length === 0 ? (
              <EmptyState
                icon={<CalendarDays className="h-6 w-6" />}
                title="No Google Calendar connection yet"
                description="Connect a Google account, pick the target calendar, then run an initial sync. New and updated Mindavio events will continue syncing after that."
              />
            ) : (
              <div className="space-y-3">
                {googleConnections.map((connection) => {
                  const config = parseGoogleConfig(connection.config);
                  const calendars = googleCalendarsByConnection[connection.id] || [];

                  return (
                    <div
                      key={connection.id}
                      className="rounded-xl border border-border/60 bg-background p-4"
                    >
                      <div className="flex flex-wrap items-start justify-between gap-3">
                        <div className="space-y-1">
                          <div className="flex items-center gap-2">
                            <p className="font-medium">{connection.name}</p>
                            <Badge variant={connection.is_active ? "default" : "outline"}>
                              {connection.is_active ? "Active" : "Paused"}
                            </Badge>
                          </div>
                          <p className="text-xs text-muted-foreground">
                            Connected account: {config.connectedEmail || "Google account"}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            Target calendar: {config.calendarSummary || "Not selected yet"}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            Last sync activity: {formatDate(connection.last_delivery_at)}
                          </p>
                          {connection.last_error && (
                            <p className="pt-2 text-xs text-red-600">{connection.last_error}</p>
                          )}
                        </div>

                        <div className="flex flex-wrap items-center gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => void handleLoadGoogleCalendars(connection.id)}
                          >
                            <RefreshCcw className="h-4 w-4" />
                            Load calendars
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => void handleToggleGoogle(connection.id, connection.is_active)}
                          >
                            {connection.is_active ? (
                              <PauseCircle className="h-4 w-4" />
                            ) : (
                              <PlayCircle className="h-4 w-4" />
                            )}
                            {connection.is_active ? "Pause" : "Resume"}
                          </Button>
                          <Button
                            size="sm"
                            onClick={() => void handleSyncGoogle(connection.id)}
                            disabled={syncingGoogleId === connection.id}
                          >
                            <RotateCw className="h-4 w-4" />
                            {syncingGoogleId === connection.id ? "Syncing..." : "Sync now"}
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => void handleDeleteGoogle(connection.id)}
                          >
                            <Trash2 className="h-4 w-4" />
                            Delete
                          </Button>
                        </div>
                      </div>

                      <div className="mt-4 grid gap-3 md:grid-cols-[1fr_auto]">
                        <Select
                          value={config.calendarId || ""}
                          onChange={(event) => {
                            const calendar = calendars.find((item) => item.id === event.target.value) || null;
                            void handleGoogleCalendarSelect(
                              connection.id,
                              event.target.value,
                              calendar?.summary || null
                            );
                          }}
                        >
                          <option value="">Select Google calendar...</option>
                          {calendars.map((calendar) => (
                            <option key={calendar.id} value={calendar.id}>
                              {calendar.summary}
                              {calendar.primary ? " (Primary)" : ""}
                            </option>
                          ))}
                        </Select>
                        {config.calendarId && (
                          <Badge variant="outline">{config.calendarId}</Badge>
                        )}
                      </div>

                      {calendars.length > 0 && (
                        <div className="mt-3 flex flex-wrap gap-2">
                          {calendars.slice(0, 6).map((calendar) => (
                            <Badge key={calendar.id} variant="outline">
                              {calendar.summary}
                              {calendar.primary ? " • Primary" : ""}
                            </Badge>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </CardContent>
        </Card>

        <div className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Webhook className="h-4 w-4" />
                Slack alerts
              </CardTitle>
              <CardDescription>
                Push selected workspace events into a Slack channel with an incoming webhook.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-5">
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="slack-name">Connection name</Label>
                  <Input
                    id="slack-name"
                    value={slackName}
                    onChange={(event) => setSlackName(event.target.value)}
                    placeholder={`${workspaceLabel} Slack alerts`}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="slack-url">Incoming webhook URL</Label>
                  <Input
                    id="slack-url"
                    value={slackWebhookUrl}
                    onChange={(event) => setSlackWebhookUrl(event.target.value)}
                    placeholder="https://hooks.slack.com/services/..."
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label>Events</Label>
                <div className="grid gap-2 md:grid-cols-2">
                  {SLACK_EVENT_OPTIONS.map((option) => (
                    <label
                      key={option.value}
                      className="flex cursor-pointer items-start gap-3 rounded-xl border border-border/60 bg-background p-3"
                    >
                      <input
                        type="checkbox"
                        checked={selectedEvents.includes(option.value)}
                        onChange={() => toggleEvent(option.value)}
                        className="mt-1"
                      />
                      <span className="text-sm">{option.label}</span>
                    </label>
                  ))}
                </div>
              </div>

              <Button onClick={() => void handleCreateSlackConnection()} disabled={submittingSlack}>
                <Webhook className="h-4 w-4" />
                {submittingSlack ? "Connecting..." : "Connect Slack"}
              </Button>

              {slackConnections.length === 0 ? (
                <EmptyState
                  icon={<Webhook className="h-6 w-6" />}
                  title="No Slack connections yet"
                  description="Create one incoming webhook connection and Mindavio will start posting selected events."
                />
              ) : (
                <div className="space-y-3">
                  {slackConnections.map((connection) => {
                    const deliveries = deliveriesByConnection[connection.id] || [];

                    return (
                      <div
                        key={connection.id}
                        className="rounded-xl border border-border/60 bg-background p-4"
                      >
                        <div className="flex flex-wrap items-start justify-between gap-3">
                          <div className="space-y-1">
                            <div className="flex items-center gap-2">
                              <p className="font-medium">{connection.name}</p>
                              <Badge variant={connection.is_active ? "default" : "outline"}>
                                {connection.is_active ? "Active" : "Paused"}
                              </Badge>
                              {connection.last_response_status !== null && (
                                <Badge
                                  variant="outline"
                                  className={cn(
                                    connection.last_response_status >= 200 &&
                                      connection.last_response_status < 300
                                      ? "border-emerald-500/40 text-emerald-600"
                                      : "border-red-500/40 text-red-600"
                                  )}
                                >
                                  {connection.last_response_status}
                                </Badge>
                              )}
                            </div>
                            <p className="text-xs text-muted-foreground">
                              Last delivery: {formatDate(connection.last_delivery_at)}
                            </p>
                            <div className="flex flex-wrap gap-2 pt-1">
                              {connection.event_types.map((eventType) => (
                                <Badge key={eventType} variant="outline">
                                  {eventType}
                                </Badge>
                              ))}
                            </div>
                            {connection.last_error && (
                              <p className="pt-2 text-xs text-red-600">{connection.last_error}</p>
                            )}
                          </div>

                          <div className="flex flex-wrap items-center gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleLoadDeliveries(connection.id)}
                            >
                              <RefreshCcw className="h-4 w-4" />
                              Load deliveries
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleToggleSlack(connection.id, connection.is_active)}
                            >
                              {connection.is_active ? (
                                <PauseCircle className="h-4 w-4" />
                              ) : (
                                <PlayCircle className="h-4 w-4" />
                              )}
                              {connection.is_active ? "Pause" : "Resume"}
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleDeleteSlack(connection.id)}
                            >
                              <Trash2 className="h-4 w-4" />
                              Delete
                            </Button>
                          </div>
                        </div>

                        {deliveries.length > 0 && (
                          <div className="mt-4 space-y-2 rounded-xl border border-border/50 bg-muted/20 p-3">
                            {deliveries.map((delivery) => (
                              <div
                                key={delivery.id}
                                className="flex flex-wrap items-center justify-between gap-2 text-xs"
                              >
                                <span className="font-medium">{delivery.event_type}</span>
                                <span className="text-muted-foreground">
                                  {delivery.response_status ?? "No response"} • {formatDate(delivery.created_at)}
                                </span>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>

          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <CalendarDays className="h-4 w-4" />
                  Calendar subscriptions
                </CardTitle>
                <CardDescription>
                  Generate read-only ICS links for Google Calendar, Apple Calendar, Outlook, or any external calendar client.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="calendar-feed-name">Feed name</Label>
                  <Input
                    id="calendar-feed-name"
                    value={calendarFeedName}
                    onChange={(event) => setCalendarFeedName(event.target.value)}
                    placeholder={`${workspaceLabel} calendar`}
                  />
                </div>

                <Button onClick={() => void handleCreateCalendarFeed()} disabled={submittingFeed}>
                  <CalendarDays className="h-4 w-4" />
                  {submittingFeed ? "Creating..." : "Create calendar feed"}
                </Button>

                {calendarFeeds.length === 0 ? (
                  <EmptyState
                    icon={<CalendarDays className="h-6 w-6" />}
                    title="No calendar feeds yet"
                    description="Create a feed and subscribe to it from Google Calendar, Apple Calendar, or Outlook."
                  />
                ) : (
                  <div className="space-y-3">
                    {calendarFeeds.map((feed) => (
                      <div
                        key={feed.id}
                        className="rounded-xl border border-border/60 bg-background p-4"
                      >
                        <div className="flex flex-wrap items-start justify-between gap-3">
                          <div className="space-y-1">
                            <div className="flex items-center gap-2">
                              <p className="font-medium">{feed.name}</p>
                              <Badge variant={feed.is_active ? "default" : "outline"}>
                                {feed.is_active ? "Active" : "Paused"}
                              </Badge>
                            </div>
                            <p className="text-xs text-muted-foreground">
                              Token prefix: <span className="font-mono">{feed.token_prefix}</span>
                            </p>
                            <p className="text-xs text-muted-foreground">
                              Last access: {formatDate(feed.last_accessed_at)}
                            </p>
                          </div>

                          <div className="flex flex-wrap items-center gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleToggleFeed(feed.id, feed.is_active)}
                            >
                              {feed.is_active ? (
                                <PauseCircle className="h-4 w-4" />
                              ) : (
                                <PlayCircle className="h-4 w-4" />
                              )}
                              {feed.is_active ? "Pause" : "Resume"}
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => void handleDeleteFeed(feed.id)}
                            >
                              <Trash2 className="h-4 w-4" />
                              Delete
                            </Button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Quick starts</CardTitle>
                <CardDescription>Three practical ways to use this right away.</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4 text-sm text-muted-foreground">
                <div className="rounded-xl border border-border/60 bg-background p-4">
                  <p className="font-medium text-foreground">Gmail capture</p>
                  <p className="mt-1">
                    Connect Gmail, pull in the latest messages, and turn anything important into a task or note in one click.
                  </p>
                </div>
                <div className="rounded-xl border border-border/60 bg-background p-4">
                  <p className="font-medium text-foreground">Google Drive capture</p>
                  <p className="mt-1">
                    Load recent Drive files, then create a follow-up task or a reference note without manually pasting links around.
                  </p>
                </div>
                <div className="rounded-xl border border-border/60 bg-background p-4">
                  <p className="font-medium text-foreground">Google Calendar</p>
                  <p className="mt-1">
                    Connect once, choose the destination calendar, then run an initial sync so new Mindavio events stay mirrored outside the app.
                  </p>
                </div>
                <div className="flex flex-wrap gap-2">
                  <Badge variant="outline">Google OAuth</Badge>
                  <Badge variant="outline">Email to Task</Badge>
                  <Badge variant="outline">Drive to Note</Badge>
                </div>
                {latestFeedUrl && (
                  <Button variant="outline" size="sm" onClick={() => void copyText(latestFeedUrl)}>
                    <ExternalLink className="h-4 w-4" />
                    Copy latest feed URL again
                  </Button>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}
