"use client";

import { Pencil, Plus, Trash2, Network } from "lucide-react";
import { useTranslation } from "react-i18next";

import { AdminSubnav, AdminSubnavButton } from "@/components/admin/admin-subnav";
import { AdminNoResourceState } from "@/components/admin/admin-no-resource-state";
import { AdminLoadingInline } from "@/components/admin/admin-loading-state";
import { AdminStatusBadge } from "@/components/admin/admin-status-badge";
import { AdminRowActionsMenu } from "@/components/admin/admin-row-actions-menu";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { AgentsPlayersPanel } from "@/modules/agents/agents-players-panel";
import { AgentProfileFields, type AgentProfileFieldsProps } from "@/modules/agents/agent-profile-fields";
import { formatCredit } from "@/modules/agents/agent-line-sidebar";
import { Button } from "@/components/ui/button";
import { percentValueToUi } from "@/lib/admin-rate-percent";
import { relativeShareRateUiFromTotal } from "@/lib/agent-profile-caps";
import { resolveRoleStatusTone } from "@/lib/admin-status-tone";
import { AdminTableMoney, adminMoneyCellClassName } from "@/components/admin/admin-table-money";
import type { AgentNodeRow, AgentProfileRow } from "@/types/api/admin-agent";

export type AgentDetailTab = "profile" | "downline" | "players";

export type AgentLineDetailPanelProps = {
  node: AgentNodeRow | null;
  profile: AgentProfileRow | null;
  profileLoading: boolean;
  profileError?: string | null;
  childAgents: AgentNodeRow[];
  childCountById: Map<number, number>;
  directPlayerCount?: number;
  onDirectPlayerCountChange?: (count: number) => void;
  siteCode: string;
  parentName: string | null;
  detailTab: AgentDetailTab;
  onDetailTabChange: (tab: AgentDetailTab) => void;
  canViewProfileTab: boolean;
  canSaveProfileTab: boolean;
  canViewDownlineTab: boolean;
  canViewPlayersTab: boolean;
  canManageNode: boolean;
  canCreateChild: boolean;
  canCreatePlayerAction: boolean;
  canDeleteChild: (node: AgentNodeRow) => boolean;
  onEditChild: (node: AgentNodeRow) => void;
  onDeleteChild: (node: AgentNodeRow) => void;
  onAddChild: () => void;
  onEditCurrent: () => void;
  onSelectChild: (node: AgentNodeRow) => void;
  profileFields: AgentProfileFieldsProps | null;
  profileSaving: boolean;
  onSaveProfile: () => void;
};

