import { Badge } from "@workspace/ui/components/badge";
import { Button } from "@workspace/ui/components/button";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@workspace/ui/components/sheet";
import { Switch } from "@workspace/ui/components/switch";
import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
import { ProTable } from "@workspace/ui/composed/pro-table/pro-table";
import {
  getUserSubscribeById,
  getUserSubscribeDevices,
  kickOfflineByUserDevice,
} from "@workspace/ui/services/admin/user";
import { deviceIdToHash } from "@workspace/ui/utils/device";
import { AlertTriangle, Gauge } from "lucide-react";
import { type ReactNode, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { IpLink } from "@/components/ip-link";
import { formatDate } from "@/utils/common";

function SpeedLimitCard({ subscriptionId }: { subscriptionId: number }) {
  const { t } = useTranslation("user");
  const [detail, setDetail] = useState<API.UserSubscribeDetail | null>(null);

  useEffect(() => {
    getUserSubscribeById({ id: subscriptionId }).then(({ data }) => {
      if (data.data) setDetail(data.data);
    });
  }, [subscriptionId]);

  if (!detail || detail.status !== 1) return null;

  const baseSpeed = detail.subscribe?.speed_limit ?? 0;
  const effectiveSpeed = detail.effective_speed ?? 0;
  const isThrottled = detail.is_throttled;

  if (baseSpeed === 0 && !isThrottled) return null;

  return (
    <div
      className={`mb-4 flex items-start gap-3 rounded-lg border p-3 text-sm ${
        isThrottled
          ? "border-destructive/40 bg-destructive/5 text-destructive"
          : "border-border bg-muted/40 text-foreground"
      }`}
    >
      {isThrottled ? (
        <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
      ) : (
        <Gauge className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
      )}
      <div className="space-y-1">
        <div className="flex flex-wrap items-center gap-2 font-medium">
          {isThrottled ? (
            <>
              <span>{t("throttled", "Speed Throttled")}</span>
              <Badge className="text-xs" variant="destructive">
                {effectiveSpeed} Mbps
              </Badge>
              {baseSpeed > 0 && (
                <span className="text-muted-foreground text-xs line-through">
                  {baseSpeed} Mbps
                </span>
              )}
            </>
          ) : (
            <>
              <span className="text-muted-foreground">
                {t("speedLimit", "Speed Limit")}
              </span>
              <Badge className="text-xs" variant="secondary">
                {effectiveSpeed > 0
                  ? `${effectiveSpeed} Mbps`
                  : t("unlimited", "Unlimited")}
              </Badge>
            </>
          )}
        </div>
        {isThrottled && detail.throttle_rule && (
          <p className="text-muted-foreground text-xs">
            {detail.throttle_rule}
          </p>
        )}
        {isThrottled && detail.throttle_start && detail.throttle_end && (
          <p className="text-muted-foreground text-xs">
            {formatDate(detail.throttle_start)} ~{" "}
            {formatDate(detail.throttle_end)}
          </p>
        )}
      </div>
    </div>
  );
}

export function SubscriptionDetail({
  trigger,
  userId,
  subscriptionId,
}: {
  trigger: ReactNode;
  userId: number;
  subscriptionId: number;
}) {
  const { t } = useTranslation("user");
  const [open, setOpen] = useState(false);

  return (
    <Sheet onOpenChange={setOpen} open={open}>
      <SheetTrigger asChild>{trigger}</SheetTrigger>
      <SheetContent
        className="w-[700px] max-w-full md:max-w-screen-md"
        side="right"
      >
        <SheetHeader>
          <SheetTitle>{t("onlineDevices", "Online Devices")}</SheetTitle>
        </SheetHeader>
        <div className="mt-4 max-h-[calc(100dvh-120px)] overflow-y-auto">
          {open && <SpeedLimitCard subscriptionId={subscriptionId} />}
          <ProTable<API.UserDevice, Record<string, unknown>>
            actions={{
              render: (row) => {
                if (!row.identifier) return [];
                return [
                  <ConfirmButton
                    cancelText={t("cancel", "Cancel")}
                    confirmText={t("confirm", "Confirm")}
                    description={t(
                      "kickOfflineConfirm",
                      `Kick device ${row.ip} offline?`
                    )}
                    key="offline"
                    onConfirm={async () => {
                      await kickOfflineByUserDevice({ id: row.id });
                      toast.success(
                        t("kickOfflineSuccess", "Device kicked offline")
                      );
                    }}
                    title={t("confirmOffline", "Confirm Offline")}
                    trigger={
                      <Button variant="destructive">
                        {t("confirmOffline", "Confirm Offline")}
                      </Button>
                    }
                  />,
                ];
              },
            }}
            columns={[
              {
                accessorKey: "enabled",
                header: t("enable", "Enable"),
                cell: ({ row }) => (
                  <Switch
                    checked={row.getValue("enabled")}
                    onChange={(checked) => {
                      console.log("Switch:", checked);
                    }}
                  />
                ),
              },
              { accessorKey: "id", header: "ID" },
              {
                accessorKey: "identifier",
                header: t("deviceNo", "Device No."),
                cell: ({ row }) => {
                  const id = row.original.id;
                  return (
                    <span className="font-mono" title={row.original.identifier}>
                      {deviceIdToHash(id)}
                    </span>
                  );
                },
              },
              {
                accessorKey: "user_agent",
                header: t("userAgent", "User Agent"),
              },
              {
                accessorKey: "ip",
                header: "IP",
                cell: ({ row }) => <IpLink ip={row.getValue("ip")} />,
              },
              {
                accessorKey: "online",
                header: t("loginStatus", "Login Status"),
                cell: ({ row }) => (
                  <Badge
                    variant={row.getValue("online") ? "default" : "destructive"}
                  >
                    {row.getValue("online")
                      ? t("online", "Online")
                      : t("offline", "Offline")}
                  </Badge>
                ),
              },
              {
                accessorKey: "updated_at",
                header: t("lastSeen", "Last Seen"),
                cell: ({ row }) => formatDate(row.getValue("updated_at")),
              },
            ]}
            request={async (pagination) => {
              const { data } = await getUserSubscribeDevices({
                user_id: userId,
                subscribe_id: subscriptionId,
                ...pagination,
              });
              return {
                list: data.data?.list || [],
                total: data.data?.total || 0,
              };
            }}
          />
        </div>
      </SheetContent>
    </Sheet>
  );
}
