import { useState } from 'react'
import type { OrderWithPayment } from '@features/payment'
import { formatDate, formatRub, truncateHash } from '../model/format'
import { StatusBadge } from './StatusBadge'
import { CopyButton } from './CopyButton'
import styles from './OrderAccordion.module.css'

interface Props {
  item: OrderWithPayment
}

export function OrderAccordion({ item }: Props) {
  const [isOpen, setIsOpen] = useState(false)
  const { order, payment } = item

  return (
    <div className={styles.item}>
      <button
        className={styles.summary}
        onClick={() => setIsOpen(v => !v)}
        type="button"
        aria-expanded={isOpen}
      >
        <div className={styles.summaryLeft}>
          <span className={styles.summaryDate}>{formatDate(order.created_at)}</span>
          {payment && <StatusBadge status={payment.status} />}
        </div>
        <div className={styles.summaryRight}>
          <span className={styles.amount}>{order.usdt_amount} USDT</span>
          <span className={styles.totalAmount}>{formatRub(order.total_price)} ₽</span>
          <svg
            className={`${styles.chevron} ${isOpen ? styles.chevronOpen : ''}`}
            width="18"
            height="18"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <polyline points="6 9 12 15 18 9" />
          </svg>
        </div>
      </button>

      <div className={`${styles.bodyOuter} ${isOpen ? styles.bodyOuterOpen : ''}`}>
        <div className={styles.bodyInner}>
          <div className={styles.body}>
            <div className={styles.col}>
              <p className={styles.colTitle}>Заказ</p>
              <InfoRow label="Сумма USDT" value={`${order.usdt_amount} USDT`} />
              <InfoRow label="Курс обмена" value={`1 USDT = ${order.usdt_exchange_rate} ₽`} />
              <InfoRow label="Сервисный сбор" value={`${order.service_fee} USDT`} />
              <InfoRow label="Комиссия за газ" value={`${order.gas_fee} USDT`} />
              <InfoRow
                label="Итого к оплате"
                value={`${formatRub(order.total_price)} ₽`}
                emphasised
              />
            </div>

            <div className={styles.col}>
              <p className={styles.colTitle}>Платёж</p>
              {payment ? (
                <>
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>Статус</span>
                    <StatusBadge status={payment.status} />
                  </div>
                  <InfoRow label="Оплачено" value={payment.itpay_paid_amount || '—'} />
                  <InfoRow label="Истекает" value={formatDate(payment.expired_date)} />
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>Хэш транзакции</span>
                    <span className={styles.infoValueRow}>
                      <span className={styles.infoValue} title={payment.web3_transaction_hash || undefined}>
                        {truncateHash(payment.web3_transaction_hash)}
                      </span>
                      {payment.web3_transaction_hash && (
                        <CopyButton value={payment.web3_transaction_hash} />
                      )}
                    </span>
                  </div>
                  <div className={styles.infoRow}>
                    <span className={styles.infoLabel}>Чек</span>
                    {payment.receipt_cloudekassir_link ? (
                      <a
                        href={payment.receipt_cloudekassir_link}
                        target="_blank"
                        rel="noopener noreferrer"
                        className={styles.infoLink}
                      >
                        Открыть →
                      </a>
                    ) : (
                      <span className={styles.infoValue}>—</span>
                    )}
                  </div>
                </>
              ) : (
                <div className={styles.infoRow}>
                  <span className={styles.infoValue}>—</span>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

function InfoRow({ label, value, emphasised }: { label: string; value: string; emphasised?: boolean }) {
  return (
    <div className={`${styles.infoRow} ${emphasised ? styles.infoRowTotal : ''}`}>
      <span className={styles.infoLabel}>{label}</span>
      <span className={styles.infoValue}>{value}</span>
    </div>
  )
}