export function AgentLineDetailPanel({
  node,
  profile,
  profileLoading,
  profileError = null,
  childAgents,
  childCountById,
  directPlayerCount,
  onDirectPlayerCountChange,
  siteCode,
  parentName,
  detailTab,
  onDetailTabChange,
  canViewProfileTab,
  canSaveProfileTab,
  canViewDownlineTab,
  canViewPlayersTab,
  canManageNode,
  canCreateChild,
  canCreatePlayerAction,
  canDeleteChild,
  onEditChild,
  onDeleteChild,
  onAddChild,
  onEditCurrent,
  onSelectChild,
  profileFields,
  profileSaving,
  onSaveProfile,
}: AgentLineDetailPanelProps): React.ReactElement {
  const { t } = useTranslation(["agents", "common"]);

  if (node === null) {
    return (
      <div className="flex flex-1 flex-col items-center justify-center px-6 py-20 text-center">
        <div className="flex size-14 items-center justify-center rounded-2xl border border-dashed border-border/80">
          <Network className="size-6 text-muted-foreground/70" aria-hidden />
        </div>
        <p className="mt-4 text-sm font-medium text-foreground">
          {t("lineUi.selectAgent", { defaultValue: "选择左侧代理" })}
        </p>
      </div>
    );
  }

  const tabs: { key: AgentDetailTab; label: string; count?: number; visible: boolean }[] = [
    {
      key: "profile",
      label: t("lineUi.tabProfileShort", { defaultValue: "占成授信" }),
      visible: canViewProfileTab,
    },
    {
      key: "downline",
      label: t("lineUi.tabDownline", { defaultValue: "直属下级" }),
      count: childAgents.length,
      visible: canViewDownlineTab,
    },
    {
      key: "players",
      label: t("lineUi.tabPlayers", { defaultValue: "直属玩家" }),
      count: directPlayerCount,
      visible: canViewPlayersTab,
    },
  ];

  const metaParts = [
    parentName
      ? t("lineUi.parentMeta", { defaultValue: "上级 {{name}}", name: parentName })
      : null,
    node.username?.trim() ? node.username : node.code,
  ].filter(Boolean);

  return (
    <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
      <div className="shrink-0 border-b border-border/60">
        <header className="px-5 py-4 sm:px-6">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div className="min-w-0 flex-1 space-y-2">
              <div className="flex flex-wrap items-center gap-2">
                <h2 className="truncate text-lg font-semibold tracking-tight">{node.name}</h2>
                <AdminStatusBadge tone={resolveRoleStatusTone(node.status)} className="shrink-0">
                  {node.status === 1
                    ? t("common:status.enabled", { defaultValue: "启用" })
                    : t("common:status.disabled", { defaultValue: "停用" })}
                </AdminStatusBadge>
              </div>
              {metaParts.length > 0 ? (
                <p className="truncate text-sm text-muted-foreground">{metaParts.join(" · ")}</p>
              ) : null}
              <AgentHeaderMetrics node={node} profile={profile} loading={profileLoading} />
            </div>
            {canManageNode ? (
              <Button type="button" size="sm" variant="outline" onClick={onEditCurrent}>
                <Pencil className="mr-1.5 size-3.5" />
                {t("lineUi.editAgent", { defaultValue: "编辑" })}
              </Button>
            ) : null}
          </div>
        </header>

        <AdminSubnav
          aria-label={t("detailTabs", { defaultValue: "代理详情" })}
          className="min-h-11 overflow-x-auto px-4 sm:px-5"
        >
          {tabs
            .filter((tab) => tab.visible)
            .map((tab) => (
              <AdminSubnavButton
                key={tab.key}
                active={detailTab === tab.key}
                onClick={() => onDetailTabChange(tab.key)}
                count={tab.count}
              >
                {tab.label}
              </AdminSubnavButton>
            ))}
        </AdminSubnav>
      </div>

      <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 py-5 sm:px-6 sm:py-6">
        {profileError ? (
          <p className="mb-4 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
            {profileError}
          </p>
        ) : null}

        {profileLoading && detailTab === "profile" ? (
          <AdminLoadingInline className="py-16" />
        ) : null}

        {detailTab === "profile" && canViewProfileTab && profileFields && !profileLoading ? (
          <div className="mx-auto max-w-3xl space-y-5">
            <AgentProfileFields {...profileFields} idPrefix="inline-agent-profile" variant="card" />
            {canSaveProfileTab ? (
              <div className="flex justify-end">
                <Button
                  type="button"
                  disabled={profileSaving || profileFields.loading}
                  onClick={onSaveProfile}
                >
                  {profileSaving
                    ? t("common:actions.saving", { defaultValue: "保存中…" })
                    : t("lineUi.saveProfile", { defaultValue: "保存" })}
                </Button>
              </div>
            ) : null}
          </div>
        ) : null}

        {detailTab === "downline" && canViewDownlineTab ? (
          <DownlineSection
            childAgents={childAgents}
            childCountById={childCountById}
            parentTotalShareRate={
              profile?.total_share_rate ?? node.profile_summary?.total_share_rate ?? null
            }
            canManageNode={canManageNode}
            canCreateChild={canCreateChild}
            canDeleteChild={canDeleteChild}
            onEditChild={onEditChild}
            onDeleteChild={onDeleteChild}
            onSelectChild={onSelectChild}
            onAddChild={onAddChild}
          />
        ) : null}

        {detailTab === "players" && canViewPlayersTab ? (
          <AgentsPlayersPanel
            siteCode={siteCode}
            agentNodeId={node.id}
            allowCreatePlayer={canCreatePlayerAction}
            embedded
            onTotalChange={onDirectPlayerCountChange}
          />
        ) : null}
      </div>
    </div>
  );
}

