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

const { Title, Text } = Typography

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

interface LedgerSummary {
  item_count: number
  total_contract_amount: number
  total_received_amount: number
  total_receivable_amount: number
}

interface LedgerItem {
  id: number
  type: string
  code: string
  name: string
  contract_amount: number
  received_amount: number
  receivable_amount: number
  status: string
}

interface Customer {
  id: number
  code: string
  name: string
  address: string
  contacts: Contact[]
  remark: string
  total_contract_amount: number
  total_received: number
  total_receivable: number
  ledger?: {
    summary: LedgerSummary
    items: LedgerItem[]
  }
  created_at: string
}

interface Quotation {
  id: number
  version: number
  quotation_date: string
  amount: number
  currency: string
  status: string
  created_at: string
}

interface BudgetProject {
  id: number
  name: string
  customer_id: number
  manager_name: string
  status: string
  quotations: Quotation[]
  created_at: string
}

const CustomerDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [customer, setCustomer] = useState<Customer | null>(null)
  const [budgetProjects, setBudgetProjects] = useState<BudgetProject[]>([])
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState('basic')

  useEffect(() => {
    fetchCustomerDetail()
    fetchRelatedBudgetProjects()
  }, [id])

  const fetchCustomerDetail = async () => {
    try {
      const res = await fetch(`/api/customers/${id}`)
      const data = await res.json()
      if (data.success) setCustomer(data.data)
    } catch (error) {
      console.error('获取客户详情失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const fetchRelatedBudgetProjects = async () => {
    try {
      const res = await apiClient.get('/api/budget-projects', { params: { customer_id: id } })
      if (res.data.success) setBudgetProjects(res.data.data || [])
    } catch (error) {
      console.error('获取预算项目失败:', error)
    }
  }

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

  const budgetProjectColumns = [
    { title: '项目名称', dataIndex: 'name', key: 'name', render: (v: string, record: BudgetProject) => (
      <Text strong onClick={() => navigate(`/budget-projects/${record.id}`)} style={{ cursor: 'pointer', color: '#1890ff' }}>{v}</Text>
    ) },
    { title: '业务经理', dataIndex: 'manager_name', key: 'manager_name' },
    { title: '状态', dataIndex: 'status', key: 'status', align: 'center' as const, render: (v: string) => {
      const map: Record<string, { status: 'success' | 'processing' | 'error' | 'default'; text: string }> = {
        negotiating: { status: 'processing', text: '商谈中' },
        signed: { status: 'success', text: '已签约' },
        unsigned: { status: 'error', text: '未签约' }
      }
      const c = map[v] || { status: 'default', text: v }
      return <Badge status={c.status} text={c.text} />
    } },
    { title: '报价版本数', dataIndex: 'quotations', key: 'quotations', align: 'center' as const, render: (q: Quotation[]) => (q || []).length },
    { title: '创建时间', dataIndex: 'created_at', key: 'created_at', render: (v: string) => v?.split('T')[0] || '-' }
  ]

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

      <Title level={4} style={{ marginBottom: 24 }}>
        <HomeOutlined style={{ marginRight: 8, color: '#52c41a' }} />
        {customer.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 }} size="small">
              <Descriptions.Item label="编号">{customer.code}</Descriptions.Item>
              <Descriptions.Item label="地址">{customer.address || '-'}</Descriptions.Item>
            </Descriptions>
            {customer.remark && (
              <div style={{ marginTop: 16 }}>
                <Text type="secondary">备注：</Text>
                <div style={{ padding: 12, background: '#f6ffed', borderRadius: 4, border: '1px solid #b7eb8f', marginTop: 8 }}>{customer.remark}</div>
              </div>
            )}
          </Tabs.TabPane>

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

          {/* TAB3: 业务台账 */}
          <Tabs.TabPane tab={<span><DollarOutlined /> 业务台账</span>} key="ledger">
            <BusinessLedgerTab
              partnerType="customer"
              summary={customer.ledger?.summary || { item_count: 0, total_contract_amount: 0, total_received_amount: 0, total_receivable_amount: 0 }}
              items={customer.ledger?.items || []}
            />
          </Tabs.TabPane>

          {/* TAB4: 关联预算 */}
          <Tabs.TabPane tab={<span><FileTextOutlined /> 关联预算</span>} key="budget">
            {budgetProjects.length > 0 ? (
              <Table columns={budgetProjectColumns} dataSource={budgetProjects} rowKey="id" size="small" pagination={{ pageSize: 10 }} bordered />
            ) : (
              <Empty description="暂无关联预算项目" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </Tabs.TabPane>
        </Tabs>
      </Card>
    </div>
  )
}

export default CustomerDetail
