import React, { useState, useMemo } from 'react';
import { 
  Table, Button, Input, Select, Tag, Avatar, Space, Drawer, 
  Modal, Form, DatePicker, message, Card, List, Typography, Divider, Badge,
  Row, Col, theme
} from 'antd';
import { 
  UserOutlined, SearchOutlined, TagsOutlined, TeamOutlined, 
  UserAddOutlined, WechatOutlined, SafetyCertificateOutlined,
  FilterOutlined, ReloadOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import type { ColumnsType } from 'antd/es/table';

const { RangePicker } = DatePicker;
const { Option } = Select;

/**
 * @name 客户信息管理
 * @description 基于企业微信 API 的客户关系管理与详情查看
 * @author AI Assistant
 */

// --- Types & Interfaces ---

interface TagItem {
  id: string;
  name: string;
  type: 'system' | 'enterprise'; // 系统标签 | 企业标签
  color?: string;
}

interface Employee {
  id: string;
  name: string;
  department: string;
  avatar?: string;
}

interface CustomerRelation {
  id: string; // 关系ID
  customerId: string;
  nickname: string;
  avatar: string;
  mobile: string; // 脱敏手机号
  type: 1 | 2; // 1: 微信, 2: 企业微信
  source: string;
  addTime: string;
  employee: Employee; // 当前关系的归属员工
  tags: TagItem[];
  remark: string; // 员工对客户的备注
  description: string; // 员工对客户的描述
}

interface CustomerDetail extends CustomerRelation {
  // 详情中包含该客户关联的所有员工记录
  relatedEmployees: {
    employee: Employee;
    addTime: string;
    source: string;
    remark: string; // 员工对客户的备注
    description: string; // 员工对客户的描述
    tags: TagItem[]; // 该员工给客户打的标签
  }[];
}

// --- Mock Data ---

const MOCK_TAGS: TagItem[] = [
  { id: '1', name: '高意向', type: 'system', color: 'blue' },
  { id: '2', name: '已成交', type: 'system', color: 'green' },
  { id: '3', name: '多次复购', type: 'enterprise', color: 'orange' },
  { id: '4', name: '投诉客户', type: 'enterprise', color: 'red' },
  { id: '5', name: 'VIP', type: 'enterprise', color: 'gold' },
];

const MOCK_EMPLOYEES: Employee[] = [
  { id: 'e1', name: '张三', department: '销售一部' },
  { id: 'e2', name: '李四', department: '销售二部' },
  { id: 'e3', name: '王五', department: '客服部' },
];

const generateMockData = (count: number): CustomerRelation[] => {
  const data: CustomerRelation[] = [];
  for (let i = 0; i < count; i++) {
    const isCorp = Math.random() > 0.7;
    const emp = MOCK_EMPLOYEES[Math.floor(Math.random() * MOCK_EMPLOYEES.length)];
    data.push({
      id: `rel_${i}`,
      customerId: `cust_${i}`,
      nickname: `客户User_${i + 1}`,
      avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${i}`,
      mobile: `138****${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
      type: isCorp ? 2 : 1,
      source: ['扫码添加', '搜索手机号', '名片分享', '群聊添加'][Math.floor(Math.random() * 4)],
      addTime: dayjs().subtract(Math.floor(Math.random() * 30), 'day').format('YYYY-MM-DD HH:mm:ss'),
      employee: emp,
      tags: MOCK_TAGS.filter(() => Math.random() > 0.7),
      remark: Math.random() > 0.5 ? `备注_${i}` : '',
      description: Math.random() > 0.5 ? `这是一段关于客户的描述信息...` : '',
    });
  }
  return data;
};

const MOCK_DATA = generateMockData(50);

// --- Components ---

export default function CustomerManagementPage() {
  const { token } = theme.useToken();
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState<CustomerRelation[]>(MOCK_DATA);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  
  // Drawer State
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentCustomer, setCurrentCustomer] = useState<CustomerDetail | null>(null);

  // Tag Modal State
  const [tagModalVisible, setTagModalVisible] = useState(false);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [taggingTarget, setTaggingTarget] = useState<'single' | 'batch'>('single');

  // Filter Handler
  const handleSearch = (values: any) => {
    const { mobile, staffName, tags, dateRange } = values;
    let filtered = [...MOCK_DATA];

    if (mobile) {
      filtered = filtered.filter(item => item.mobile.includes(mobile) || item.nickname.includes(mobile));
    }
    if (staffName) {
      filtered = filtered.filter(item => item.employee.name.includes(staffName));
    }
    if (tags && tags.length > 0) {
      filtered = filtered.filter(item => item.tags.some(t => tags.includes(t.id)));
    }
    if (dateRange) {
      const [start, end] = dateRange;
      filtered = filtered.filter(item => {
        const time = dayjs(item.addTime);
        return time.isAfter(start) && time.isBefore(end);
      });
    }

    setDataSource(filtered);
    message.success(`查询到 ${filtered.length} 条记录`);
  };

  const handleReset = () => {
    form.resetFields();
    setDataSource(MOCK_DATA);
  };

  // Tagging Handler
  const openTagModal = (target: 'single' | 'batch', record?: CustomerRelation) => {
    setTaggingTarget(target);
    if (target === 'single' && record) {
      setSelectedRowKeys([record.id]);
      setSelectedTags(record.tags.map(t => t.id));
    } else {
      if (selectedRowKeys.length === 0) {
        message.warning('请先勾选需要打标的客户');
        return;
      }
      setSelectedTags([]); // 批量打标时默认不回显，或者回显公共标签（此处简化为清空）
    }
    setTagModalVisible(true);
  };

  const handleTagSubmit = () => {
    const newTags = MOCK_TAGS.filter(t => selectedTags.includes(t.id));
    const updatedData = dataSource.map(item => {
      if (selectedRowKeys.includes(item.id)) {
        return { ...item, tags: newTags };
      }
      return item;
    });
    
    setDataSource(updatedData);
    setTagModalVisible(false);
    message.success(`成功为 ${selectedRowKeys.length} 位客户更新标签`);
    setSelectedRowKeys([]); // Clear selection after batch operation
  };

  // Details Handler
  const showDetails = (record: CustomerRelation) => {
    // Mock fetching details and related employees
    // Create some multi-employee relationship samples for demo
    const isMultiRelationSample = record.id.endsWith('0') || record.id.endsWith('5'); // Every 5th record has multiple relations
    
    const mockRelatedEmployees = [
      { 
        employee: record.employee, 
        addTime: record.addTime, 
        source: record.source,
        remark: record.remark,
        description: record.description,
        tags: record.tags
      },
    ];
    
    if (isMultiRelationSample) {
        // Add 2-4 extra relations
        const extraCount = Math.floor(Math.random() * 3) + 2;
        for(let i=0; i<extraCount; i++) {
            const randomEmp = MOCK_EMPLOYEES.find(e => e.id !== record.employee.id) || MOCK_EMPLOYEES[1];
            mockRelatedEmployees.push({
                employee: randomEmp,
                addTime: dayjs().subtract(Math.floor(Math.random() * 100), 'day').format('YYYY-MM-DD HH:mm:ss'),
                source: ['名片分享', '群聊添加', '搜索手机号'][Math.floor(Math.random() * 3)],
                remark: Math.random() > 0.5 ? `差异化备注_${i}` : '',
                description: Math.random() > 0.5 ? `这是另一位员工记录的描述...` : '',
                tags: MOCK_TAGS.filter(() => Math.random() > 0.6)
            });
        }
    } else {
        // Randomly add another employee relation for some others
        if (Math.random() > 0.7) {
            mockRelatedEmployees.push({
                employee: MOCK_EMPLOYEES.find(e => e.id !== record.employee.id) || MOCK_EMPLOYEES[0],
                addTime: dayjs().subtract(2, 'day').format('YYYY-MM-DD HH:mm:ss'),
                source: '群聊添加',
                remark: '意向客户',
                description: '咨询过产品价格',
                tags: [MOCK_TAGS[0]]
            });
        }
    }

    setCurrentCustomer({
      ...record,
      relatedEmployees: mockRelatedEmployees
    });
    setDrawerVisible(true);
  };

  // Table Columns
  const columns: ColumnsType<CustomerRelation> = [
    {
      title: '客户信息',
      dataIndex: 'nickname',
      key: 'nickname',
      render: (_, record) => (
        <Space>
          <Avatar src={record.avatar} icon={<UserOutlined />} />
          <div className="flex flex-col">
            <span className="font-medium">{record.nickname}</span>
            <span className="text-xs text-gray-400">
              {record.type === 2 ? <span className="text-orange-500">@企业微信</span> : <span className="text-green-500">@微信</span>}
            </span>
          </div>
        </Space>
      ),
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
      render: (text) => <span className="font-mono text-gray-600">{text}</span>,
    },
    {
      title: '归属员工',
      dataIndex: ['employee', 'name'],
      key: 'employee',
      render: (_, record) => (
        <div className="flex flex-col">
          <span>{record.employee.name}</span>
          <span className="text-xs text-gray-400">{record.employee.department}</span>
        </div>
      ),
    },
    {
      title: '客户标签',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <div className="flex flex-wrap gap-1 max-w-[200px]">
          {tags.map(tag => (
            <Tag color={tag.color} key={tag.id} className="mr-0 mb-1">
              {tag.name}
            </Tag>
          ))}
        </div>
      ),
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
    },
    {
      title: '添加时间',
      dataIndex: 'addTime',
      key: 'addTime',
      sorter: (a, b) => dayjs(a.addTime).unix() - dayjs(b.addTime).unix(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" size="small" onClick={() => showDetails(record)}>详情</Button>
          <Button type="text" size="small" onClick={() => openTagModal('single', record)}>打标</Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24, background: '#f5f7fa', minHeight: '100vh', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* 筛选区域 */}
      <Card bordered={false} bodyStyle={{ padding: '24px 24px 0 24px' }}>
        <Form form={form} onFinish={handleSearch} layout="vertical">
          <Row gutter={24}>
            <Col span={6}>
              <Form.Item name="mobile" label="搜索客户">
                <Input placeholder="请输入手机号/昵称" allowClear prefix={<SearchOutlined style={{ color: token.colorTextPlaceholder }} />} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="staffName" label="归属员工">
                <Input placeholder="请输入员工姓名" allowClear prefix={<TeamOutlined style={{ color: token.colorTextPlaceholder }} />} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="tags" label="客户标签">
                <Select mode="multiple" placeholder="请选择标签" allowClear maxTagCount="responsive" style={{ width: '100%' }}>
                  {MOCK_TAGS.map(tag => (
                    <Option key={tag.id} value={tag.id}>
                      <Badge color={tag.color} text={tag.name} />
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="dateRange" label="添加时间">
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row justify="end" style={{ marginBottom: 24 }}>
            <Space>
              <Button onClick={handleReset} icon={<ReloadOutlined />}>重置</Button>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
            </Space>
          </Row>
        </Form>
      </Card>

      {/* 数据列表区域 */}
      <Card bordered={false} bodyStyle={{ padding: 0 }}>
        <div style={{ padding: '16px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: `1px solid ${token.colorSplit}` }}>
          <Typography.Title level={5} style={{ margin: 0 }}>客户关系列表</Typography.Title>
          <Space>
            <Button 
              icon={<TagsOutlined />} 
              disabled={selectedRowKeys.length === 0}
              onClick={() => openTagModal('batch')}
            >
              批量打标
            </Button>
          </Space>
        </div>
        
        <Table
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
          }}
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          pagination={{ 
            total: dataSource.length,
            showSizeChanger: true,
            showQuickJumper: true,
            defaultPageSize: 10,
            showTotal: (total) => `共 ${total} 条记录`
          }}
          style={{ padding: '0 24px 24px' }}
        />
      </Card>

      {/* 客户详情抽屉 */}
      <Drawer
        title="客户详情"
        placement="right"
        width={640}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
      >
        {currentCustomer && (
          <div className="flex flex-col gap-6">
            {/* 基础信息卡片 */}
            <div className="flex items-start gap-4 p-4 bg-blue-50 rounded-lg border border-blue-100">
              <Avatar size={64} src={currentCustomer.avatar} icon={<UserOutlined />} />
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-2">
                  <h3 className="text-xl font-bold m-0">{currentCustomer.nickname}</h3>
                  {currentCustomer.type === 2 ? 
                    <Tag icon={<WechatOutlined />} color="orange">企业微信</Tag> : 
                    <Tag icon={<WechatOutlined />} color="green">微信客户</Tag>
                  }
                </div>
                <div className="grid grid-cols-2 gap-y-2 text-sm text-gray-600">
                  <div>手机号：<span className="font-mono">{currentCustomer.mobile}</span></div>
                  <div>添加来源：{currentCustomer.source}</div>
                  <div className="col-span-2 flex items-start gap-2">
                    <span className="whitespace-nowrap">当前标签：</span>
                    <div className="flex flex-wrap gap-1">
                      {currentCustomer.tags.map(tag => (
                        <Tag key={tag.id} color={tag.color}>{tag.name}</Tag>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <Divider orientation={"left" as any}>关联员工记录 ({currentCustomer.relatedEmployees.length})</Divider>

            {/* 关联员工列表 */}
            <List
              itemLayout="vertical"
              dataSource={currentCustomer.relatedEmployees}
              renderItem={(item: any) => (
                <List.Item className="bg-white p-4 rounded-lg border border-gray-100 shadow-sm mb-3">
                  <List.Item.Meta
                    avatar={<Avatar icon={<UserOutlined />} style={{ backgroundColor: '#87d068' }} />}
                    title={
                      <div className="flex justify-between items-center">
                        <Space>
                            <span className="font-medium">{item.employee.name}</span>
                            <Tag className="m-0 text-xs">{item.employee.department}</Tag>
                        </Space>
                        <span className="text-gray-400 text-xs">{item.addTime}</span>
                      </div>
                    }
                    description={
                      <div className="flex flex-col gap-2 mt-2">
                        <div className="text-xs text-gray-500">
                          <Space split={<Divider type="vertical" />}>
                            <span>来源: {item.source}</span>
                            <span>备注: {item.remark || '-'}</span>
                          </Space>
                        </div>
                        {item.description && (
                            <div className="text-xs bg-gray-50 p-2 rounded text-gray-600">
                                描述：{item.description}
                            </div>
                        )}
                        {item.tags && item.tags.length > 0 && (
                            <div className="flex flex-wrap gap-1">
                                {item.tags.map((tag: any) => (
                                    <Tag key={tag.id} color={tag.color} style={{ fontSize: 10, lineHeight: '18px' }}>
                                        {tag.name}
                                    </Tag>
                                ))}
                            </div>
                        )}
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
            
            <div className="mt-4 p-4 bg-gray-50 rounded text-xs text-gray-500">
              <SafetyCertificateOutlined className="mr-1" />
              数据安全提示：客户手机号已进行脱敏处理，完整号码查看需申请权限。
            </div>
          </div>
        )}
      </Drawer>

      {/* 打标弹窗 */}
      <Modal
        title={taggingTarget === 'single' ? "客户打标" : `批量打标 (已选 ${selectedRowKeys.length} 人)`}
        open={tagModalVisible}
        onOk={handleTagSubmit}
        onCancel={() => setTagModalVisible(false)}
      >
        <div className="py-4">
          <div className="mb-2 font-medium">选择标签：</div>
          <Select
            mode="multiple"
            style={{ width: '100%' }}
            placeholder="请选择标签"
            value={selectedTags}
            onChange={setSelectedTags}
            options={MOCK_TAGS.map(tag => ({ 
              label: tag.name, 
              value: tag.id,
              key: tag.id 
            }))}
          />
          <div className="mt-4 flex flex-wrap gap-2">
            {MOCK_TAGS.map(tag => (
              <Tag.CheckableTag
                key={tag.id}
                checked={selectedTags.includes(tag.id)}
                onChange={(checked) => {
                  if (checked) {
                    setSelectedTags([...selectedTags, tag.id]);
                  } else {
                    setSelectedTags(selectedTags.filter(t => t !== tag.id));
                  }
                }}
              >
                {tag.name}
              </Tag.CheckableTag>
            ))}
          </div>
        </div>
      </Modal>
    </div>
  );
}