function AgentHeaderMetrics({
  node,
  profile,
  loading,
}: {
  node: AgentNodeRow;
  profile: AgentProfileRow | null;
  loading: boolean;
}): React.ReactElement {
  const { t } = useTranslation("agents");

  if (loading) {
    return <p className="text-sm text-muted-foreground">…</p>;
  }

  const totalShare = profile?.total_share_rate ?? node.profile_summary?.total_share_rate ?? 0;
  const parentShare = profile?.parent_caps?.total_share_rate;
  const relativeShareUi = relativeShareRateUiFromTotal(totalShare, parentShare);
  const shareMetric =
    relativeShareUi !== null
      ? `${t("profile.relativeShareRateValue", {
          defaultValue: "占上级 {{rate}}%",
          rate: relativeShareUi,
        })}（${t("profile.actualShareRate", {
          defaultValue: "实际占成 {{rate}}%",
          rate: percentValueToUi(totalShare),
        })}）`
      : `${t("profile.totalShareRate", { defaultValue: "占成" })} ${percentValueToUi(totalShare)}%`;

  const items = [
    shareMetric,
    `${t("profile.creditLimit", { defaultValue: "授信" })} ${formatCredit(profile?.credit_limit ?? 0)}`,
    `${t("lineUi.availableCredit", { defaultValue: "可下发" })} ${formatCredit(profile?.available_credit ?? 0)}`,
    `${t("profile.rebateLimit", { defaultValue: "回水上限" })} ${percentValueToUi(profile?.rebate_limit ?? 0)}%`,
  ];

  return (
    <p className="text-sm text-muted-foreground">
      {items.join(" · ")}
    </p>
  );
}

function DownlineSection({
  childAgents,
  childCountById,
  parentTotalShareRate,
  canManageNode,
  canCreateChild,
  canDeleteChild,
  onEditChild,
  onDeleteChild,
  onSelectChild,
  onAddChild,
}: {
  childAgents: AgentNodeRow[];
  childCountById: Map<number, number>;
  parentTotalShareRate: number | null;
  canManageNode: boolean;
  canCreateChild: boolean;
  canDeleteChild: (node: AgentNodeRow) => boolean;
  onEditChild: (node: AgentNodeRow) => void;
  onDeleteChild: (node: AgentNodeRow) => void;
  onSelectChild: (node: AgentNodeRow) => void;
  onAddChild: () => void;
}): React.ReactElement {
  const { t } = useTranslation(["agents", "common"]);

  if (childAgents.length === 0) {
    return (
      <AdminNoResourceState message={t("lineUi.downlineEmptyShort", { defaultValue: "暂无直属下级" })}>
        {canManageNode && canCreateChild ? (
          <Button type="button" size="sm" onClick={onAddChild}>
            <Plus className="mr-1.5 size-3.5" />
            {t("createChild", { defaultValue: "添加下级" })}
          </Button>
        ) : null}
      </AdminNoResourceState>
    );
  }

  return (
    <div className="space-y-3">
      {canManageNode && canCreateChild ? (
        <div className="flex justify-end">
          <Button type="button" size="sm" onClick={onAddChild}>
            <Plus className="mr-1.5 size-3.5" />
            {t("createChild", { defaultValue: "添加下级" })}
          </Button>
        </div>
      ) : null}
      <DownlineTable
        childAgents={childAgents}
        childCountById={childCountById}
        parentTotalShareRate={parentTotalShareRate}
        canManageNode={canManageNode}
        onEditChild={onEditChild}
        onDeleteChild={onDeleteChild}
        onSelectChild={onSelectChild}
        canDeleteChild={canDeleteChild}
      />
    </div>
  );
}

