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 { Skeleton } from "@workspace/ui/components/skeleton";
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 { AlertCircle, 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);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  useEffect(() => {
    let ignore = false;

    setIsLoading(true);
    setIsError(false);
    getUserSubscribeById({ id: subscriptionId })
      .then(({ data }) => {
        if (!ignore) setDetail(data.data || null);
      })
      .catch(() => {
        if (!ignore) {
          setDetail(null);
          setIsError(true);
        }
      })
      .finally(() => {
        if (!ignore) setIsLoading(false);
      });

    return () => {
      ignore = true;
    };
  }, [subscriptionId]);

  if (isLoading) {
    return (
      <div className="mb-4 rounded-lg border bg-muted/30 p-3">
        <Skeleton className="mb-3 h-5 w-40" />
        <div className="grid grid-cols-2 gap-3">
          <Skeleton className="h-16" />
          <Skeleton className="h-16" />
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="mb-4 flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-destructive text-sm">
        <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
        <span>
          {t("subscriptionDetailLoadFailed", "Failed to load speed settings.")}
        </span>
      </div>
    );
  }

  if (!detail) {
    return (
      <div className="mb-4 rounded-lg border bg-muted/30 p-3 text-muted-foreground text-sm">
        {t("subscriptionDetailEmpty", "No subscription details found.")}
      </div>
    );
  }

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

  const baseSpeed = detail.subscribe?.speed_limit ?? 0;
  const userSpeed = detail.speed_limit ?? 0;
  const effectiveSpeed = detail.effective_speed ?? 0;
  const isThrottled = detail.is_throttled;
  const rules = detail.traffic_limit || [];
  const hasLimitConfig =
    baseSpeed > 0 || userSpeed > 0 || effectiveSpeed > 0 || rules.length > 0;

  if (!(hasLimitConfig || isThrottled)) {
    return (
      <div className="mb-4 rounded-lg border bg-muted/30 p-3 text-muted-foreground text-sm">
        {t("speedLimitEmpty", "No user-level speed limit rules configured.")}
      </div>
    );
  }

  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="min-w-0 flex-1 space-y-3">
        <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">
                  {t("subscriptionDefault", "Subscription Default")}:{" "}
                  {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>
        <div className="grid gap-2 sm:grid-cols-3">
          <SpeedMetric
            label={t("subscriptionDefault", "Subscription Default")}
            value={baseSpeed}
          />
          <SpeedMetric
            label={t("userOverride", "User Override")}
            value={userSpeed}
          />
          <SpeedMetric
            label={t("effectiveSpeed", "Effective Speed")}
            value={effectiveSpeed}
          />
        </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>
        )}
        {rules.length > 0 && (
          <div className="space-y-2">
            <p className="font-medium text-foreground text-xs">
              {t("trafficLimitRules", "Traffic Limit Rules")}
            </p>
            <div className="grid gap-2">
              {rules.map((rule, index) => (
                <div
                  className="rounded-md border bg-background/60 px-3 py-2 text-muted-foreground text-xs"
                  key={`${rule.stat_type}-${rule.stat_value}-${index}`}
                >
                  {t("trafficLimitRuleSummary", {
                    defaultValue:
                      "{{traffic}} GB in {{value}} {{type}} -> {{speed}} Mbps",
                    traffic: rule.traffic_usage,
                    value: rule.stat_value,
                    type:
                      rule.stat_type === "hour"
                        ? t("hour", "Hour")
                        : t("day", "Day"),
                    speed: rule.speed_limit,
                  })}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function SpeedMetric({ label, value }: { label: string; value: number }) {
  const { t } = useTranslation("user");

  return (
    <div className="rounded-md border bg-background/60 p-2">
      <div className="text-muted-foreground text-xs">{label}</div>
      <div className="font-medium text-foreground">
        {value > 0 ? `${value} Mbps` : t("unlimited", "Unlimited")}
      </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")} disabled />
                ),
              },
              { 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>
  );
}
