import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Button, Space, Card, Typography } from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { supabase } from '@/config/supabase';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';

const { TextArea } = Input;
const { Title } = Typography;

const SupplierForm = () => {
  const { id } = useParams();
  const [searchParams] = useSearchParams();
  const isEdit = searchParams.get('edit') === 'true';
  const isView = id && !isEdit;
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const fetchSupplierDetail = async () => {
    try {
      const { data, error } = await supabase
        .from('resources')
        .select('*')
        .eq('id', id)
        .single();

      if (error) throw error;
      
      if (id) {
        // 设置表单初始值
        form.setFieldsValue({
          name: data.attributes.name,
          contact: data.attributes.contact,
          phone: data.attributes.phone,
          address: data.attributes.address,
          status: data.attributes.status || 'active',
          remark: data.attributes.remark
        });
      }
    } catch (error) {
      console.error('获取供应商详情失败:', error);
    }
  };

  useEffect(() => {
    if (id) {
      fetchSupplierDetail();
    }
  }, [id]);

  const onFinish = async (values) => {
    try {
      const supplierData = {
        type: 'supplier',
        attributes: {
          name: values.name,
          contact: values.contact,
          phone: values.phone,
          address: values.address,
          status: values.status,
          remark: values.remark
        }
      };

      let result;
      if (id) {
        result = await supabase
          .from('resources')
          .update(supplierData)
          .eq('id', id)
          .select();
      } else {
        result = await supabase
          .from('resources')
          .insert([supplierData])
          .select();
      }

      if (result.error) throw result.error;
      navigate('/company/supplier');
    } catch (error) {
      console.error('保存失败:', error);
    }
  };

  return (
    <div className="bg-gradient-to-b from-gray-50 to-white min-h-screen p-6">
      <Card 
        className="shadow-lg rounded-lg border-0"
        title={
          <div className="flex justify-between items-center py-2">
            <div className="flex items-center space-x-3">
              <Title level={4} className="mb-0 text-gray-800">
                {id ? (isEdit ? '编辑供应商' : '查看供应商') : '新建供应商'}
              </Title>
              <span className="text-gray-400 text-sm">
                {id ? (isEdit ? '请修改供应商信息' : '供应商详情') : '请填写供应商信息'}
              </span>
            </div>
            <Space size="middle">
              <Button 
                icon={<ArrowLeftOutlined />}
                onClick={() => navigate('/company/supplier')}
              >
                返回
              </Button>
              {!isView && (
                <Button 
                  type="primary" 
                  icon={<SaveOutlined />}
                  onClick={() => form.submit()}
                >
                  保存
                </Button>
              )}
            </Space>
          </div>
        }
        style={{ backgroundColor: '#fff' }}
      >
        <Form
          form={form}
          onFinish={onFinish}
          layout="vertical"
          initialValues={{
            status: 'active'
          }}
          className="space-y-6"
          disabled={isView}
        >
          {/* 基本信息卡片 */}
          <Card 
            className="shadow-sm rounded-lg"
            type="inner" 
            title={
              <span className="flex items-center space-x-2 text-gray-700">
                <span className="w-1 h-4 bg-blue-500 rounded-full"/>
                <span>基本信息</span>
              </span>
            }
          >
            <Form.Item
              label="供应商名称"
              name="name"
              rules={[{ required: true, message: '请输入供应商名称' }]}
            >
              <Input placeholder="请输入供应商名称" />
            </Form.Item>

            <Form.Item
              label="联系人"
              name="contact"
              rules={[{ required: true, message: '请输入联系人姓名' }]}
            >
              <Input placeholder="请输入联系人姓名" />
            </Form.Item>

            <Form.Item
              label="联系电话"
              name="phone"
              rules={[
                { required: true, message: '请输入联系电话' },
              ]}
            >
              <Input placeholder="请输入联系电话" />
            </Form.Item>

            <Form.Item
              label="地址"
              name="address"
            >
              <Input.TextArea rows={3} placeholder="请输入详细地址" />
            </Form.Item>

            <Form.Item
              label="状态"
              name="status"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Select>
                <Select.Option value="active">启用</Select.Option>
                <Select.Option value="inactive">禁用</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="备注"
              name="remark"
            >
              <Input.TextArea rows={3} placeholder="请输入备注信息" />
            </Form.Item>
          </Card>
        </Form>
      </Card>
    </div>
  );
};

export default SupplierForm;