import React from 'react'
import { Table, Card, Row, Col, Statistic, Empty, Tag } from 'antd'
import { DollarOutlined } from '@ant-design/icons'

interface LedgerItem {
  id: number
  type: string
  code: string
  name: string
  contract_amount?: number
  order_amount?: number
  paid_amount?: number
  unpaid_amount?: number
  received_amount?: number
  receivable_amount?: number
  primary_freight?: number
  primary_freight_currency?: string
  primary_freight_status?: string
  secondary_freight?: number
  secondary_freight_currency?: string
  secondary_freight_status?: string
  project_name?: string
  status?: string
  date?: string
}

interface LedgerSummary {
  item_count: number
  total_contract_amount?: number
  total_order_amount?: number
  total_paid_amount?: number
  total_unpaid_amount?: number
  total_received_amount?: number
  total_receivable_amount?: number
  total_primary_freight?: number
  total_secondary_freight?: number
  total_freight?: number
  paid_primary_freight?: number
  paid_secondary_freight?: number
  paid_amount?: number
  unpaid_amount?: number
}

interface BusinessLedgerTabProps {
  partnerType: 'subcontractor' | 'customer' | 'supplier' | 'logistics'
  summary: LedgerSummary
  items: LedgerItem[]
  loading?: boolean
}

