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

export const TeamForm = ({ form }) => {
  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  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('file')
        .upload(filePath, file);

      if (uploadError) throw uploadError;

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

      form.setFieldsValue({ 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="avatarUrl"
        label="团队头像"
        valuePropName="fileList"
        getValueFromEvent={normFile}
      >
        <Upload
          customRequest={handleUpload}
          showUploadList={false}
          maxCount={1}
          listType="picture-card"
        >
          {form.getFieldValue('avatarUrl') ? (
            <img
              src={form.getFieldValue('avatarUrl')}
              alt="avatar"
              className="w-full h-full object-cover"
            />
          ) : (
            <div>
              <PlusOutlined />
              <div className="mt-2">上传头像</div>
            </div>
          )}
        </Upload>
      </Form.Item>

   
    </Form>
  );
};