import React, { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import {
  Card, Descriptions, Tag, Spin, Empty, Row, Col, Tabs, Button, Typography
} from 'antd'
import {
  ArrowLeftOutlined, SolutionOutlined, UserOutlined, PhoneOutlined,
  FileTextOutlined, DollarOutlined, BankOutlined
} from '@ant-design/icons'
import BusinessLedgerTab from '../components/BusinessLedgerTab'

const { Title, Text } = Typography

interface Contact {
  name: string
  position: string
  phone: string
  is_primary?: boolean
}

interface PaymentInfo {
  id: number
  account_name: string
  bank_account: string
  bank_name: string
  qr_code?: string
  is_primary: boolean
}

interface LedgerSummary {
  item_count: number
  total_contract_amount: number
  total_paid_amount: number
  total_unpaid_amount: number
}

interface LedgerItem {
  id: number
  type: string
  code: string
  name: string
  contract_amount: number
  paid_amount: number
  unpaid_amount: number
  status: string
}

interface Subcontractor {
  id: number
  code: string
  name: string
  scope: string
  features: string
  country: string
  contacts: Contact[]
  payment_infos: PaymentInfo[]
  remark: string
  total_contract_amount: number
  total_paid: number
  total_payable: number
  ledger?: {
    summary: LedgerSummary
    items: LedgerItem[]
  }
  created_at: string
}

const SubcontractorDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [subcontractor, setSubcontractor] = useState<Subcontractor | null>(null)
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState('basic')

  useEffect(() => {
    fetchSubcontractorDetail()
  }, [id])

  const fetchSubcontractorDetail = async () => {
    try {
      const res = await fetch(`/api/subcontractors/${id}`)
      const data = await res.json()
      if (data.success) setSubcontractor(data.data)
    } catch (error) {
      console.error('获取分包商详情失败:', error)
    } finally {
      setLoading(false)
    }
  }

  if (loading) return <Spin style={{ display: 'flex', justifyContent: 'center', padding: 50 }} />
  if (!subcontractor) return <Empty description="分包商不存在" style={{ marginTop: 100 }} />

  return (
    <div style={{ padding: '16px', maxWidth: 1200, margin: '0 auto' }}>
      <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/subcontractors')} style={{ marginBottom: 16 }} type="text">
        返回列表
      </Button>

      <Title level={4} style={{ marginBottom: 24 }}>
        <SolutionOutlined style={{ marginRight: 8, color: '#722ed1' }} />
        {subcontractor.name}
      </Title>

      <Card style={{ borderRadius: 8 }}>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          {/* TAB1: 基本信息 */}
          <Tabs.TabPane tab={<span><UserOutlined /> 基本信息</span>} key="basic">
            <Descriptions bordered column={{ xs: 1, sm: 2, md: 3 }} size="small">
              <Descriptions.Item label="编号">{subcontractor.code}</Descriptions.Item>
              <Descriptions.Item label="承包范围">{subcontractor.scope || '-'}</Descriptions.Item>
              <Descriptions.Item label="国家"><Tag color="purple">{subcontractor.country || '-'}</Tag></Descriptions.Item>
            </Descriptions>
            {subcontractor.features && (
              <div style={{ marginTop: 16 }}>
                <Text type="secondary">特点：</Text>
                <div style={{ padding: 12, background: '#f9f0ff', borderRadius: 4, border: '1px solid #d3adf7', marginTop: 8 }}>{subcontractor.features}</div>
              </div>
            )}
            {subcontractor.remark && (
              <div style={{ marginTop: 16 }}>
                <Text type="secondary">备注：</Text>
                <div style={{ padding: 12, background: '#fafafa', borderRadius: 4, marginTop: 8 }}>{subcontractor.remark}</div>
              </div>
            )}
          </Tabs.TabPane>

          {/* TAB2: 联系人 */}
          <Tabs.TabPane tab={<span><PhoneOutlined /> 联系人</span>} key="contacts">
            <Row gutter={[16, 16]}>
              {(subcontractor.contacts || []).map((contact, i) => (
                <Col key={i} xs={24} sm={12} lg={8}>
                  <Card size="small" style={{ borderLeft: contact.is_primary ? '3px solid #722ed1' : '3px solid #d9d9d9', background: contact.is_primary ? '#f9f0ff' : '#fff' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                      <Text strong>{contact.name || '未命名'}</Text>
                      {contact.is_primary && <Tag color="purple">主联系人</Tag>}
                    </div>
                    <div style={{ color: '#666', fontSize: 13 }}>
                      {contact.position && <div>职位：{contact.position}</div>}
                      {contact.phone && <div>电话：{contact.phone}</div>}
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
            {(subcontractor.contacts || []).length === 0 && <Empty description="暂无联系人" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
          </Tabs.TabPane>

          {/* TAB3: 收款信息 */}
          <Tabs.TabPane tab={<span><BankOutlined /> 收款信息</span>} key="payment">
            <Row gutter={[16, 16]}>
              {(subcontractor.payment_infos || []).map((payment, i) => (
                <Col key={i} xs={24} sm={12} lg={8}>
                  <Card size="small" style={{ borderLeft: payment.is_primary ? '3px solid #722ed1' : '3px solid #d9d9d9', background: payment.is_primary ? '#f9f0ff' : '#fff' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                      <Text strong>{payment.account_name}</Text>
                      {payment.is_primary && <Tag color="purple">默认账户</Tag>}
                    </div>
                    <div style={{ color: '#666', fontSize: 13 }}>
                      <div>银行：{payment.bank_name}</div>
                      <div>账号：{payment.bank_account}</div>
                      {payment.qr_code && (
                        <div style={{ marginTop: 8 }}>
                          <Text type="secondary">二维码：</Text>
                          <div style={{ marginTop: 4 }}>
                            <img src={payment.qr_code} alt="二维码" style={{ maxWidth: '100%', maxHeight: 120, border: '1px solid #d9d9d9', borderRadius: 4 }} />
                          </div>
                        </div>
                      )}
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
            {(subcontractor.payment_infos || []).length === 0 && <Empty description="暂无收款信息" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
          </Tabs.TabPane>

          {/* TAB4: 业务台账 */}
          <Tabs.TabPane tab={<span><DollarOutlined /> 业务台账</span>} key="ledger">
            <BusinessLedgerTab
              partnerType="subcontractor"
              summary={subcontractor.ledger?.summary || { item_count: 0, total_contract_amount: 0, total_paid_amount: 0, total_unpaid_amount: 0 }}
              items={subcontractor.ledger?.items || []}
            />
          </Tabs.TabPane>
        </Tabs>
      </Card>
    </div>
  )
}

export default SubcontractorDetail
