// BEGIN CHANGE: account house card - resumo da house da conta logada
"use client";

import Link from "next/link";
import { ItemIcon } from "@/components/ItemIcon";
import { CollapsiblePanel } from "@/components/CollapsiblePanel";
import { PlayerName } from "@/components/PlayerName";

type AccessList = {
  players: string[];
  guilds: { rank: string; guild: string }[];
  expressions: string[];
};

type HouseItem = {
  itemId: number;
  name: string;
  count: number;
  ownerName: string;
  location: string;
  syncedAt: number;
};

type DoorList = {
  doorId: number;
  players: string[];
  guilds: { rank: string; guild: string }[];
  expressions: string[];
};

export type AccountHouse = {
  houseId: number;
  worldId: number;
  houseName: string;
  ownerId: number;
  ownerName: string;
  town: number;
  size: number;
  price: number;
  rent: number;
  // BEGIN CHANGE: owner gold total (bank + backpack + depot)
  ownerBalance: number;
  ownerBank?: number;
  ownerInventory?: number;
  ownerDepot?: number;
  // END CHANGE
  paid: number;
  warnings: number;
  lastWarning: number;
  clear: boolean;
  isProtected: boolean;
  guild: boolean;
  rentStatus: string;
  daysLeft: number | null;
  doorsCount: number;
  beds: number;
  tiles: number;
  guests: AccessList;
  subowners: AccessList;
  doorLists: DoorList[];
  items: HouseItem[];
  itemCount: number;
  // BEGIN CHANGE: rent payment history
  rentHistory?: RentHistoryRow[];
  // END CHANGE
};

// BEGIN CHANGE: rent payment history row
export type RentHistoryRow = {
  id: number;
  amount: number;
  status: string;
  paidUntil: number;
  warnings: number;
  source: string;
  createdAt: number;
  playerName: string;
};
// END CHANGE

export type AccountHousePayload = {
  ok: boolean;
  hasHouse: boolean;
  housesPerAccount: number;
  rentPeriod: string;
  houseCleanDays: number;
  houses: AccountHouse[];
};

type Labels = {
  title: string;
  empty: string;
  goHouses: string;
  name: string;
  owner: string;
  rent: string;
  // BEGIN CHANGE: owner gold label
  ownerGold: string;
  ownerGoldBreakdown: string;
  // END CHANGE
  rentPeriod: string;
  rentPeriodDaily: string;
  rentPeriodWeekly: string;
  rentPeriodMonthly: string;
  rentPeriodYearly: string;
  rentPeriodNever: string;
  paidUntil: string;
  rentStatus: string;
  rentOk: string;
  rentDueSoon: string;
  rentOverdue: string;
  rentWarning: string;
  rentClear: string;
  rentUnknown: string;
  daysLeft: string;
  warnings: string;
  protection: string;
  protectionOn: string;
  protectionOff: string;
  guildHall: string;
  size: string;
  beds: string;
  doors: string;
  tiles: string;
  price: string;
  town: string;
  guests: string;
  subowners: string;
  doorLists: string;
  doorId: string;
  guildEntry: string;
  expression: string;
  none: string;
  itemsTitle: string;
  // BEGIN CHANGE: rent history labels
  rentHistoryTitle: string;
  rentHistoryEmpty: string;
  rentHistoryWhen: string;
  rentHistoryAmount: string;
  rentHistoryStatus: string;
  rentHistoryPaidUntil: string;
  rentHistorySource: string;
  rentStatusPaid: string;
  rentStatusWarning: string;
  rentStatusEvicted: string;
  rentStatusOther: string;
  // END CHANGE
  itemsEmpty: string;
  itemsSynced: string;
  itemLocation: string;
  itemOwner: string;
  itemName: string;
  limitNote: string;
};

type Props = {
  data: AccountHousePayload | null;
  loading: boolean;
  rentPeriod: string;
  labels: Labels;
};

function fmtGold(n: number): string {
  try {
    return n.toLocaleString("pt-BR");
  } catch {
    return String(n);
  }
}

