import { usePurchaseRequests } from '@features/admin'
import styles from './OrganizationPurchaseRequests.module.css'

interface Props {
  orgId: string
}

function formatAmount(value: string | null, suffix: string): string {
  if (!value) return '—'
  return `${value} ${suffix}`
}

function formatDate(value: string | null): string {
  if (!value) return '—'
  const d = new Date(value)
  if (Number.isNaN(d.getTime())) return '—'
  return d.toLocaleString('ru-RU')
}

export function OrganizationPurchaseRequests({ orgId }: Props) {
  const { data, isLoading, isError } = usePurchaseRequests(orgId)

  if (isLoading) {
    return <div className={styles.state}>Загрузка...</div>
  }

  if (isError) {
    return <div className={styles.state}>Не удалось загрузить заявки</div>
  }

  if (!data || data.items.length === 0) {
    return <div className={styles.state}>Заявок пока нет</div>
  }

  return (
    <div className={styles.tableWrap}>
      <table className={styles.table}>
        <thead>
          <tr>
            <th>USDT</th>
            <th>Сумма ₽</th>
            <th>Курс</th>
            <th>Статус</th>
            <th>Создана</th>
          </tr>
        </thead>
        <tbody>
          {data.items.map((req) => (
            <tr key={req.id}>
              <td className={styles.mono}>{formatAmount(req.usdt_amount, 'USDT')}</td>
              <td className={styles.mono}>{formatAmount(req.rub_amount, '₽')}</td>
              <td className={styles.mono}>{req.exchange_rate ?? '—'}</td>
              <td>
                <span className={styles.status}>{req.status}</span>
              </td>
              <td>{formatDate(req.created_at)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
