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 CustomerForm = () => {
  const { id } = useParams();
  const [searchParams] = useSearchParams();
  const isView = id&&!searchParams.get('edit');
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const fetchCustomerDetail = 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,
          level: data.attributes.level || 'regular',
          status: data.attributes.status || 'active',
          remark: data.attributes.remark
        });
      }
    } catch (error) {
      console.error('获取客户详情失败:', error);
    }
  };

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

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

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

      if (result.error) throw result.error;
      navigate('/company/customer');
    } 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 ? '编辑客户' : '新建客户'}
              </Title>
              <span className="text-gray-400 text-sm">
                {id ? '请修改客户信息' : '请填写客户信息'}
              </span>
            </div>
            <Space size="middle">
              <Button 
                icon={<ArrowLeftOutlined />}
                onClick={() => navigate('/company/customer')}
              >
                返回
              </Button>
              {!isView && (
                <Button 
                  type="primary" 
                  icon={<SaveOutlined />}
                  onClick={() => form.submit()}
                >
                  保存
                </Button>
              )}
            </Space>
          </div>
        }
        styles={{ backgroundColor: '#fff' }}
      >
        <Form
          form={form}
          onFinish={onFinish}
          layout="vertical"
          initialValues={{
            status: 'active',
            level: 'regular'
          }}
          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="level"
              rules={[{ required: true, message: '请选择客户等级' }]}
            >
              <Select>
                <Select.Option value="vip">VIP客户</Select.Option>
                <Select.Option value="regular">普通客户</Select.Option>
                <Select.Option value="potential">潜在客户</Select.Option>
              </Select>
            </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 CustomerForm;