"use client";

import { useEffect, useState, type FormEvent, type KeyboardEvent } from "react";
import {
  Bell,
  Check,
  ChevronLeft,
  ChevronRight,
  Info,
  Mail,
  MessageCircle,
  RefreshCw,
  Search,
  Send,
  Users,
} from "lucide-react";
import { toast } from "react-hot-toast";
import { FormField, SelectField } from "@/components/shared/form-field";
import { Panel } from "@/components/shared/panel";
import { StatusBadge } from "@/components/shared/status-badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { dateTime } from "@/lib/format";
import {
  createCampaign,
  fetchCampaigns,
  fetchNotificationRecipients,
} from "./client-api";
import {
  notificationMedia,
  notificationTypes,
  type CampaignLog,
  type CampaignPagination,
  type NotificationMedia,
  type NotificationType,
  type NotificationRecipient,
  type RecipientPage,
} from "./types";
import { WhatsAppSessionsPanel } from "./whatsapp-sessions-panel";

type NotificationTab = "send" | "history" | "whatsapp";
const notificationTabs: NotificationTab[] = ["send", "history", "whatsapp"];

const initialCampaignDraft = {
  type: "PROMOTION" as NotificationType,
  media: "whatsapp" as NotificationMedia,
  title: "",
  message: "",
  redirectUrl: "",
};

const emptyPagination: CampaignPagination = {
  page: 1,
  totalPages: 1,
  totalDocs: 0,
  limit: 10,
  hasPrevPage: false,
  hasNextPage: false,
};

function fullName(recipient: Pick<NotificationRecipient, "firstName" | "lastName">) {
  return `${recipient.firstName} ${recipient.lastName}`.trim();
}

function messageFrom(error: unknown, fallback: string) {
  return error instanceof Error && error.message.trim() ? error.message : fallback;
}

function getRange(pagination: CampaignPagination, count: number) {
  if (!pagination.totalDocs || !count) return { start: 0, end: 0 };
  const start = (pagination.page - 1) * pagination.limit + 1;
  return {
    start,
    end: Math.min(start + count - 1, pagination.totalDocs),
  };
}

