import { Card, Table, Button, Space, Tag, Input, Select, message, Modal } from 'antd'
import { PlusOutlined, EyeOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import request from '../../utils/request'
import { CUSTOMER_STATUS } from '../../utils/constants'
import dayjs from 'dayjs'

const { Search } = Input
const { Option } = Select

const CustomerList = () => {
  const [data, setData] = useState([])
  const [loading, setLoading] = useState(false)
  const [pagination, setPagination] = useState({ current: 1, pageSize: 20, total: 0 })
  const [filters, setFilters] = useState({ status: '', keyword: '' })
  const navigate = useNavigate()

  useEffect(() => {
    loadData()
  }, [pagination.current, pagination.pageSize, filters])

  const loadData = async () => {
    setLoading(true)
    try {
      const res = await request.get('/customers', {
        params: {
          page: pagination.current,
          limit: pagination.pageSize,
          ...filters
        }
      })
      setData(res.data.customers)
      setPagination(prev => ({ ...prev, total: res.data.pagination.total }))
    } catch (error) {
      console.error('加载数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleSearch = (value) => {
    setFilters(prev => ({ ...prev, keyword: value }))
    setPagination(prev => ({ ...prev, current: 1 }))
  }

  const handleStatusChange = (value) => {
    setFilters(prev => ({ ...prev, status: value }))
    setPagination(prev => ({ ...prev, current: 1 }))
  }

  const handleTableChange = (newPagination) => {
    setPagination(newPagination)
  }

  const columns = [
    {
      title: '客户名称',
      dataIndex: 'customer_name',
      key: 'customer_name',
      width: 200,
      fixed: 'left',
    },
    {
      title: '行业',
      dataIndex: 'industry',
      key: 'industry',
      width: 120,
    },
    {
      title: '地区',
      dataIndex: 'region',
      key: 'region',
      width: 100,
    },
    {
      title: '联系人',
      dataIndex: 'contact_person',
      key: 'contact_person',
      width: 100,
    },
    {
      title: '联系电话',
      dataIndex: 'contact_phone',
      key: 'contact_phone',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={CUSTOMER_STATUS[status]?.color}>
          {CUSTOMER_STATUS[status]?.text}
        </Tag>
      ),
    },
    {
      title: '负责人',
      dataIndex: 'owner_name',
      key: 'owner_name',
      width: 100,
    },
    {
      title: '保护期到期',
      dataIndex: 'protected_end_date',
      key: 'protected_end_date',
      width: 160,
      render: (text, record) => {
        const isExpired = record.is_expired === 1
        return (
          <span style={{ color: isExpired ? '#ff4d4f' : undefined }}>
            {dayjs(text).format('YYYY-MM-DD HH:mm')}
          </span>
        )
      },
    },
    {
      title: '报备时间',
      dataIndex: 'report_time',
      key: 'report_time',
      width: 160,
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 100,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/customers/${record.id}`)}
          >
            查看
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <div>
      <Card>
        <Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
          <Space>
            <Search
              placeholder="搜索客户名称、联系人、电话"
              allowClear
              onSearch={handleSearch}
              style={{ width: 300 }}
            />
            <Select
              placeholder="客户状态"
              allowClear
              style={{ width: 120 }}
              onChange={handleStatusChange}
            >
              <Option value="following">跟进中</Option>
              <Option value="won">已成交</Option>
              <Option value="lost">已丢单</Option>
              <Option value="released">已释放</Option>
            </Select>
          </Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => navigate('/customers/create')}
          >
            报备客户
          </Button>
        </Space>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1400 }}
        />
      </Card>
    </div>
  )
}

export default CustomerList
