import React from 'react';
import { Form, Input, Select, Upload } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { supabase } from '@/config/supabase';

export const TeamForm = ({ form }) => {
  const handleUpload = async ({ file, onSuccess, onError }) => {
    try {
      const fileExt = file.name.split('.').pop();
      const fileName = `${Math.random()}.${fileExt}`;
      const filePath = `team-avatars/${fileName}`;

      const { error: uploadError } = await supabase.storage
        .from('avatars')
        .upload(filePath, file);

      if (uploadError) throw uploadError;

      const { data: { publicUrl } } = supabase.storage
        .from('avatars')
        .getPublicUrl(filePath);

      form.setFieldValue('avatarUrl', publicUrl);
      onSuccess(publicUrl);
    } catch (error) {
      console.error('Upload error:', error);
      onError(error);
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      requiredMark={false}
    >
      <Form.Item
        name="name"
        label="团队名称"
        rules={[{ required: true, message: '请输入团队名称' }]}
      >
        <Input placeholder="请输入团队名称" />
      </Form.Item>
      <Form.Item
        name="type"
        label="项目归属"
      >
        <Input placeholder="请输入项目归属" />
      </Form.Item>
      <Form.Item
        name="avatarUrl"
        label="团队头像"
      >
        <Upload
          customRequest={handleUpload}
          showUploadList={false}
          maxCount={1}
          listType="picture-card"
        >
          {form.getFieldValue('avatarUrl') ? (
            <img
              src={form.getFieldValue('avatarUrl')}
              alt="avatar"
              style={{ width: '100%', height: '100%', objectFit: 'cover' }}
            />
          ) : (
            <div>
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>上传头像</div>
            </div>
          )}
        </Upload>
      </Form.Item>

     
    </Form>
  );
};