import React, { useEffect } from 'react';
import { Button, Space, message } from 'antd';
import { useState } from 'react';
import { useStaff } from '@nice/client';
import { PlusOutlined } from '@ant-design/icons';
import DefaultFieldInitializer from './defaultFieldInitializer';
import StaffFieldTable from './staffFieldTable';
import StaffFieldModal from './staffFieldModal';
import { useWatch } from 'antd/es/form/Form';
import { Form } from 'antd';

const StaffFieldManage = () => {
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingField, setEditingField] = useState<any>(null);
  const { 
    addCustomField, 
    updateCustomField, 
    deleteCustomField,
    useCustomFields
  } = useStaff();
  const { data: fields, isLoading } = useCustomFields();
  const optionFieldTypes = ['select', 'radio',]; 
  const [showOptions, setShowOptions] = useState(false); 
  const typeValue = useWatch('type', form);

  useEffect(() => {
    setShowOptions(optionFieldTypes.includes(typeValue));
  }, [typeValue, optionFieldTypes]);

  const [isInitConfirmVisible, setIsInitConfirmVisible] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);

  const checkFieldExists = (name: string, excludeId?: string) => {
    return fields?.some(field => 
      field.name === name && field.id !== excludeId
    );
  };

  const handleAdd = () => {
    setEditingField(null);
    form.resetFields();
    form.setFieldsValue({ options: [] }); 
    setIsModalVisible(true);
  };

  const handleEdit = (record: any) => {
    setEditingField(record);
    let optionsToSet = record.options;
    if (typeof record.options === 'object' && record.options !== null && !Array.isArray(record.options)) {
      optionsToSet = Object.entries(record.options).map(([value, label]) => ({ label, value }));
    }
    form.setFieldsValue({ ...record, options: optionsToSet }); 
    setIsModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteCustomField.mutateAsync(id);
      message.success('字段删除成功');
    } catch (error) {
      message.error('字段删除失败');
    }
  };
  
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的字段');
      return;
    }
    try {
      await Promise.all(
        selectedRowKeys.map(async (id: string) => { 
          await deleteCustomField.mutateAsync(id);
        })
      );
      message.success('批量删除成功');
      setSelectedRowKeys([]);
    } catch (error) {
      message.error('批量删除失败');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (checkFieldExists(values.name, editingField?.id)) {
        message.error('字段标识已存在，请使用其他标识');
        return;
      }

      setIsProcessing(true);

      if (editingField) {
        await updateCustomField.mutateAsync({
          id: editingField.id,
          ...values,
        });
        message.success('字段更新成功');
      } else {
        await addCustomField.mutateAsync(values);
        message.success('字段添加成功');
      }
      setIsModalVisible(false);
    } catch (error) {
      message.error('操作失败：' + (error instanceof Error ? error.message : '未知错误'));
    } finally {
      setIsProcessing(false);
    }
  };

  

  return (
    <div className="bg-white p-6 rounded-lg shadow">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-lg font-semibold">字段管理</h2>
        <Space>
          <DefaultFieldInitializer
            fields={fields}
            isProcessing={isProcessing}
            setIsProcessing={setIsProcessing}
            isInitConfirmVisible={isInitConfirmVisible}
            setIsInitConfirmVisible={setIsInitConfirmVisible}
          />
          
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
            loading={isProcessing}
          >
            添加字段
          </Button>
        </Space>
      </div>

      <StaffFieldTable
        fields={fields}
        isLoading={isLoading}
        isProcessing={isProcessing}
        selectedRowKeys={selectedRowKeys}
        setSelectedRowKeys={setSelectedRowKeys}
        handleEdit={handleEdit}
        handleDelete={handleDelete}
        handleBatchDelete={handleBatchDelete}
      />

      <StaffFieldModal
        form={form}
        isModalVisible={isModalVisible}
        setIsModalVisible={setIsModalVisible}
        editingField={editingField}
        isProcessing={isProcessing}
        handleSubmit={handleSubmit}
        optionFieldTypes={optionFieldTypes}
        showOptions={showOptions}
      />
    </div>
  );
};

export default StaffFieldManage;