/**
 * KRA - User Form Component
 * Create/Edit user form in drawer
 */
import React, { useState, useEffect } from 'react';
import {
  Drawer,
  Form,
  Input,
  Button,
  Space,
  Switch,
  Cascader,
  message,
  Avatar,
} from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { register, setUserInfo } from '@/services/kratos/user';
import SelectImage from '@/components/SelectImage/SelectImage';

interface AuthorityOption {
  authorityId: string;
  authorityName: string;
  children?: AuthorityOption[];
}

interface UserFormProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
  initialValues: any | null;
  dialogFlag: 'add' | 'edit';
  authOptions: AuthorityOption[];
}

const UserForm: React.FC<UserFormProps> = ({
  visible,
  onClose,
  onSuccess,
  initialValues,
  dialogFlag,
  authOptions,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [headerImg, setHeaderImg] = useState('');
  const [selectImageVisible, setSelectImageVisible] = useState(false);

  useEffect(() => {
    if (visible) {
      if (initialValues) {
        form.setFieldsValue({
          ...initialValues,
          authorityIds: initialValues.authorityIds || 
            initialValues.authorities?.map((a: any) => a.authorityId) || [],
        });
        setHeaderImg(initialValues.headerImg || '');
      } else {
        form.resetFields();
        form.setFieldsValue({ enable: 1 });
        setHeaderImg('');
      }
    }
  }, [visible, initialValues, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        ...values,
        headerImg,
        authorityId: values.authorityIds?.[0] || '',
        enable: values.enable ? 1 : 2,
      };

      let res;
      if (dialogFlag === 'add') {
        res = await register(submitData);
      } else {
        res = await setUserInfo({ ...initialValues, ...submitData });
      }

      if (res.code === 0) {
        message.success(dialogFlag === 'add' ? '创建成功' : '编辑成功');
        onSuccess();
      } else {
        message.error(res.msg || '操作失败');
      }
    } catch (error) {
      console.error('Form validation failed:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    form.resetFields();
    setHeaderImg('');
    onClose();
  };

  // 转换角色选项为 Cascader 格式
  const convertToCascaderOptions = (options: AuthorityOption[]): any[] => {
    return options.map((item) => ({
      value: item.authorityId,
      label: item.authorityName,
      children: item.children ? convertToCascaderOptions(item.children) : undefined,
    }));
  };

  return (
    <>
      <Drawer
        title={dialogFlag === 'add' ? '新增用户' : '编辑用户'}
        width={500}
        open={visible}
        onClose={handleClose}
        extra={
          <Space>
            <Button onClick={handleClose}>取消</Button>
            <Button type="primary" loading={loading} onClick={handleSubmit}>
              确定
            </Button>
          </Space>
        }
      >
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          initialValues={{ enable: true }}
        >
          {dialogFlag === 'add' && (
            <>
              <Form.Item
                name="userName"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 5, message: '最低5位字符' },
                ]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入用户密码' },
                  { min: 6, message: '最低6位字符' },
                ]}
              >
                <Input.Password placeholder="请输入密码" />
              </Form.Item>
            </>
          )}
          <Form.Item
            name="nickName"
            label="昵称"
            rules={[{ required: true, message: '请输入用户昵称' }]}
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              {
                pattern: /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/,
                message: '请输入合法手机号',
              },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              {
                pattern: /^([0-9A-Za-z\-_.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/,
                message: '请输入正确的邮箱',
              },
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="authorityIds"
            label="用户角色"
            rules={[{ required: true, message: '请选择用户角色' }]}
          >
            <Cascader
              options={convertToCascaderOptions(authOptions)}
              multiple
              showCheckedStrategy="SHOW_CHILD"
              placeholder="请选择用户角色"
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item name="enable" label="启用" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item label="头像">
            <div
              style={{
                width: 100,
                height: 100,
                border: '1px dashed #d9d9d9',
                borderRadius: 8,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                cursor: 'pointer',
                overflow: 'hidden',
              }}
              onClick={() => setSelectImageVisible(true)}
            >
              {headerImg ? (
                <Avatar src={headerImg} size={98} shape="square" />
              ) : (
                <UserOutlined style={{ fontSize: 32, color: '#999' }} />
              )}
            </div>
          </Form.Item>
        </Form>
      </Drawer>

      <SelectImage
        visible={selectImageVisible}
        onCancel={() => setSelectImageVisible(false)}
        onSelect={(url) => {
          setHeaderImg(url);
          setSelectImageVisible(false);
        }}
      />
    </>
  );
};

export default UserForm;
