import React, { useState } from 'react';
import { Modal, Form, Input, Select, message } from 'antd';
import { MembershipTable } from './MembershipTable';

const { Option } = Select;

export const ExpandedMemberships = ({ teamId, memberships: initialMemberships }) => {
  const [memberships, setMemberships] = useState(initialMemberships);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  const handleUpdate = (id, values) => {
    setMemberships(prev => 
      prev.map(item => item.id === id ? { ...item, ...values } : item)
    );
    message.success('成员信息已更新');
  };

  const handleDelete = (id) => {
    setMemberships(prev => prev.filter(item => item.id !== id));
    message.success('成员已删除');
  };

  const handleAdd = () => {
    setIsModalVisible(true);
    form.resetFields();
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      const newMember = {
        id: `${Date.now()}`,
        teamId,
        isCreator: false,
        ...values,
      };
      setMemberships(prev => [...prev, newMember]);
      setIsModalVisible(false);
      message.success('成员已添加');
    } catch (error) {
      console.error('Add failed:', error);
    }
  };

  return (
    <div className="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg">
      <h3 className="text-lg font-medium mb-4">团队成员</h3>
      
      <MembershipTable
        memberships={memberships}
        onUpdate={handleUpdate}
        onDelete={handleDelete}
        onAdd={handleAdd}
      />

      <Modal
        title="添加成员"
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name={['user', 'name']}
            label="姓名"
            rules={[{ required: true, message: '请输入姓名!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name={['user', 'email']}
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱!' },
              { type: 'email', message: '请输入有效的邮箱!' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色!' }]}
          >
            <Select>
              <Option value="ADMIN">Admin</Option>
              <Option value="MEMBER">Member</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};