import React, { useState } from 'react';
import { Table, Button, Space, Popconfirm, Tag, Form } from 'antd';
import { EditOutlined, DeleteOutlined, SaveOutlined, CloseOutlined, PlusOutlined } from '@ant-design/icons';
import { EditableMembershipCell } from './EditableMembershipCell';
import { roleColors } from '../constants/teamConstants';

export const MembershipTable = ({ memberships, onUpdate, onDelete, onAdd }) => {
  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState('');

  const isEditing = (record) => record.id === editingKey;

  const edit = (record) => {
    form.setFieldsValue({ ...record });
    setEditingKey(record.id);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      setEditingKey('');
      onUpdate(key, row);
    } catch (error) {
      console.error('Save failed:', error);
    }
  };

  const columns = [
    {
      title: '成员',
      dataIndex: 'users',
      key: 'users',
      editable: true,
      render: (users) => (
        <div className="flex flex-col">
          <span className="font-medium">{users.email}</span>
          <span className="text-gray-500 text-sm">{users.email}</span>
        </div>
      ),
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      editable: true,
      render: (role) => (
        <Tag color={roleColors[role]}>
          {role.toLowerCase()}
        </Tag>
      ),
    },
    {
      title: '创建者',
      dataIndex: 'is_creator',
      key: 'is_creator',
      render: (is_creator) => (
        is_creator ? (
          <Tag color="green">是</Tag>
        ) : (
          <Tag color="default">否</Tag>
        )
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <Space>
            <Button
              icon={<SaveOutlined />}
              onClick={() => save(record.id)}
              type="link"
               size='small'
            >
              保存
            </Button>
            <Button
              icon={<CloseOutlined />}
              onClick={cancel}
              type="link"
               size='small'
            >
              取消
            </Button>
          </Space>
        ) : (
          <Space>
            <Button
              disabled={editingKey !== '' || record.isCreator}
              icon={<EditOutlined />}
              onClick={() => edit(record)}
              type="link"
               size='small'
            >
              编辑
            </Button>
            {!record.isCreator && (
              <Popconfirm
                title="确定要删除该成员吗？"
                onConfirm={() => onDelete(record.id)}
              >
                <Button
                  icon={<DeleteOutlined />}
                  type="link"
                   size='small'
                  danger
                >
                  删除
                </Button>
              </Popconfirm>
            )}
          </Space>
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <div className="space-y-4">
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={onAdd}
        className="mb-4"
      >
        添加成员
      </Button>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableMembershipCell,
            },
          }}
          columns={mergedColumns}
          dataSource={memberships}
          rowKey="id"
          pagination={false}
        />
      </Form>
    </div>
  );
};