import { useState } from 'react'
import type { ClientOperation, Payment, SbpWithdrawalOperation } from '@features/payment'
import { formatDate, formatRub, truncateHash } from '../model/format'
import { StatusBadge } from './StatusBadge'
import { WithdrawalStatusBadge } from './WithdrawalStatusBadge'
import { CopyButton } from './CopyButton'
import styles from './OperationAccordion.module.css'

interface Props {
  op: ClientOperation
}

export function OperationAccordion({ op }: Props) {
  const [isOpen, setIsOpen] = useState(false)

  // type — основной признак, но опираемся и на наличие данных (защита от пустых полей).
  const isWithdrawal = op.type === 'withdrawal' ? !!op.withdrawal : !op.payment && !!op.withdrawal

  if (isWithdrawal && op.withdrawal) {
    return <Accordion isOpen={isOpen} onToggle={() => setIsOpen((v) => !v)} summary={withdrawalSummary(op.withdrawal)}>
      {withdrawalBody(op.withdrawal)}
    </Accordion>
  }

  if (op.payment) {
    return <Accordion isOpen={isOpen} onToggle={() => setIsOpen((v) => !v)} summary={paymentSummary(op.payment)}>
      {paymentBody(op.payment)}
    </Accordion>
  }

  return null
}

// --- Каркас аккордеона (общий для обоих типов операций) ---

interface AccordionProps {
  isOpen: boolean
  onToggle: () => void
  summary: React.ReactNode
  children: React.ReactNode
}

function Accordion({ isOpen, onToggle, summary, children }: AccordionProps) {
  return (
    <div className={styles.item}>
      <button className={styles.summary} onClick={onToggle} type="button" aria-expanded={isOpen}>
        {summary}
        <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>
      </button>

      <div className={`${styles.bodyOuter} ${isOpen ? styles.bodyOuterOpen : ''}`}>
        <div className={styles.bodyInner}>
          <div className={styles.body}>{children}</div>
        </div>
      </div>
    </div>
  )
}

// --- Платёж ---

function paymentSummary(payment: Payment) {
  return (
    <>
      <span className={styles.summaryLeft}>
        <span className={styles.opType}>Платёж</span>
        <span className={styles.summaryDate}>{formatDate(payment.created_at)}</span>
        {payment.status && <StatusBadge status={payment.status} />}
      </span>
      <span className={styles.summaryRight}>
        {payment.itpay_paid_amount && (
          <span className={styles.totalAmount}>{formatRub(payment.itpay_paid_amount)} ₽</span>
        )}
      </span>
    </>
  )
}

function paymentBody(payment: Payment) {
  return (
    <>
      <div className={styles.col}>
        <p className={styles.colTitle}>Платёж</p>
        <div className={styles.infoRow}>
          <span className={styles.infoLabel}>Статус</span>
          {payment.status ? <StatusBadge status={payment.status} /> : <span className={styles.infoValue}>—</span>}
        </div>
        <InfoRow label="Оплачено" value={payment.itpay_paid_amount || '—'} />
        <InfoRow label="Истекает" value={formatDate(payment.expired_date ?? '')} />
      </div>

      <div className={styles.col}>
        <p className={styles.colTitle}>Транзакция</p>
        <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>
    </>
  )
}

// --- Вывод (СБП) ---

function withdrawalSummary(w: SbpWithdrawalOperation) {
  return (
    <>
      <span className={styles.summaryLeft}>
        <span className={styles.opType}>Вывод СБП</span>
        <span className={styles.summaryDate}>{formatDate(w.created_at ?? '')}</span>
        {w.status && <WithdrawalStatusBadge status={w.status} />}
      </span>
      <span className={styles.summaryRight}>
        {w.usdt_amount && <span className={styles.amount}>{w.usdt_amount} USDT</span>}
        {w.rub_amount && <span className={styles.totalAmount}>{formatRub(w.rub_amount)} ₽</span>}
      </span>
    </>
  )
}

function withdrawalBody(w: SbpWithdrawalOperation) {
  return (
    <>
      <div className={styles.col}>
        <p className={styles.colTitle}>Вывод (СБП)</p>
        <div className={styles.infoRow}>
          <span className={styles.infoLabel}>Статус</span>
          {w.status ? <WithdrawalStatusBadge status={w.status} /> : <span className={styles.infoValue}>—</span>}
        </div>
        <InfoRow label="Банк" value={w.bank_name || '—'} />
        <InfoRow label="Телефон" value={w.phone || '—'} />
        <InfoRow label="Создан" value={formatDate(w.payout_created_at ?? w.created_at ?? '')} />
        <InfoRow label="Завершён" value={formatDate(w.payout_completed_at ?? '')} />
        {w.provider_error && <InfoRow label="Ошибка" value={w.provider_error} />}
      </div>

      <div className={styles.col}>
        <p className={styles.colTitle}>Суммы</p>
        <InfoRow label="Сумма USDT" value={w.usdt_amount ? `${w.usdt_amount} USDT` : '—'} />
        <InfoRow label="Курс обмена" value={w.usdt_exchange_rate ? `1 USDT = ${w.usdt_exchange_rate} ₽` : '—'} />
        <InfoRow label="Сервисный сбор" value={w.service_fee_usdt ? `${w.service_fee_usdt} USDT` : '—'} />
        <InfoRow label="Сумма к выводу" value={w.rub_amount ? `${formatRub(w.rub_amount)} ₽` : '—'} emphasised />
      </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>
  )
}