function DownlineTable({
  childAgents,
  childCountById,
  parentTotalShareRate,
  canManageNode,
  canDeleteChild,
  onEditChild,
  onDeleteChild,
  onSelectChild,
}: {
  childAgents: AgentNodeRow[];
  childCountById: Map<number, number>;
  parentTotalShareRate: number | null;
  canManageNode: boolean;
  canDeleteChild: (node: AgentNodeRow) => boolean;
  onEditChild: (node: AgentNodeRow) => void;
  onDeleteChild: (node: AgentNodeRow) => void;
  onSelectChild: (node: AgentNodeRow) => void;
}): React.ReactElement {
  const { t } = useTranslation(["agents", "common"]);
  const showRelativeShare =
    parentTotalShareRate !== null && Number(parentTotalShareRate) > 0;

  return (
    <div className="admin-table-inset overflow-hidden">
      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow className="hover:bg-transparent">
              <TableHead>{t("agentName", { defaultValue: "名称" })}</TableHead>
              <TableHead>{t("loginUsername", { defaultValue: "登录名" })}</TableHead>
              <TableHead className="text-right whitespace-nowrap">
                {showRelativeShare
                  ? t("profile.totalShareWithRelative", { defaultValue: "实际占成 / 占上级" })
                  : t("profile.totalShareRate", { defaultValue: "占成" })}
              </TableHead>
              <TableHead className="text-right whitespace-nowrap">
                {t("profile.creditLimit", { defaultValue: "授信" })}
              </TableHead>
              <TableHead className="text-right whitespace-nowrap">
                {t("lineUi.availableCredit", { defaultValue: "可下发" })}
              </TableHead>
              <TableHead className="text-center whitespace-nowrap">
                {t("lineUi.downlineColumns.downlineCount", { defaultValue: "下级" })}
              </TableHead>
              <TableHead>{t("common:status.label", { defaultValue: "状态" })}</TableHead>
              {canManageNode ? (
                <TableHead className="sticky right-0 z-20 w-14 text-center shadow-[-1px_0_0_rgba(203,213,225,0.7)]">
                  {t("common:table.actions", { defaultValue: "操作" })}
                </TableHead>
              ) : null}
            </TableRow>
          </TableHeader>
          <TableBody>
            {childAgents.map((child) => {
              const summary = child.profile_summary;
              return (
                <TableRow
                  key={child.id}
                  className="cursor-pointer"
                  onClick={() => onSelectChild(child)}
                >
                  <TableCell>
                    <div className="font-medium">{child.name}</div>
                    <div className="font-mono text-xs text-muted-foreground">{child.code}</div>
                  </TableCell>
                  <TableCell className="text-sm">{child.username ?? "—"}</TableCell>
                  <TableCell className="text-right text-sm">
                    {summary ? (
                      <DownlineShareCell
                        totalShareRate={summary.total_share_rate}
                        parentTotalShareRate={parentTotalShareRate}
                      />
                    ) : (
                      "—"
                    )}
                  </TableCell>
                  <TableCell className={adminMoneyCellClassName("text-right text-sm")}>
                    {summary ? <AdminTableMoney>{formatCredit(summary.credit_limit)}</AdminTableMoney> : "—"}
                  </TableCell>
                  <TableCell className={adminMoneyCellClassName("text-right text-sm")}>
                    {summary ? (
                      <AdminTableMoney>{formatCredit(summary.available_credit)}</AdminTableMoney>
                    ) : (
                      "—"
                    )}
                  </TableCell>
                  <TableCell className="text-center tabular-nums text-sm">
                    {childCountById.get(child.id) ?? 0}
                  </TableCell>
                  <TableCell>
                    <AdminStatusBadge tone={resolveRoleStatusTone(child.status)} className="shrink-0">
                      {child.status === 1
                        ? t("common:status.enabled", { defaultValue: "启用" })
                        : t("common:status.disabled", { defaultValue: "停用" })}
                    </AdminStatusBadge>
                  </TableCell>
                  {canManageNode ? (
                    <TableCell
                      className="sticky right-0 z-10 text-center shadow-[-1px_0_0_rgba(203,213,225,0.7)]"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <AdminRowActionsMenu
                        actions={[
                          {
                            key: "edit",
                            label: t("lineUi.editDownline", { defaultValue: "编辑" }),
                            icon: Pencil,
                            onClick: () => onEditChild(child),
                          },
                          {
                            key: "delete",
                            label: t("lineUi.deleteDownline", { defaultValue: "删除" }),
                            icon: Trash2,
                            destructive: true,
                            disabled: !canDeleteChild(child),
                            onClick: () => onDeleteChild(child),
                          },
                        ]}
                      />
                    </TableCell>
                  ) : null}
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}

function DownlineShareCell({
  totalShareRate,
  parentTotalShareRate,
}: {
  totalShareRate: number;
  parentTotalShareRate: number | null;
}): React.ReactElement {
  const { t } = useTranslation("agents");
  const relativeShareUi = relativeShareRateUiFromTotal(totalShareRate, parentTotalShareRate);

  if (relativeShareUi !== null) {
    return (
      <div className="tabular-nums">
        <div>{percentValueToUi(totalShareRate)}%</div>
        <div className="text-xs text-muted-foreground">
          {t("profile.relativeShareRateValue", {
            defaultValue: "占上级 {{rate}}%",
            rate: relativeShareUi,
          })}
        </div>
      </div>
    );
  }

  return <div className="tabular-nums">{percentValueToUi(totalShareRate)}%</div>;
}
