import React, { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import {
  Card, Descriptions, Tag, Spin, Empty, Row, Col, Statistic, Table, Button, Divider, Typography, Badge
} from 'antd'
import {
  ArrowLeftOutlined, ShopOutlined, FileTextOutlined, DollarOutlined, UserOutlined, PhoneOutlined
} from '@ant-design/icons'

const { Title, Text } = Typography

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

interface Supplier {
  id: number
  code: string
  name: string
  supply_category: string
  country: string
  contacts: Contact[]
  remark: string
  total_purchase_amount: number
  total_paid: number
  total_payable: number
  created_at: string
}

interface Project {
  id: number
  project_code: string
  name: string
  contract_amount: number
  status: string
  customer_id: number
  supplier_id: number
}

const SupplierDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [supplier, setSupplier] = useState<Supplier | null>(null)
  const [projects, setProjects] = useState<Project[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchSupplierDetail()
    fetchRelatedProjects()
  }, [id])

  const fetchSupplierDetail = async () => {
    try {
      const res = await fetch(`/api/suppliers/${id}`)
      const data = await res.json()
      if (data.success) setSupplier(data.data)
    } catch (error) {
      console.error('获取供应商详情失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const fetchRelatedProjects = async () => {
    try {
      // 获取所有项目，筛选关联到此供应商的
      const res = await fetch('/api/projects')
      const data = await res.json()
      if (data.success) {
        // 供应商暂无supplier_id关联，先显示空
        // 后续可以在项目中添加供应商关联字段
        const supplierProjects = (data.data || []).filter((p: Project) => p.supplier_id === parseInt(id))
        setProjects(supplierProjects)
      }
    } catch (error) {
      console.error('获取项目失败:', error)
    }
  }

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

  const totalContract = projects.reduce((sum, p) => sum + (parseFloat(p.contract_amount) || 0), 0)
  // 供应商暂无已付/应付数据，暂时显示0
  const totalPaid = 0
  const totalPayable = 0

  const projectColumns = [
    { title: '项目编号', dataIndex: 'project_code', key: 'project_code', width: 120 },
    { title: '项目名称', dataIndex: 'name', key: 'name', render: (v: string) => <Text strong>{v}</Text> },
    { title: '合同金额', dataIndex: 'contract_amount', key: 'contract_amount', align: 'right' as const, render: (v: string) => `¥${(parseFloat(v) || 0).toLocaleString()}` },
    { title: '状态', dataIndex: 'status', key: 'status', align: 'center' as const, render: (v: string) => <Badge status={v === 'completed' ? 'success' : 'processing'} text={v === 'completed' ? '已完成' : v === 'planning' ? '规划中' : v === 'in_progress' ? '进行中' : v} /> }
  ]

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

      <Title level={4} style={{ marginBottom: 24 }}>
        <ShopOutlined style={{ marginRight: 8, color: '#1890ff' }} />
        {supplier.name}
      </Title>

      {/* ========== 卡片1：基本信息 ========== */}
      <Card title={<><UserOutlined /> 基本信息</>} style={{ marginBottom: 24, borderRadius: 8 }} headStyle={{ background: '#f5f5f5', fontWeight: 600 }}>
        <Descriptions bordered column={{ xs: 1, sm: 2, md: 3 }} size="small">
          <Descriptions.Item label="编号">{supplier.code}</Descriptions.Item>
          <Descriptions.Item label="供应类别">{supplier.supply_category || '-'}</Descriptions.Item>
          <Descriptions.Item label="国家"><Tag color="blue">{supplier.country || '-'}</Tag></Descriptions.Item>
        </Descriptions>
        
        {supplier.remark && (
          <>
            <Divider style={{ margin: '16px 0' }} />
            <div><Text type="secondary">备注：</Text><div style={{ marginTop: 8, padding: 12, background: '#fafafa', borderRadius: 4 }}>{supplier.remark}</div></div>
          </>
        )}
        
        <Divider style={{ margin: '16px 0' }} />
        <div style={{ marginBottom: 8 }}><Text type="secondary"><PhoneOutlined style={{ marginRight: 4 }} />联系人</Text></div>
        <Row gutter={[16, 16]}>
          {(supplier.contacts || []).map((contact, i) => (
            <Col key={i} xs={24} sm={12} lg={8}>
              <Card size="small" style={{ borderLeft: contact.is_primary ? '3px solid #1890ff' : '3px solid #d9d9d9', background: contact.is_primary ? '#f0f5ff' : '#fff' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                  <Text strong>{contact.name || '未命名'}</Text>
                  {contact.is_primary && <Tag color="blue" size="small">主联系人</Tag>}
                </div>
                <div style={{ color: '#666', fontSize: 13 }}>
                  {contact.position && <div>职位：{contact.position}</div>}
                  {contact.phone && <div>电话：{contact.phone}</div>}
                </div>
              </Card>
            </Col>
          ))}
        </Row>
        {(supplier.contacts || []).length === 0 && <Empty description="暂无联系人" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
      </Card>

      {/* ========== 卡片2：关联项目 ========== */}
      <Card title={<><FileTextOutlined /> 关联项目</>} style={{ marginBottom: 24, borderRadius: 8 }} headStyle={{ background: '#f5f5f5', fontWeight: 600 }}>
        {projects.length > 0 ? (
          <Table columns={projectColumns} dataSource={projects} rowKey="id" size="small" pagination={false} bordered />
        ) : (
          <Empty description="暂无关联项目（在项目管理中添加供应商关联后会自动显示）" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
      </Card>

      {/* ========== 卡片3：财务信息 ========== */}
      <Card title={<><DollarOutlined /> 财务信息</>} style={{ borderRadius: 8 }} headStyle={{ background: '#f5f5f5', fontWeight: 600 }}>
        <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={totalContract} 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={totalPaid} 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={totalPayable} 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={totalPayable} prefix="¥" valueStyle={{ color: '#faad14', fontSize: 20 }} />
            </Card>
          </Col>
        </Row>
        <Divider style={{ margin: '16px 0' }} />
        <div style={{ marginBottom: 16 }}><Text type="secondary">项目明细</Text></div>
        {projects.length > 0 ? (
          <Table columns={projectColumns} dataSource={projects} rowKey="id" size="small" pagination={false} bordered />
        ) : (
          <Empty description="暂无财务数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
      </Card>
    </div>
  )
}

export default SupplierDetail
