import React, { useEffect, useState } from 'react';
import { Card, App } from 'antd';
import { TeamHeader } from './components/TeamHeader';
import { TeamTable } from './components/TeamTable';
import CreateTeamModal from './components/CreateTeamModal';
import { useTeams } from '@/hooks/team/useTeams';
import { useAuth } from '@/contexts/AuthContext';

const TeamManagement = () => {
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  
  const [sorter, setSorter] = useState({
    field: 'created_at',
    order: 'descend',
  });

  const { 
    teams, 
    loading, 
    fetchTeams, 
    createTeam, 
    updateTeam, 
    deleteTeam 
  } = useTeams(pagination, sorter);

  const [modalVisible, setModalVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const { user } = useAuth();

  useEffect(() => {
    const loadTeams = async () => {
      const { total } = await fetchTeams();
      setPagination(prev => ({ ...prev, total }));
    };
    loadTeams();
  }, [fetchTeams]);

  const handleTableChange = (newPagination, filters, newSorter) => {
    const params = {
      current: newPagination?.current,
      pageSize: newPagination?.pageSize,
      field: newSorter?.field,
      order: newSorter?.order,
    };

    setPagination(prev => ({
      ...prev,
      current: params.current,
      pageSize: params.pageSize,
    }));

    setSorter({
      field: params.field || sorter.field,
      order: params.order || sorter.order,
    });

    fetchTeams(params).then(({ total }) => {
      setPagination(prev => ({ ...prev, total }));
    });
  };

  const handleAdd = () => {
    setModalVisible(true);
  };

  const handleModalCancel = () => {
    setModalVisible(false);
  };

  const handleModalSubmit = async (values) => {
    try {
      setConfirmLoading(true);
      await createTeam({ ...values, userId: user.id });
      setModalVisible(false);
      setPagination(prev => ({ ...prev, current: 1 }));
      const { total } = await fetchTeams({ current: 1 });
      setPagination(prev => ({ ...prev, total }));
    } catch (error) {
      console.error('Failed to create team:', error);
    } finally {
      setConfirmLoading(false);
    }
  };
  const onSearch=(value)=>{
    fetchTeams({search:value})
  }
  return (
    <App>
      <Card title="团队管理" bordered={false}>
        <TeamHeader onSearch={onSearch} onAdd={handleAdd} />
        <TeamTable 
          tableLoading={loading}
          dataSource={teams}
          pagination={pagination}
          onTableChange={handleTableChange}
          onUpdate={updateTeam}
          onDelete={deleteTeam}
        />
        <CreateTeamModal
          open={modalVisible}
          onCancel={handleModalCancel}
          onSubmit={handleModalSubmit}
          confirmLoading={confirmLoading}
        />
      </Card>
    </App>
  );
};

export default TeamManagement;