"use client";

import { useQuery } from "@tanstack/react-query";
import { ChevronRight, Megaphone, ClipboardList } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { TableSkeleton } from "@/components/shared/states";
import { PushBroadcastStatusBadge, PushDeliveryStatusBadge } from "@/features/push/push-badges";
import { getPushBroadcasts, getPushDeliveries } from "@/services/push";
import { queryKeys } from "@/lib/query-keys";
import { useI18n, useT } from "@/i18n";
import { formatRelative } from "@/lib/format";

export type PushTab = "overview" | "broadcasts" | "deliveries" | "devices" | "failedJobs";

function SectionHeading({
  title,
  onNavigate,
  tab,
}: {
  title: string;
  onNavigate: (tab: PushTab) => void;
  tab: PushTab;
}) {
  const t = useT();
  return (
    <div className="flex items-center justify-between gap-3">
      <CardTitle className="text-base">{title}</CardTitle>
      <Button variant="ghost" size="sm" onClick={() => onNavigate(tab)} className="gap-1">
        {t("common.viewAll")}
        <ChevronRight className="h-3.5 w-3.5 rtl:rotate-180" aria-hidden />
      </Button>
    </div>
  );
}

/**
 * The overview tab of the push module: the health tiles live above this, and
 * here the two feeds the support desk checks first — the latest broadcasts and
 * the newest pushes — with a jump to their full logs.
 */
export function OverviewTab({ onNavigate }: { onNavigate: (tab: PushTab) => void }) {
  const t = useT();
  const { locale } = useI18n();

  const broadcastFilters = { page: 1, rows: 4 };
  const broadcastQuery = useQuery({
    queryKey: queryKeys.push.broadcasts(broadcastFilters),
    queryFn: () => getPushBroadcasts(broadcastFilters),
  });

  const deliveryFilters = { page: 1, rows: 6 };
  const deliveryQuery = useQuery({
    queryKey: queryKeys.push.deliveries(deliveryFilters),
    queryFn: () => getPushDeliveries(deliveryFilters),
  });

  const broadcasts = broadcastQuery.data?.Model ?? [];

  return (
    <div className="grid gap-4 lg:grid-cols-2">
      <Card>
        <CardHeader className="pb-2">
          <SectionHeading title={t("push.recentBroadcasts")} onNavigate={onNavigate} tab="broadcasts" />
        </CardHeader>
        <CardContent>
          {broadcastQuery.isPending ? (
            <TableSkeleton rows={4} cols={1} />
          ) : broadcastQuery.isError ? (
            <p className="text-sm text-destructive">{String(broadcastQuery.error)}</p>
          ) : broadcasts.length === 0 ? (
            <div className="flex flex-col items-center gap-2 py-8 text-center">
              <Megaphone className="h-8 w-8 text-muted-foreground" aria-hidden />
              <p className="text-sm text-muted-foreground">{t("push.emptyBroadcasts")}</p>
            </div>
          ) : (
            <ul className="divide-y" role="list">
              {broadcasts.map((broadcast) => (
                <li key={broadcast.uuid} className="flex items-center gap-3 py-2.5">
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium text-foreground">{broadcast.title}</p>
                    <p className="truncate text-xs text-muted-foreground">{broadcast.body}</p>
                  </div>
                  <div className="flex shrink-0 items-center gap-2">
                    <Badge variant="accent" className="hidden sm:inline-flex">
                      {broadcast.audience_label}
                    </Badge>
                    <PushBroadcastStatusBadge status={broadcast.status} label={broadcast.status_label} />
                    <span className="numeric text-xs text-muted-foreground" title={formatRelative(broadcast.created_at, locale)}>
                      {formatRelative(broadcast.created_at, locale)}
                    </span>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-2">
          <SectionHeading title={t("push.recentDeliveries")} onNavigate={onNavigate} tab="deliveries" />
        </CardHeader>
        <CardContent>
          {deliveryQuery.isPending ? (
            <TableSkeleton rows={6} cols={1} />
          ) : deliveryQuery.isError ? (
            <p className="text-sm text-destructive">{String(deliveryQuery.error)}</p>
          ) : (deliveryQuery.data?.Model ?? []).length === 0 ? (
            <div className="flex flex-col items-center gap-2 py-8 text-center">
              <ClipboardList className="h-8 w-8 text-muted-foreground" aria-hidden />
              <p className="text-sm text-muted-foreground">{t("push.emptyDeliveries")}</p>
            </div>
          ) : (
            <ul className="divide-y" role="list">
              {(deliveryQuery.data?.Model ?? []).map((delivery) => (
                <li key={delivery.uuid} className="flex items-center gap-3 py-2.5">
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium text-foreground">
                      {delivery.recipient?.name ?? "—"}
                    </p>
                    <p className="truncate text-xs text-muted-foreground">{delivery.title}</p>
                  </div>
                  <div className="flex shrink-0 items-center gap-2">
                    <PushDeliveryStatusBadge status={delivery.status} label={delivery.status_label} />
                    <span className="numeric text-xs text-muted-foreground" title={formatRelative(delivery.created_at, locale)}>
                      {formatRelative(delivery.created_at, locale)}
                    </span>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>
    </div>
  );
}