import React, { useState } from 'react';
import { Table, Form, Button, Space, Popconfirm, Tag, message } from 'antd';
import { EditOutlined, DeleteOutlined, SaveOutlined, CloseOutlined } from '@ant-design/icons';
import { EditableCell } from './EditableCell';
import { ExpandedMemberships } from './ExpandedMemberships';
export const TeamTable = ({ tableLoading,pagination,dataSource, onTableChange,onDelete ,onUpdate}) => {
  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState('');
  const [loading, setLoading] = useState(false);
  const isEditing = (record) => record.id === editingKey;

  const edit = (record) => {
    form.setFieldsValue({ 
      name: record.name,
      description: record.description 
    });
    setEditingKey(record.id);
  };

  const cancel = () => {
    setEditingKey('');
    form.resetFields();
  };

  // 保存编辑
  const save = async (key) => {
    try {
      setLoading(true);
      const row = await form.validateFields();
      await onUpdate(key, {
        name: row.name,
        description: row.description,
        updated_at: new Date().toISOString()
      });
      setEditingKey('');
      message.success('更新成功');
      onTableChange?.(); // 刷新数据
    } catch (error) {
      console.error('Save failed:', error);
      message.error('更新失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 删除团队
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      await onDelete(id)
      message.success('删除成功');
      onTableChange?.(); // 刷新数据
    } catch (error) {
      console.error('Delete failed:', error);
      message.error('删除失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '团队名称',
      dataIndex: 'name',
      key: 'name',
      editable: true,
      render: (text, record) => (
        <div className="flex items-center gap-2">
          {record.avatar_url && (
            <img 
              src={record.avatar_url} 
              alt={text} 
              className="w-8 h-8 rounded-full object-cover"
            />
          )}
          <span className="font-medium">{text}</span>
        </div>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      editable: true,
    },
    {
      title: '成员数量',
      dataIndex: 'team_membership',
      key: 'team_membership',
      render: (team_membership) => team_membership?.length || 0,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      sorter:true,
      defaultSortOrder: 'descend', 
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <Space  size={0}>
            <Button
              icon={<SaveOutlined />}
              onClick={() => save(record.id)}
              type="link"
              size='small'
              loading={loading}
            >
              保存
            </Button>
            <Button
             size='small'
              icon={<CloseOutlined />}
              onClick={cancel}
              type="link"
            >
              取消
            </Button>
          </Space>
        ) : (
          <Space>
            <Button
             size='small'
              disabled={editingKey !== ''}
              icon={<EditOutlined />}
              onClick={() => edit(record)}
              type="link"
            >
              编辑
            </Button>
            <Popconfirm
              title="确定要删除该团队吗？"
              onConfirm={() => handleDelete(record.id)}
            >
              <Button
                icon={<DeleteOutlined />}
                type="link"
                danger
                 size='small'
                loading={loading}
              >
                删除
              </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),
      }),
    };
  });
  const handleTableChange = (pagination, filters, sorter, extra) => {
    onTableChange?.(pagination, filters, sorter, extra);

  }
  return (
    <Form form={form} component={false}>
      <Table
      scroll={{ x: true }}
      pagination={pagination}
        loading={loading||tableLoading}
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        onChange={handleTableChange}
        dataSource={dataSource}
        columns={mergedColumns}
        rowKey="id"
        expandable={{
          expandedRowRender: (record) => (
            <ExpandedMemberships 
              memberships={record.team_membership} 
              teamId={record.id}
              onMembershipChange={onTableChange}
            />
          ),
        }}
      />
    </Form>
  );
};