"use client";

import React from "react";

import { Button } from "../Button/";
import { Icon } from "../Icon/";
import { Cell } from "./Cell";
import TableContext from "./TableContext";
import { TableRow } from "./types";

interface RowProps {
  row: TableRow;
}

const Row = ({ row }: RowProps) => {
  const { headers, expandableRows, isResponsive } =
    React.useContext(TableContext);
  return headers.map(({ key, label, cellProps }, index, array) => {
    const cell = row[key];
    const isObject = typeof cell === "object" && cell !== null;
    const value = isObject && "value" in cell ? cell.value : cell;
    const props =
      isObject && "value" in cell
        ? Object.entries(cell)
            .filter(([k]) => k !== "value" && k !== "rawValue")
            .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {})
        : {};
    const rl = row?.expand?.length || 0;

    return (
      <React.Fragment key={key}>
        <Cell
          {...cellProps}
          {...props}
          {...(isResponsive && { "data-label": label })}
        >
          {value ? (value as React.ReactNode) : ""}
        </Cell>
        {index === array.length - 1 &&
          expandableRows?.hasExpandableRows &&
          (row?.expand ? (
            <Cell className="align-right table__cell--shrink table__cell--expand">
              <Button
                type="ghost"
                htmlType="button"
                size="small"
                isSquare
                className="mb-none"
                data-subrow-toggle
                aria-expanded={row.isExpanded ? "true" : "false"}
                aria-controls={row.expand?.map((r) => r.id).join(" ")}
              >
                <span className="visually-hidden">
                  {`Zobraziť ${rl} súvisiac${
                    rl > 4 ? "ich" : rl > 1 ? "e" : "i"
                  } riad${rl > 4 ? "kov" : rl > 1 ? "ky" : "ok"}`}
                </span>
                <Icon name="chevron-down" size="large" />
              </Button>
            </Cell>
          ) : (
            <Cell className="align-right table__cell--shrink">
              <span className="sr-only">
                {expandableRows?.expandableRowsCaptions?.emptyRow}
              </span>
            </Cell>
          ))}
      </React.Fragment>
    );
  });
};

Row.displayName = "TableRow";

export { Row };
