import React, { useEffect, useState } from 'react';
import { Card, Table, Button, message, Popconfirm, Tag, Space } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useResources } from '@/hooks/resource/useResource';
import { useNavigate } from 'react-router-dom';

const CustomerPage = () => {
  const navigate = useNavigate();
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });
  const [sorter, setSorter] = useState({ field: 'created_at', order: 'descend' });

  const {
    resources: customers,
    loading,
    total,
    fetchResources: fetchCustomers,
    deleteResource: deleteCustomer
  } = useResources(pagination, sorter, 'customer');

  useEffect(() => {
    fetchCustomers();
  }, []);

  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
    setSorter(sorter);
    fetchCustomers({
      current: pagination.current,
      pageSize: pagination.pageSize,
      field: sorter.field,
      order: sorter.order,
    });
  };

  const handleDelete = async (id) => {
    try {
      await deleteCustomer(id);
      message.success('删除成功');
      fetchCustomers();
    } catch (error) {
      message.error('删除失败：' + error.message);
    }
  };

  const columns = [
    {
      title: '客户名称',
      dataIndex: ['attributes', 'name'],
      key: 'name',
      ellipsis: true,
    },
    {
      title: '联系人',
      dataIndex: ['attributes', 'contact'],
      key: 'contact',
    },
    {
      title: '电话',
      dataIndex: ['attributes', 'phone'],
      key: 'phone',
    },
    {
      title: '客户等级',
      dataIndex: ['attributes', 'level'],
      key: 'level',
      render: (level) => {
        const colors = {
          vip: 'gold',
          regular: 'blue',
          potential: 'green'
        };
        const labels = {
          vip: 'VIP客户',
          regular: '普通客户',
          potential: '潜在客户'
        };
        return <Tag color={colors[level]}>{labels[level]}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: ['attributes', 'status'],
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建日期',
      dataIndex: 'created_at',
      key: 'created_at',
      sorter: true,
      render: (text) => (
        <span>{new Date(text).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })}</span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      render: (_, record) => (
        <Space size={0}>
          <Button
            size='small'
            type="link"
            icon={<EditOutlined />}
            onClick={() => navigate(`/company/customerInfo/${record.id}?edit=true`)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个客户吗？"
            description="删除后将无法恢复！"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
            okButtonProps={{ danger: true }}
          >
            <Button size='small' type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Card
      title={
        <Space>
          <span>客户管理</span>
          <Tag color="blue">{total} 个客户</Tag>
        </Space>
      }
      className='h-full w-full overflow-auto'
      extra={
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => navigate('/company/customerInfo')}
        >
          新增客户
        </Button>
      }
    >
      <Table
        columns={columns}
        dataSource={customers}
        rowKey="id"
        scroll={{ x: true }}
        loading={loading}
        onChange={handleTableChange}
        pagination={{
          ...pagination,
          total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />
    </Card>
  );
};

export default CustomerPage;