"use client";

import {
  Alert,
  AlertDescription,
  AlertTitle,
} from "@workspace/ui/components/alert";
import {
  Avatar,
  AvatarFallback,
  AvatarImage,
} from "@workspace/ui/components/avatar";
import { Badge } from "@workspace/ui/components/badge";
import Empty from "@workspace/ui/composed/empty";
import {
  ProTable,
  type ProTableActions,
} from "@workspace/ui/composed/pro-table/pro-table";
import { getAdminInviteList } from "@workspace/ui/services/admin/invite";
import { CircleAlert } from "lucide-react";
import { useRef } from "react";
import { useTranslation } from "react-i18next";
import { Display } from "@/components/display";
import { formatDate } from "@/utils/common";

type InviteFilters = {
  search?: string;
  inviter_id?: string;
  invitee_id?: string;
};

function toOptionalNumber(value?: string) {
  if (!value) return;
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : undefined;
}

function InviteUserCell({
  id,
  identifier,
  avatar,
}: {
  id: number;
  identifier: string;
  avatar?: string;
}) {
  const fallback = identifier?.charAt(0)?.toUpperCase() || "U";

  return (
    <div className="flex min-w-48 items-center gap-2">
      <Avatar className="h-8 w-8">
        <AvatarImage alt={identifier || `#${id}`} src={avatar} />
        <AvatarFallback className="text-xs">{fallback}</AvatarFallback>
      </Avatar>
      <div className="min-w-0">
        <div className="font-medium text-sm">#{id}</div>
        <div className="max-w-52 truncate text-muted-foreground text-xs">
          {identifier || "--"}
        </div>
      </div>
    </div>
  );
}

function InviteIdentifierCell({
  id,
  identifier,
}: {
  id: number;
  identifier: string;
}) {
  return (
    <div className="min-w-44">
      <div className="font-medium text-sm">#{id}</div>
      <div className="max-w-52 truncate text-muted-foreground text-xs">
        {identifier || "--"}
      </div>
    </div>
  );
}

export default function InviteManagement() {
  const { t } = useTranslation("invite");
  const ref = useRef<ProTableActions>(null);

  return (
    <ProTable<API.AdminInviteRelation, InviteFilters>
      action={ref}
      columns={[
        {
          accessorKey: "inviter_id",
          header: t("inviter", "Inviter"),
          cell: ({ row }) => (
            <InviteIdentifierCell
              id={row.original.inviter_id}
              identifier={row.original.inviter_identifier}
            />
          ),
        },
        {
          accessorKey: "invitee_id",
          header: t("invitee", "Invitee"),
          cell: ({ row }) => (
            <InviteUserCell
              avatar={row.original.invitee_avatar}
              id={row.original.invitee_id}
              identifier={row.original.invitee_identifier}
            />
          ),
        },
        {
          accessorKey: "invitee_enable",
          header: t("status", "Status"),
          cell: ({ row }) => (
            <Badge
              variant={row.original.invitee_enable ? "default" : "secondary"}
            >
              {row.original.invitee_enable
                ? t("enabled", "Enabled")
                : t("disabled", "Disabled")}
            </Badge>
          ),
        },
        {
          accessorKey: "invited_at",
          header: t("invitedAt", "Invited At"),
          cell: ({ row }) => formatDate(row.original.invited_at),
        },
        {
          accessorKey: "order_count",
          header: t("orderCount", "Orders"),
        },
        {
          accessorKey: "has_purchased",
          header: t("hasPurchased", "Purchased"),
          cell: ({ row }) => (
            <Badge variant={row.original.has_purchased ? "default" : "outline"}>
              {row.original.has_purchased ? t("yes", "Yes") : t("no", "No")}
            </Badge>
          ),
        },
        {
          accessorKey: "inviter_commission",
          header: t("commission", "Commission"),
          cell: ({ row }) => (
            <Display type="currency" value={row.original.inviter_commission} />
          ),
        },
        {
          accessorKey: "inviter_gift_days",
          header: t("inviterGiftDays", "Inviter Gift Days"),
          cell: ({ row }) =>
            t("days", "{{count}} days", {
              count: row.original.inviter_gift_days,
            }),
        },
        {
          accessorKey: "invitee_gift_days",
          header: t("inviteeGiftDays", "Invitee Gift Days"),
          cell: ({ row }) =>
            t("days", "{{count}} days", {
              count: row.original.invitee_gift_days,
            }),
        },
      ]}
      empty={<Empty description={t("empty", "No invite records")} />}
      error={
        <Alert className="mx-auto max-w-md" variant="destructive">
          <CircleAlert aria-hidden="true" />
          <AlertTitle>
            {t("loadErrorTitle", "Failed to load invites")}
          </AlertTitle>
          <AlertDescription>
            {t("loadErrorDescription", "Refresh the table or try again later.")}
          </AlertDescription>
        </Alert>
      }
      header={{ title: t("title", "Invite Management") }}
      params={[
        {
          key: "search",
          placeholder: t("searchPlaceholder", "Email or phone"),
        },
        {
          key: "inviter_id",
          placeholder: t("inviterId", "Inviter ID"),
        },
        {
          key: "invitee_id",
          placeholder: t("inviteeId", "Invitee ID"),
        },
      ]}
      request={async (pagination, filters) => {
        const { data } = await getAdminInviteList({
          page: pagination.page,
          size: pagination.size,
          search: filters.search?.trim() || undefined,
          inviter_id: toOptionalNumber(filters.inviter_id),
          invitee_id: toOptionalNumber(filters.invitee_id),
        });

        return {
          list:
            data.data?.list.map((item) => ({
              ...item,
              id: `${item.inviter_id}-${item.invitee_id}-${item.invited_at}`,
            })) || [],
          total: data.data?.total || 0,
        };
      }}
    />
  );
}