function rentPeriodLabel(period: string, labels: Labels): string {
  switch (period) {
    case "weekly":
      return labels.rentPeriodWeekly;
    case "monthly":
      return labels.rentPeriodMonthly;
    case "yearly":
      return labels.rentPeriodYearly;
    case "never":
      return labels.rentPeriodNever;
    default:
      return labels.rentPeriodDaily;
  }
}

function rentStatusText(status: string, labels: Labels): string {
  switch (status) {
    case "ok":
      return labels.rentOk;
    case "due_soon":
      return labels.rentDueSoon;
    case "overdue":
      return labels.rentOverdue;
    case "warning":
      return labels.rentWarning;
    case "clear":
      return labels.rentClear;
    default:
      return labels.rentUnknown;
  }
}

function rentStatusClass(status: string): string {
  switch (status) {
    case "overdue":
    case "clear":
      return "text-red-400";
    case "warning":
    case "due_soon":
      return "text-amber-300";
    case "ok":
      return "text-emerald-400";
    default:
      return "text-muted";
  }
}

function AccessListBlock({
  list,
  labels,
}: {
  list: AccessList;
  labels: Labels;
}) {
  const hasPlayers = list.players.length > 0;
  const hasGuilds = list.guilds.length > 0;
  const hasExpr = list.expressions.length > 0;
  if (!hasPlayers && !hasGuilds && !hasExpr) {
    return <p className="text-sm text-muted">{labels.none}</p>;
  }
  return (
    <ul className="space-y-1 text-sm">
      {list.players.map((name) => (
        <li key={`p-${name}`}>
          <PlayerName name={name} size="inline" />
        </li>
      ))}
      {list.guilds.map((g, i) => (
        <li key={`g-${i}`} className="text-muted">
          {labels.guildEntry.replace("{rank}", g.rank || "-").replace("{guild}", g.guild || "-")}
        </li>
      ))}
      {list.expressions.map((ex) => (
        <li key={`e-${ex}`} className="font-mono text-xs text-muted">
          {labels.expression}: {ex}
        </li>
      ))}
    </ul>
  );
}

// BEGIN CHANGE: rent history status label
function rentHistoryStatusLabel(status: string, labels: Labels): string {
  if (status === "paid") return labels.rentStatusPaid;
  if (status === "warning") return labels.rentStatusWarning;
  if (status.startsWith("evicted")) return labels.rentStatusEvicted;
  return labels.rentStatusOther.replace("{status}", status || "-");
}
// END CHANGE