const formatAmount = (amount: number | undefined, currency?: string) => {
  const symbols: Record<string, string> = { CNY: '¥', USD: '$', LAK: '₭', THB: '฿' }
  const sym = currency ? (symbols[currency] || '¥') : '¥'
  return `${sym}${(amount || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}

const getStatusTag = (status: string | undefined) => {
  if (!status) return '-'
  const map: Record<string, { color: string; text: string }> = {
    completed: { color: 'success', text: '已完成' },
    in_progress: { color: 'processing', text: '进行中' },
    planning: { color: 'default', text: '规划中' },
    pending: { color: 'default', text: '待处理' },
    approved: { color: 'success', text: '已批准' },
    paid: { color: 'green', text: '已支付' },
    requested: { color: 'blue', text: '已申请' },
    active: { color: 'processing', text: '进行中' },
  }
  const info = map[status] || { color: 'default', text: status }
  return <Tag color={info.color}>{info.text}</Tag>
}

const BusinessLedgerTab: React.FC<BusinessLedgerTabProps> = ({ partnerType, summary, items, loading }) => {
  const renderSummaryCards = () => {
    switch (partnerType) {
      case 'subcontractor':
        return (
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#e6f7ff', border: '1px solid #91d5ff' }}>
                <Statistic title="合同总金额" value={summary.total_contract_amount || 0} prefix="¥" valueStyle={{ color: '#1890ff', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                <Statistic title="已付总额" value={summary.total_paid_amount || 0} prefix="¥" valueStyle={{ color: '#52c41a', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#fff2f0', border: '1px solid #ffccc7' }}>
                <Statistic title="未付总额" value={summary.total_unpaid_amount || 0} prefix="¥" valueStyle={{ color: '#ff4d4f', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#fffbe6', border: '1px solid #ffe58f' }}>
                <Statistic title="项目数量" value={summary.item_count || 0} suffix="个" valueStyle={{ color: '#faad14', fontSize: 20 }} />
              </Card>
            </Col>
          </Row>
        )
      case 'customer':
        return (
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#e6f7ff', border: '1px solid #91d5ff' }}>
                <Statistic title="合同总金额" value={summary.total_contract_amount || 0} prefix="¥" valueStyle={{ color: '#1890ff', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                <Statistic title="已收总额" value={summary.total_received_amount || 0} prefix="¥" valueStyle={{ color: '#52c41a', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#fff2f0', border: '1px solid #ffccc7' }}>
                <Statistic title="应收总额" value={summary.total_receivable_amount || 0} prefix="¥" valueStyle={{ color: '#ff4d4f', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#fffbe6', border: '1px solid #ffe58f' }}>
                <Statistic title="项目数量" value={summary.item_count || 0} suffix="个" valueStyle={{ color: '#faad14', fontSize: 20 }} />
              </Card>
            </Col>
          </Row>
        )
      case 'supplier':
        return (
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#e6f7ff', border: '1px solid #91d5ff' }}>
                <Statistic title="采购总额" value={summary.total_order_amount || 0} prefix="¥" valueStyle={{ color: '#1890ff', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                <Statistic title="已付总额" value={summary.total_paid_amount || 0} prefix="¥" valueStyle={{ color: '#52c41a', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#fff2f0', border: '1px solid #ffccc7' }}>
                <Statistic title="未付总额" value={summary.total_unpaid_amount || 0} prefix="¥" valueStyle={{ color: '#ff4d4f', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#fffbe6', border: '1px solid #ffe58f' }}>
                <Statistic title="订单数量" value={summary.item_count || 0} suffix="个" valueStyle={{ color: '#faad14', fontSize: 20 }} />
              </Card>
            </Col>
          </Row>
        )
      case 'logistics':
        return (
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#e6f7ff', border: '1px solid #91d5ff' }}>
                <Statistic title="一次运费总额" value={summary.total_primary_freight || 0} suffix=" CNY" valueStyle={{ color: '#1890ff', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#f6ffed', border: '1px solid #b7eb8f' }}>
                <Statistic title="已付总额" value={summary.paid_amount || 0} prefix="¥" valueStyle={{ color: '#52c41a', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#fff2f0', border: '1px solid #ffccc7' }}>
                <Statistic title="未付总额" value={summary.unpaid_amount || 0} prefix="¥" valueStyle={{ color: '#ff4d4f', fontSize: 20 }} />
              </Card>
            </Col>
            <Col xs={12} lg={6}>
              <Card size="small" style={{ textAlign: 'center', background: '#fffbe6', border: '1px solid #ffe58f' }}>
                <Statistic title="物流单数量" value={summary.item_count || 0} suffix="个" valueStyle={{ color: '#faad14', fontSize: 20 }} />
              </Card>
            </Col>
          </Row>
        )
    }
  }

  const getColumns = () => {
    const baseColumns: any[] = [
      { title: '编号', dataIndex: 'code', key: 'code', width: 120 },
      { title: '名称', dataIndex: 'name', key: 'name', render: (v: string) => <span style={{ fontWeight: 500 }}>{v}</span> },
    ]

    switch (partnerType) {
      case 'subcontractor':
        return [
          ...baseColumns,
          { title: '合同金额', dataIndex: 'contract_amount', key: 'contract_amount', align: 'right' as const, render: (v: number) => formatAmount(v) },
          { title: '状态', dataIndex: 'status', key: 'status', align: 'center' as const, render: getStatusTag },
        ]
      case 'customer':
        return [
          ...baseColumns,
          { title: '合同金额', dataIndex: 'contract_amount', key: 'contract_amount', align: 'right' as const, render: (v: number) => formatAmount(v) },
          { title: '状态', dataIndex: 'status', key: 'status', align: 'center' as const, render: getStatusTag },
        ]
      case 'supplier':
        return [
          ...baseColumns,
          { title: '采购金额', dataIndex: 'order_amount', key: 'order_amount', align: 'right' as const, render: (v: number) => formatAmount(v) },
          { title: '状态', dataIndex: 'status', key: 'status', align: 'center' as const, render: getStatusTag },
        ]
      case 'logistics':
        return [
          ...baseColumns,
          { title: '项目', dataIndex: 'project_name', key: 'project_name', render: (v: string) => v || '-' },
          { title: '一次运费', dataIndex: 'primary_freight', key: 'primary_freight', align: 'right' as const, render: (v: number, r: LedgerItem) => formatAmount(v, r.primary_freight_currency) },
          { title: '一次运费状态', dataIndex: 'primary_freight_status', key: 'primary_freight_status', align: 'center' as const, width: 100, render: getStatusTag },
          { title: '状态', dataIndex: 'status', key: 'status', align: 'center' as const, render: getStatusTag },
        ]
      default:
        return baseColumns
    }
  }

  return (
    <div>
      {renderSummaryCards()}
      {items && items.length > 0 ? (
        <Table
          columns={getColumns()}
          dataSource={items}
          rowKey="id"
          size="small"
          pagination={{ pageSize: 10 }}
          loading={loading}
          bordered
        />
      ) : (
        <Empty description="暂无业务记录" image={Empty.PRESENTED_IMAGE_SIMPLE} />
      )}
    </div>
  )
}

export default BusinessLedgerTab
