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="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.Item
        name="tags"
        label="标签"
        rules={[{ required: true, message: '请选择至少一个标签' }]}
      >
        <Select
          mode="tags"
          placeholder="请输入或选择标签"
          options={[
            { label: '研发', value: 'development' },
            { label: '设计', value: 'design' },
            { label: '运营', value: 'operation' },
            { label: '市场', value: 'marketing' },
          ]}
        />
      </Form.Item>
    </Form>
  );
};