export function NotificationsView() {
  const [activeTab, setActiveTab] = useState<NotificationTab>("send");
  const [recipients, setRecipients] = useState<RecipientPage>({
    recipients: [],
    pagination: emptyPagination,
  });
  const [campaigns, setCampaigns] = useState<CampaignLog[]>([]);
  const [selectedRecipientIds, setSelectedRecipientIds] = useState<string[]>([]);
  const [recipientSearch, setRecipientSearch] = useState("");
  const [recipientQuery, setRecipientQuery] = useState("");
  const [recipientPage, setRecipientPage] = useState(1);
  const [recipientRefresh, setRecipientRefresh] = useState(0);
  const [recipientLoadedKey, setRecipientLoadedKey] = useState("");
  const [recipientFailure, setRecipientFailure] = useState<{
    requestKey: string;
    message: string;
  } | null>(null);
  const [historySearch, setHistorySearch] = useState("");
  const [historyQuery, setHistoryQuery] = useState("");
  const [historyType, setHistoryType] = useState<NotificationType | "">("");
  const [historyMedia, setHistoryMedia] = useState<NotificationMedia | "">("");
  const [historyPage, setHistoryPage] = useState(1);
  const [historyPagination, setHistoryPagination] = useState(emptyPagination);
  const [historyRefresh, setHistoryRefresh] = useState(0);
  const [historyLoadedKey, setHistoryLoadedKey] = useState("");
  const [historyFailure, setHistoryFailure] = useState<{
    requestKey: string;
    message: string;
  } | null>(null);
  const [draft, setDraft] = useState(initialCampaignDraft);
  const [formError, setFormError] = useState("");
  const [sending, setSending] = useState(false);
  const recipientRequestKey = [recipientQuery, recipientPage, recipientRefresh].join(":");
  const recipientsLoading = recipientLoadedKey !== recipientRequestKey;
  const recipientsError =
    recipientFailure?.requestKey === recipientRequestKey ? recipientFailure.message : "";
  const historyRequestKey = [
    historyQuery,
    historyType,
    historyMedia,
    historyPage,
    historyRefresh,
  ].join(":");
  const historyLoading = historyLoadedKey !== historyRequestKey;
  const historyError =
    historyFailure?.requestKey === historyRequestKey ? historyFailure.message : "";

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      setRecipientQuery(recipientSearch.trim());
      setRecipientPage(1);
    }, 350);
    return () => window.clearTimeout(timeout);
  }, [recipientSearch]);

  useEffect(() => {
    const controller = new AbortController();
    void fetchNotificationRecipients(
      { search: recipientQuery, page: recipientPage, limit: 10 },
      controller.signal,
    )
      .then((result) => {
        if (controller.signal.aborted) return;
        setRecipients(result);
        setRecipientFailure(null);
        setRecipientLoadedKey(recipientRequestKey);
      })
      .catch((error: unknown) => {
        if (!controller.signal.aborted) {
          setRecipients({ recipients: [], pagination: emptyPagination });
          setRecipientFailure({
            requestKey: recipientRequestKey,
            message: messageFrom(error, "Unable to load EV drivers. Please try again."),
          });
          setRecipientLoadedKey(recipientRequestKey);
        }
      });
    return () => controller.abort();
  }, [recipientPage, recipientQuery, recipientRefresh, recipientRequestKey]);

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      setHistoryQuery(historySearch.trim());
      setHistoryPage(1);
    }, 350);
    return () => window.clearTimeout(timeout);
  }, [historySearch]);

  useEffect(() => {
    const controller = new AbortController();
    void fetchCampaigns(
      {
        search: historyQuery,
        type: historyType,
        media: historyMedia,
        page: historyPage,
        limit: 10,
      },
      controller.signal,
    )
      .then((result) => {
        if (controller.signal.aborted) return;
        setCampaigns(result.campaigns);
        setHistoryPagination(result.pagination);
        setHistoryFailure(null);
        setHistoryLoadedKey(historyRequestKey);
      })
      .catch((error: unknown) => {
        if (!controller.signal.aborted) {
          setCampaigns([]);
          setHistoryPagination(emptyPagination);
          setHistoryFailure({
            requestKey: historyRequestKey,
            message: messageFrom(error, "Unable to load campaign history. Please try again."),
          });
          setHistoryLoadedKey(historyRequestKey);
        }
      });
    return () => controller.abort();
  }, [historyMedia, historyPage, historyQuery, historyRefresh, historyRequestKey, historyType]);

  const allVisibleSelected =
    recipients.recipients.length > 0 &&
    recipients.recipients.every((recipient) =>
      selectedRecipientIds.includes(recipient.id),
    );
  const recipientRange = getRange(recipients.pagination, recipients.recipients.length);
  const historyRange = getRange(historyPagination, campaigns.length);

  function moveTabFocus(event: KeyboardEvent<HTMLButtonElement>) {
    let nextTab: NotificationTab;
    if (event.key === "Home") {
      nextTab = "send";
    } else if (event.key === "End") {
      nextTab = "whatsapp";
    } else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
      const activeIndex = notificationTabs.indexOf(activeTab);
      const direction = event.key === "ArrowRight" ? 1 : -1;
      nextTab = notificationTabs[
        (activeIndex + direction + notificationTabs.length) % notificationTabs.length
      ];
    } else {
      return;
    }

    event.preventDefault();
    setActiveTab(nextTab);
    const tabIds: Record<NotificationTab, string> = {
      send: "send-campaign-tab",
      history: "campaign-history-tab",
      whatsapp: "whatsapp-tab",
    };
    document
      .getElementById(tabIds[nextTab])
      ?.focus();
  }

  function toggleRecipient(recipientId: string) {
    setSelectedRecipientIds((current) =>
      current.includes(recipientId)
        ? current.filter((id) => id !== recipientId)
        : [...current, recipientId],
    );
  }

  function toggleVisibleRecipients() {
    const visibleIds = recipients.recipients.map((recipient) => recipient.id);
    setSelectedRecipientIds((current) =>
      allVisibleSelected
        ? current.filter((id) => !visibleIds.includes(id))
        : [...new Set([...current, ...visibleIds])],
    );
  }

  async function submitCampaign(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const title = draft.title.trim();
    const message = draft.message.trim();

    if (!selectedRecipientIds.length) {
      setFormError("Select at least one EV driver.");
      return;
    }
    if (selectedRecipientIds.length > 500) {
      setFormError("A campaign can target up to 500 selected EV drivers at a time.");
      return;
    }
    if (!title || title.length > 200) {
      setFormError("Enter a title between 1 and 200 characters.");
      return;
    }
    if (!message || message.length > 1000) {
      setFormError("Enter a message between 1 and 1,000 characters.");
      return;
    }

    setSending(true);
    setFormError("");
    try {
      const result = await createCampaign({
        type: draft.type,
        media: draft.media,
        title,
        message,
        userIds: selectedRecipientIds,
        redirectUrl: draft.redirectUrl.trim() || undefined,
      });
      toast.success(result.message);
      setDraft(initialCampaignDraft);
      setSelectedRecipientIds([]);
      setRecipientSearch("");
      setRecipientQuery("");
      setRecipientPage(1);
      setActiveTab("history");
      setHistoryPage(1);
      setHistoryRefresh((version) => version + 1);
    } catch (error) {
      toast.error(messageFrom(error, "Unable to send the campaign. Please try again."));
    } finally {
      setSending(false);
    }
  }

  return (
    <div className="space-y-5">
      <div className="flex items-start gap-3 rounded-xl border border-primary/20 bg-primary/5 px-4 py-3 text-sm">
        <Info className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden="true" />
        <p className="text-muted-foreground">
          Campaign history, EV driver recipients, and WhatsApp sessions load from
          the backend. Campaign sends and new WhatsApp sessions are created there.
        </p>
      </div>

      <div className="border-b border-border">
        <div className="-mb-px flex gap-6" role="tablist" aria-label="Notifications">
          <button
            type="button"
            role="tab"
            id="send-campaign-tab"
            aria-selected={activeTab === "send"}
            aria-controls="send-campaign-panel"
            tabIndex={activeTab === "send" ? 0 : -1}
            onClick={() => setActiveTab("send")}
            onKeyDown={moveTabFocus}
            className={`border-b-2 px-1 py-3 text-sm font-medium transition-colors ${
              activeTab === "send"
                ? "border-primary text-primary"
                : "border-transparent text-muted-foreground hover:text-foreground"
            }`}
          >
            Send Campaign
          </button>
          <button
            type="button"
            role="tab"
            id="campaign-history-tab"
            aria-selected={activeTab === "history"}
            aria-controls="campaign-history-panel"
            tabIndex={activeTab === "history" ? 0 : -1}
            onClick={() => setActiveTab("history")}
            onKeyDown={moveTabFocus}
            className={`border-b-2 px-1 py-3 text-sm font-medium transition-colors ${
              activeTab === "history"
                ? "border-primary text-primary"
                : "border-transparent text-muted-foreground hover:text-foreground"
            }`}
          >
            History
          </button>
          <button
            type="button"
            role="tab"
            id="whatsapp-tab"
            aria-selected={activeTab === "whatsapp"}
            aria-controls="whatsapp-panel"
            tabIndex={activeTab === "whatsapp" ? 0 : -1}
            onClick={() => setActiveTab("whatsapp")}
            onKeyDown={moveTabFocus}
            className={`border-b-2 px-1 py-3 text-sm font-medium transition-colors ${
              activeTab === "whatsapp"
                ? "border-primary text-primary"
                : "border-transparent text-muted-foreground hover:text-foreground"
            }`}
          >
            WhatsApp Sessions
          </button>
        </div>
      </div>

      <div
        id="send-campaign-panel"
        role="tabpanel"
        aria-labelledby="send-campaign-tab"
        className="grid gap-5 xl:grid-cols-[minmax(0,1.15fr)_minmax(340px,0.85fr)]"
        hidden={activeTab !== "send"}
      >
        <Panel
          title="Recipients"
          description="Choose the EV drivers who should receive this campaign."
          actions={
            <span className="inline-flex items-center gap-1.5 rounded-full bg-muted px-3 py-1.5 text-xs font-medium text-muted-foreground">
              <Users className="size-3.5" aria-hidden="true" />
              {selectedRecipientIds.length} selected
            </span>
          }
        >
          <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div className="relative w-full sm:max-w-xs">
              <Search
                className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
                aria-hidden="true"
              />
              <Input
                aria-label="Search recipients"
                value={recipientSearch}
                onChange={(event) => setRecipientSearch(event.target.value)}
                placeholder="Search EV drivers..."
                className="pl-9"
              />
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={toggleVisibleRecipients}
                disabled={recipientsLoading || recipients.recipients.length === 0}
              >
                {allVisibleSelected ? "Clear visible" : "Select visible"}
              </Button>
              <Button
                type="button"
                variant="outline"
                size="icon"
                aria-label="Refresh EV driver list"
                title="Refresh EV driver list"
                disabled={recipientsLoading}
                onClick={() => setRecipientRefresh((version) => version + 1)}
              >
                <RefreshCw className={recipientsLoading ? "size-4 animate-spin" : "size-4"} />
              </Button>
            </div>
          </div>

          {recipientsError && (
            <div role="alert" className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
              <span>{recipientsError}</span>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => setRecipientRefresh((version) => version + 1)}
              >
                Retry
              </Button>
            </div>
          )}

          <div className="overflow-x-auto">
            <table className="data-table min-w-[650px]">
              <thead>
                <tr>
                  <th scope="col" className="w-12">
                    <input
                      type="checkbox"
                      aria-label="Select all visible EV drivers"
                      checked={allVisibleSelected}
                      onChange={toggleVisibleRecipients}
                      disabled={recipientsLoading || recipients.recipients.length === 0}
                      className="size-4 accent-primary"
                    />
                  </th>
                  <th scope="col">Name</th>
                  <th scope="col">Email</th>
                  <th scope="col">Status</th>
                </tr>
              </thead>
              <tbody>
                {recipientsLoading ? (
                  <tr>
                    <td colSpan={4} className="py-10 text-center text-muted-foreground">
                      Loading EV drivers…
                    </td>
                  </tr>
                ) : recipients.recipients.length ? (
                  recipients.recipients.map((recipient) => (
                    <tr key={recipient.id}>
                      <td>
                        <input
                          type="checkbox"
                          aria-label={`Select ${fullName(recipient)}`}
                          checked={selectedRecipientIds.includes(recipient.id)}
                          onChange={() => toggleRecipient(recipient.id)}
                          className="size-4 accent-primary"
                        />
                      </td>
                      <td className="font-medium">{fullName(recipient)}</td>
                      <td className="text-muted-foreground">{recipient.email || "—"}</td>
                      <td>
                        <StatusBadge tone={recipient.active ? "success" : "neutral"}>
                          {recipient.active ? "Active" : "Inactive"}
                        </StatusBadge>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={4} className="py-10 text-center text-muted-foreground">
                      {recipientsError ? "The recipient list is unavailable." : "No EV drivers match your search."}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          <div className="mt-4 flex flex-col gap-3 border-t border-border pt-4 text-sm text-muted-foreground sm:flex-row sm:items-center sm:justify-between">
            <span>
              Showing {recipientRange.start}–{recipientRange.end} of {recipients.pagination.totalDocs} EV drivers
            </span>
            <div className="flex items-center gap-2 self-end sm:self-auto">
              <Button
                type="button"
                variant="outline"
                size="icon"
                aria-label="Previous recipient page"
                disabled={!recipients.pagination.hasPrevPage || recipientsLoading}
                onClick={() => setRecipientPage((page) => Math.max(1, page - 1))}
              >
                <ChevronLeft className="size-4" />
              </Button>
              <span>Page {recipients.pagination.page} of {recipients.pagination.totalPages}</span>
              <Button
                type="button"
                variant="outline"
                size="icon"
                aria-label="Next recipient page"
                disabled={!recipients.pagination.hasNextPage || recipientsLoading}
                onClick={() => setRecipientPage((page) => page + 1)}
              >
                <ChevronRight className="size-4" />
              </Button>
            </div>
          </div>
        </Panel>

        <Panel
          title="Campaign details"
          description="Compose a notification for the selected EV drivers."
        >
          <form className="space-y-4" onSubmit={submitCampaign}>
            <div className="grid gap-4 sm:grid-cols-2">
              <SelectField
                label="Channel"
                name="media"
                value={draft.media}
                onChange={(event) =>
                  setDraft((current) => ({
                    ...current,
                    media: event.target.value as NotificationMedia,
                  }))
                }
                options={notificationMedia.map(({ value, label }) => ({ value, label }))}
              />
              <SelectField
                label="Type"
                name="type"
                value={draft.type}
                onChange={(event) =>
                  setDraft((current) => ({
                    ...current,
                    type: event.target.value as NotificationType,
                  }))
                }
                options={notificationTypes.map(({ value, label }) => ({ value, label }))}
              />
            </div>

            <FormField
              label="Title"
              name="title"
              value={draft.title}
              onChange={(event) =>
                setDraft((current) => ({ ...current, title: event.target.value }))
              }
              placeholder="Enter notification title"
              maxLength={200}
            />
            <p className="-mt-3 text-right text-xs text-muted-foreground">
              {draft.title.length}/200
            </p>

            <div>
              <label className="field-label" htmlFor="campaign-message">
                Message
              </label>
              <textarea
                id="campaign-message"
                value={draft.message}
                onChange={(event) =>
                  setDraft((current) => ({ ...current, message: event.target.value }))
                }
                placeholder="Write the notification message"
                maxLength={1000}
                rows={5}
                className="w-full resize-y rounded-lg border border-input bg-card px-4 py-3 text-sm outline-none transition-colors placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
              />
              <p className="mt-1 text-right text-xs text-muted-foreground">
                {draft.message.length}/1,000
              </p>
            </div>

            <FormField
              label="Redirect URL (optional)"
              name="redirectUrl"
              value={draft.redirectUrl}
              onChange={(event) =>
                setDraft((current) => ({
                  ...current,
                  redirectUrl: event.target.value,
                }))
              }
              placeholder="/locations or https://example.com"
            />

            <div className="rounded-lg border border-border bg-muted/40 px-4 py-3 text-sm">
              <p className="font-medium">Audience</p>
              <p className="mt-1 text-muted-foreground">
                EV drivers with the user role in your signed-in organization.
              </p>
            </div>

            {formError && (
              <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
                {formError}
              </p>
            )}

            <Button type="submit" className="w-full" disabled={sending}>
              <Send className={sending ? "size-4 animate-pulse" : "size-4"} aria-hidden="true" />
              {sending ? "Sending…" : "Send campaign"}
            </Button>
          </form>
        </Panel>
      </div>

      <div
        id="campaign-history-panel"
        role="tabpanel"
        aria-labelledby="campaign-history-tab"
        hidden={activeTab !== "history"}
      >
        <Panel
          title="Campaign History"
          description="Review campaign delivery results from the notification service."
          actions={
            <Button
              type="button"
              variant="outline"
              size="icon"
              aria-label="Refresh campaign history"
              title="Refresh campaign history"
              disabled={historyLoading}
              onClick={() => setHistoryRefresh((version) => version + 1)}
            >
              <RefreshCw className={historyLoading ? "size-4 animate-spin" : "size-4"} />
            </Button>
          }
        >
          <div className="mb-5 flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
            <div className="relative w-full lg:max-w-sm">
              <Search
                className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
                aria-hidden="true"
              />
              <Input
                aria-label="Search campaign history"
                value={historySearch}
                onChange={(event) => setHistorySearch(event.target.value)}
                placeholder="Search campaigns..."
                className="pl-9"
              />
            </div>
            <div className="grid w-full gap-3 sm:grid-cols-2 lg:w-auto">
              <SelectField
                label="Type"
                name="history-type"
                value={historyType}
                onChange={(event) => {
                  setHistoryType(event.target.value as NotificationType | "");
                  setHistoryPage(1);
                }}
                options={[
                  { value: "", label: "All types" },
                  ...notificationTypes.map(({ value, label }) => ({ value, label })),
                ]}
              />
              <SelectField
                label="Channel"
                name="history-media"
                value={historyMedia}
                onChange={(event) => {
                  setHistoryMedia(event.target.value as NotificationMedia | "");
                  setHistoryPage(1);
                }}
                options={[
                  { value: "", label: "All channels" },
                  ...notificationMedia.map(({ value, label }) => ({ value, label })),
                ]}
              />
            </div>
          </div>

          {historyError && (
            <div role="alert" className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
              <span>{historyError}</span>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => setHistoryRefresh((version) => version + 1)}
              >
                Retry
              </Button>
            </div>
          )}

          <div className="overflow-x-auto">
            <table className="data-table min-w-[900px]">
              <thead>
                <tr>
                  <th scope="col">Campaign</th>
                  <th scope="col">Type</th>
                  <th scope="col">Channel</th>
                  <th scope="col">Successful</th>
                  <th scope="col">Failed</th>
                  <th scope="col">Created at</th>
                </tr>
              </thead>
              <tbody>
                {historyLoading ? (
                  <tr>
                    <td colSpan={6} className="py-12 text-center text-muted-foreground">
                      Loading campaign history…
                    </td>
                  </tr>
                ) : campaigns.length ? (
                  campaigns.map((campaign) => (
                    <CampaignRow key={campaign.id} campaign={campaign} />
                  ))
                ) : (
                  <tr>
                    <td colSpan={6} className="py-12 text-center text-muted-foreground">
                      {historyError ? "Campaign history is unavailable." : "No campaigns match these filters."}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          <div className="mt-4 flex flex-col gap-3 border-t border-border pt-4 text-sm text-muted-foreground sm:flex-row sm:items-center sm:justify-between">
            <span>
              Showing {historyRange.start}–{historyRange.end} of {historyPagination.totalDocs} campaigns
            </span>
            <div className="flex items-center gap-2 self-end sm:self-auto">
              <Button
                type="button"
                variant="outline"
                size="icon"
                aria-label="Previous campaign page"
                disabled={!historyPagination.hasPrevPage || historyLoading}
                onClick={() => setHistoryPage((page) => Math.max(1, page - 1))}
              >
                <ChevronLeft className="size-4" />
              </Button>
              <span>Page {historyPagination.page} of {historyPagination.totalPages}</span>
              <Button
                type="button"
                variant="outline"
                size="icon"
                aria-label="Next campaign page"
                disabled={!historyPagination.hasNextPage || historyLoading}
                onClick={() => setHistoryPage((page) => page + 1)}
              >
                <ChevronRight className="size-4" />
              </Button>
            </div>
          </div>
        </Panel>
      </div>

      <div
        id="whatsapp-panel"
        role="tabpanel"
        aria-labelledby="whatsapp-tab"
        hidden={activeTab !== "whatsapp"}
      >
        {activeTab === "whatsapp" && <WhatsAppSessionsPanel />}
      </div>
    </div>
  );
}

function CampaignRow({ campaign }: { campaign: CampaignLog }) {
  const channelCounts = {
    webpush: {
      successful: campaign.success_webpush,
      failed: campaign.error_webpush,
    },
    email: {
      successful: campaign.success_email,
      failed: campaign.error_email,
    },
    whatsapp: {
      successful: campaign.success_whatsapp,
      failed: campaign.error_whatsapp,
    },
    fcm: {
      successful: campaign.success_fcm,
      failed: campaign.error_fcm,
    },
  }[campaign.media];
  const mediaOption = notificationMedia.find((option) => option.value === campaign.media);
  const ChannelIcon =
    campaign.media === "email"
      ? Mail
      : campaign.media === "whatsapp"
        ? MessageCircle
        : Bell;

  return (
    <tr>
      <td className="max-w-[340px]">
        <p className="truncate font-medium">{campaign.title}</p>
        <p className="mt-1 truncate text-xs text-muted-foreground">{campaign.message}</p>
      </td>
      <td>{campaign.type}</td>
      <td>
        <span className="inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-1 text-xs font-medium">
          <ChannelIcon className="size-3.5" aria-hidden="true" />
          {mediaOption?.label ?? campaign.media}
        </span>
      </td>
      <td>
        <span className="inline-flex items-center gap-1.5 text-emerald-600 dark:text-emerald-400">
          <Check className="size-4" aria-hidden="true" />
          {channelCounts.successful}
        </span>
      </td>
      <td>{channelCounts.failed}</td>
      <td className="whitespace-nowrap text-muted-foreground">
        {dateTime(campaign.created_at)}
      </td>
    </tr>
  );
}
