import React, { useState, useEffect } from 'react';
import { Button, Spin, Input, message } from 'antd';
import MemberList from '../components/member/MemberList';
import MemberModal from '../components/member/MemberModal';
import { useMemberManagement } from '../hooks/useMemberManagement';
import { Member } from '../types/member';

const { Search } = Input;

const MemberManagement: React.FC = () => {
  const { 
    members, 
    loading,
    addMember, 
    editMember, 
    deleteMember,
    fetchMembers
  } = useMemberManagement();

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingMember, setEditingMember] = useState<Member | null>(null);
  const [searchTerm, setSearchTerm] = useState('');

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

  useEffect(() => {
    console.log('Members:', members);
  }, [members]);

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

  const handleEdit = (member: Member) => {
    console.log('Editing member:', member);
    setEditingMember(member);
    setIsModalVisible(true);
  };

  const handleOk = async (member: Member) => {
    try {
      if (editingMember) {
        await editMember({ ...editingMember, ...member });
      } else {
        await addMember(member);
      }
      setIsModalVisible(false);
      message.success(editingMember ? '会友信息更新成功' : '会友添加成功');
      fetchMembers(); // 重新获取会友列表
    } catch (error) {
      message.error('操作失败，请重试');
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setEditingMember(null);
  };

  const handleSearch = (value: string) => {
    setSearchTerm(value);
  };

  const handleDelete = async (memberId: string) => {
    try {
      await deleteMember(memberId);
      message.success('会友删除成功');
      fetchMembers(); // 重新获取会友列表
    } catch (error) {
      message.error('删除失败，请重试');
    }
  };

  const filteredMembers = members.filter(member => 
    member.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    member.phone.includes(searchTerm) ||
    member.idNumber.includes(searchTerm)
  );

  return (
    <div>
      <h1>会友管理</h1>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <Button type="primary" onClick={showModal}>
          添加会友
        </Button>
        <Search
          placeholder="搜索姓名、手机号或身份证号"
          onSearch={handleSearch}
          style={{ width: 300 }}
        />
      </div>
      {loading ? (
        <Spin size="large" />
      ) : (
        <MemberList 
          members={filteredMembers} 
          onEdit={handleEdit} 
          onDelete={handleDelete} 
        />
      )}
      <MemberModal 
        visible={isModalVisible} 
        onOk={handleOk} 
        onCancel={handleCancel} 
        initialValues={editingMember}
      />
    </div>
  );
}

export default MemberManagement;
