import { useState, type ReactElement } from 'react';
import { PanelTopClose, PanelTopOpen } from 'lucide-react';
import { Text } from '@mantine/core';
import type { TrialBalanceTableFieldsFragment } from '../../../gql/graphql.js';
import { BusinessExtendedInfo } from '../../business-ledger/business-extended-info.js';
import { Tooltip } from '../../common/index.js';
import { Button } from '../../ui/button.js';
import { TrialBalanceReportFilters } from './trial-balance-report-filters.js';

export type ExtendedBusiness = Extract<
  TrialBalanceTableFieldsFragment,
  { businessTransactionsSum: unknown }
>['businessTransactionsSum'][number];

interface Props {
  record: ExtendedBusiness;
  sortCodeKey: number;
  filter: TrialBalanceReportFilters;
  isAllOpened: boolean;
}

export const TrialBalanceReportBusiness = ({
  record,
  sortCodeKey,
  filter,
  isAllOpened,
}: Props): ReactElement => {
  const [isExtended, setIsExtended] = useState(isAllOpened);
  const rowTotal = record?.total?.raw ?? 0;
  const rowDebit = record?.debit?.raw ?? 0;
  const rowCredit = record?.credit?.raw ?? 0;
  return (
    <>
      <tr key={record.business.id}>
        <td>{sortCodeKey}</td>
        <td>{record.business.id}</td>
        <td>{record.business.name ?? undefined}</td>
        <td>{rowDebit ? record?.debit?.formatted : undefined}</td>
        <td>{rowCredit ? record?.credit?.formatted : undefined}</td>
        <td>
          {(rowTotal > 0.001 || rowTotal < -0.001) && (
            <Text color={rowTotal > 0 ? 'green' : 'red'}>{record?.total?.formatted}</Text>
          )}
        </td>
        <td>
          <Tooltip content="Detailed records">
            <Button
              variant="outline"
              size="icon"
              className="size-7.5"
              onClick={(): void => setIsExtended(i => !i)}
            >
              {isExtended || isAllOpened ? (
                <PanelTopClose className="size-5" />
              ) : (
                <PanelTopOpen className="size-5" />
              )}
            </Button>
          </Tooltip>
        </td>
      </tr>
      {(isExtended || isAllOpened) && (
        <tr>
          <td colSpan={7}>
            <BusinessExtendedInfo businessID={record.business?.id} filter={filter} />
          </td>
        </tr>
      )}
    </>
  );
};