function HouseDetail({
  house,
  labels,
  rentPeriod,
}: {
  house: AccountHouse;
  labels: Labels;
  rentPeriod: string;
}) {
  const paidLabel =
    house.paid > 0
      ? new Date(house.paid * 1000).toLocaleString()
      : "-";

  return (
    <div className="space-y-4">
      <dl className="grid gap-3 text-sm sm:grid-cols-2">
        <div>
          <dt className="text-muted">{labels.name}</dt>
          <dd className="font-medium">{house.houseName || `#${house.houseId}`}</dd>
        </div>
        <div>
          <dt className="text-muted">{labels.owner}</dt>
          <dd className="font-medium">
            {house.ownerName ? <PlayerName name={house.ownerName} size="inline" /> : "-"}
          </dd>
        </div>
        <div>
          <dt className="text-muted">{labels.rent}</dt>
          <dd className="font-medium">{fmtGold(house.rent)} gp</dd>
        </div>
        {/* BEGIN CHANGE: owner total gold beside rent (bank+backpack+depot) */}
        <div>
          <dt className="text-muted">{labels.ownerGold}</dt>
          <dd className={`font-medium tabular-nums ${(house.ownerBalance ?? 0) < house.rent ? "text-amber-300" : "text-brand"}`}>
            {fmtGold(house.ownerBalance ?? 0)} gp
          </dd>
          <p className="mt-1 text-xs text-muted">
            {labels.ownerGoldBreakdown
              .replace("{bank}", fmtGold(house.ownerBank ?? house.ownerBalance ?? 0))
              .replace("{inv}", fmtGold(house.ownerInventory ?? 0))
              .replace("{depot}", fmtGold(house.ownerDepot ?? 0))}
          </p>
        </div>
        {/* END CHANGE */}
        <div>
          <dt className="text-muted">{labels.rentPeriod}</dt>
          <dd className="font-medium">{rentPeriodLabel(rentPeriod, labels)}</dd>
        </div>
        <div>
          <dt className="text-muted">{labels.paidUntil}</dt>
          <dd className="font-medium">{paidLabel}</dd>
        </div>
        <div>
          <dt className="text-muted">{labels.rentStatus}</dt>
          <dd className={`font-medium ${rentStatusClass(house.rentStatus)}`}>
            {rentStatusText(house.rentStatus, labels)}
            {house.daysLeft !== null && house.daysLeft >= 0 && house.rentStatus === "ok" && (
              <span className="ml-1 text-xs text-muted">
                ({labels.daysLeft.replace("{n}", String(house.daysLeft))})
              </span>
            )}
          </dd>
        </div>
        <div>
          <dt className="text-muted">{labels.warnings}</dt>
          <dd className="font-medium">{house.warnings}</dd>
        </div>
        <div>
          <dt className="text-muted">{labels.protection}</dt>
          <dd className="font-medium">
            {house.isProtected ? labels.protectionOn : labels.protectionOff}
          </dd>
        </div>
        <div>
          <dt className="text-muted">{labels.size}</dt>
          <dd className="font-medium">{house.size} sqm</dd>
        </div>
        <div>
          <dt className="text-muted">{labels.beds}</dt>
          <dd className="font-medium">{house.beds}</dd>
        </div>
        <div>
          <dt className="text-muted">{labels.doors}</dt>
          <dd className="font-medium">{house.doorsCount}</dd>
        </div>
        <div>
          <dt className="text-muted">{labels.tiles}</dt>
          <dd className="font-medium">{house.tiles}</dd>
        </div>
        <div>
          <dt className="text-muted">{labels.price}</dt>
          <dd className="font-medium">{fmtGold(house.price)} gp</dd>
        </div>
        <div>
          <dt className="text-muted">{labels.town}</dt>
          <dd className="font-medium">{house.town}</dd>
        </div>
        {house.guild && (
          <div className="sm:col-span-2">
            <span className="rounded-full bg-brand/15 px-2 py-0.5 text-xs font-semibold text-brand">
              {labels.guildHall}
            </span>
          </div>
        )}
      </dl>

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <h4 className="mb-2 text-sm font-medium">{labels.guests}</h4>
          <AccessListBlock list={house.guests} labels={labels} />
        </div>
        <div>
          <h4 className="mb-2 text-sm font-medium">{labels.subowners}</h4>
          <AccessListBlock list={house.subowners} labels={labels} />
        </div>
      </div>

      {house.doorLists.length > 0 && (
        <div>
          <h4 className="mb-2 text-sm font-medium">{labels.doorLists}</h4>
          <div className="space-y-3">
            {house.doorLists.map((d) => (
              <div key={d.doorId} className="rounded-lg border border-border/60 p-3">
                <p className="mb-2 text-xs text-muted">
                  {labels.doorId}: {d.doorId}
                </p>
                <AccessListBlock
                  list={{
                    players: d.players,
                    guilds: d.guilds,
                    expressions: d.expressions,
                  }}
                  labels={labels}
                />
              </div>
            ))}
          </div>
        </div>
      )}

      {/* BEGIN CHANGE: rent payment history table */}
      <div>
        <h4 className="mb-2 text-sm font-medium">{labels.rentHistoryTitle}</h4>
        {(house.rentHistory ?? []).length === 0 ? (
          <p className="text-sm text-muted">{labels.rentHistoryEmpty}</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[520px] text-left text-sm">
              <thead className="text-muted">
                <tr>
                  <th className="px-2 py-1.5 font-medium">{labels.rentHistoryWhen}</th>
                  <th className="px-2 py-1.5 font-medium">{labels.rentHistoryAmount}</th>
                  <th className="px-2 py-1.5 font-medium">{labels.rentHistoryStatus}</th>
                  <th className="px-2 py-1.5 font-medium">{labels.rentHistoryPaidUntil}</th>
                  <th className="px-2 py-1.5 font-medium">{labels.rentHistorySource}</th>
                </tr>
              </thead>
              <tbody>
                {(house.rentHistory ?? []).map((row) => (
                  <tr key={row.id} className="border-t border-border/40">
                    <td className="px-2 py-1.5 text-xs text-muted">
                      {row.createdAt > 0
                        ? new Date(row.createdAt * 1000).toLocaleString()
                        : "-"}
                    </td>
                    <td className="px-2 py-1.5 tabular-nums">{fmtGold(row.amount)} gp</td>
                    <td className="px-2 py-1.5">
                      {rentHistoryStatusLabel(row.status, labels)}
                      {row.warnings > 0 ? ` (${row.warnings})` : ""}
                    </td>
                    <td className="px-2 py-1.5 text-xs text-muted">
                      {row.paidUntil > 0
                        ? new Date(row.paidUntil * 1000).toLocaleString()
                        : "-"}
                    </td>
                    <td className="px-2 py-1.5 text-xs text-muted">{row.source || "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
      {/* END CHANGE */}

      <div>
        <h4 className="mb-2 text-sm font-medium">
          {labels.itemsTitle} ({house.itemCount})
        </h4>
        {house.items.length === 0 ? (
          <p className="text-sm text-muted">{labels.itemsEmpty}</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[520px] text-left text-sm">
              <thead className="text-muted">
                <tr>
                  <th className="px-2 py-1.5 font-medium">{labels.itemName}</th>
                  <th className="px-2 py-1.5 font-medium">{labels.itemLocation}</th>
                  <th className="px-2 py-1.5 font-medium">{labels.itemOwner}</th>
                </tr>
              </thead>
              <tbody>
                {house.items.map((it, idx) => (
                  <tr key={`${it.itemId}-${idx}`} className="border-t border-border/40">
                    <td className="px-2 py-1.5">
                      <div className="flex items-center gap-2">
                        <ItemIcon id={it.itemId} size={24} alt={it.name} />
                        <span>
                          {it.name || `#${it.itemId}`}
                          {it.count > 1 ? ` x${it.count}` : ""}
                        </span>
                      </div>
                    </td>
                    <td className="px-2 py-1.5 text-xs text-muted">{it.location || "-"}</td>
                    <td className="px-2 py-1.5 text-xs">{it.ownerName || "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        {house.items.length > 0 && house.items[0]?.syncedAt > 0 && (
          <p className="mt-2 text-xs text-muted">
            {labels.itemsSynced.replace(
              "{date}",
              new Date(house.items[0].syncedAt * 1000).toLocaleString(),
            )}
          </p>
        )}
      </div>
    </div>
  );
}

export function AccountHouseCard({ data, loading, rentPeriod, labels }: Props) {
  const headerRight = (
    <Link href="/houses" className="text-xs text-brand hover:underline">
      {labels.goHouses}
    </Link>
  );

  if (loading) {
    return (
      <CollapsiblePanel id="account-house" title={labels.title} headerRight={headerRight}>
        <p className="text-sm text-muted">...</p>
      </CollapsiblePanel>
    );
  }

  if (!data?.hasHouse || !data.houses.length) {
    return (
      <CollapsiblePanel id="account-house" title={labels.title} headerRight={headerRight}>
        <p className="text-sm text-muted">{labels.empty}</p>
        {data && data.housesPerAccount > 0 && (
          <p className="mt-2 text-xs text-muted">
            {labels.limitNote.replace("{n}", String(data.housesPerAccount))}
          </p>
        )}
      </CollapsiblePanel>
    );
  }

  const period = data.rentPeriod || rentPeriod;

  return (
    <CollapsiblePanel id="account-house" title={labels.title} headerRight={headerRight}>
      {data.houses.map((house) => (
        <HouseDetail
          key={`${house.houseId}-${house.worldId}`}
          house={house}
          labels={labels}
          rentPeriod={period}
        />
      ))}
      <p className="mt-4 text-xs text-muted">
        {labels.limitNote.replace("{n}", String(data.housesPerAccount))}
      </p>
    </CollapsiblePanel>
  );
}
// END CHANGE
