import { useState } from 'react'
import { useMe } from '@features/auth'
import { Spinner } from '@shared/ui'
import { TransactionsList } from '@widgets/transactions-list'
import { PurchaseRequestsList } from '@widgets/purchase-requests-list'
import styles from './TransactionsPanel.module.css'

type Tab = 'transactions' | 'requests'

// Reusable transactions block: list plus the «Транзакции / Заявки» tabs that
// only legal-entity accounts see. Used as the «Транзакции» item of the profile
// dashboard.
export function TransactionsPanel() {
  const { data, isLoading } = useMe()
  const [tab, setTab] = useState<Tab>('transactions')

  if (isLoading) return <Spinner fullscreen label="Загрузка" />

  const isLegal = !!data && data.account_type !== 'individual'
  const activeTab: Tab = isLegal ? tab : 'transactions'

  return (
    <div className={styles.panel}>
      {isLegal && (
        <div className={styles.tabs}>
          <button
            type="button"
            className={styles.tab}
            data-active={activeTab === 'transactions' || undefined}
            onClick={() => setTab('transactions')}
          >
            Транзакции
          </button>
          <button
            type="button"
            className={styles.tab}
            data-active={activeTab === 'requests' || undefined}
            onClick={() => setTab('requests')}
          >
            Заявки
          </button>
        </div>
      )}

      {activeTab === 'transactions' ? <TransactionsList /> : <PurchaseRequestsList />}
    </div>
  )
}
