import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Table, Button, message, Modal, Space, Image, Input, Tag } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { deviceApi } from '../api/deviceApi';
import ExcelImportExport from './ExcelImportExport';
import MemberForm from './MemberForm';
import Highlighter from 'react-highlight-words';

const MemberList = () => {
  const [members, setMembers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingMember, setEditingMember] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);

  const fetchMembers = useCallback(async () => {
    setLoading(true);
    try {
      const data = await deviceApi.getAllPersons();
      console.log('获取到的会友列表数据:', data);
      setMembers(data);
      message.success('会友列表获取成功');
    } catch (error) {
      console.error('获取会友列表失败', error);
      message.error(`获取会友列表失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  const getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={searchInput}
          placeholder={`搜索 ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            搜索
          </Button>
          <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
            重置
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
    onFilter: (value, record) =>
      record[dataIndex] ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()) : '',
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (
        text
      ),
  });

  const handleAdd = () => {
    setEditingMember(null);
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingMember(record);
    setIsModalVisible(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '您确定要删除这个会友吗？此操作不可逆。',
      onOk: async () => {
        try {
          await deviceApi.deletePerson(id);
          message.success('会友删除成功');
          fetchMembers();
        } catch (error) {
          console.error('删除会友失败', error);
          message.error(`删除会友失败: ${error.message}`);
        }
      },
    });
  };

  const handleSubmit = async (values) => {
    try {
      if (editingMember) {
        console.log('更新会员信息:', values);
        await deviceApi.updatePerson(editingMember.personId, values);
        message.success('会友信息更新成功');
      } else {
        console.log('添加新会员:', values);
        await deviceApi.addPerson(values);
        message.success('会友添加成功');
      }
      setIsModalVisible(false);
      fetchMembers();
    } catch (error) {
      console.error('操作失败', error);
      message.error(`操作失败: ${error.message}`);
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'personId', key: 'personId' },
    { 
      title: '姓名', 
      dataIndex: 'name', 
      key: 'name',
      ...getColumnSearchProps('name'),
    },
    { title: '性别', dataIndex: 'gender', key: 'gender' },
    { title: '年龄', dataIndex: 'age', key: 'age' },
    { title: '出生日期', dataIndex: 'birthDate', key: 'birthDate' },
    { title: '婚姻状况', dataIndex: 'maritalStatus', key: 'maritalStatus' },
    { 
      title: '是否受洗', 
      dataIndex: 'isBaptized', 
      key: 'isBaptized',
      render: (isBaptized) => isBaptized ? '是' : '否'
    },
    { title: '受洗日期', dataIndex: 'baptismDate', key: 'baptismDate' },
    { 
      title: '联系方式', 
      dataIndex: 'contact', 
      key: 'contact',
      ...getColumnSearchProps('contact'),
    },
    { 
      title: '服侍岗位', 
      dataIndex: 'servicePosition', 
      key: 'servicePosition',
      ...getColumnSearchProps('servicePosition'),
      render: (positions) => (
        <>
          {positions && positions.map((position) => (
            <Tag color="blue" key={position}>
              {position}
            </Tag>
          ))}
        </>
      ),
    },
    { 
      title: '照片', 
      dataIndex: 'photo', 
      key: 'photo',
      render: (photo) => photo ? <Image src={photo} width={50} /> : '无照片'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => handleEdit(record)}>编辑</Button>
          <Button onClick={() => handleDelete(record.personId)} danger>删除</Button>
        </Space>
      ),
    },
  ];

  console.log('当前会友列表数据:', members);

  return (
    <div>
      <h2>会友列表</h2>
      <div style={{ marginBottom: 16 }}>
        <Button onClick={fetchMembers} type="primary" style={{ marginRight: 8 }}>
          刷新列表
        </Button>
        <Button onClick={handleAdd} type="primary" icon={<PlusOutlined />}>
          添加会友
        </Button>
      </div>
      <ExcelImportExport members={members} onImport={fetchMembers} />
      <Table
        columns={columns}
        dataSource={members}
        rowKey="personId"
        loading={loading}
      />
      <Modal
        title={editingMember ? "编辑会友" : "添加会友"}
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={600}
      >
        <MemberForm 
          initialValues={editingMember} 
          onSubmit={handleSubmit}
        />
      </Modal>
    </div>
  );
};

export default MemberList;
