import {
  Button,
  Drawer,
  Form,
  FormInstance,
  Input,
  Radio,
  Space,
  Switch,
} from "antd";
import { FC, useRef, useState } from "react";

export interface TopicDrawerProps {
  open: boolean;
  close: () => void;
}

let id = 0;

export const TopicDrawer: FC<TopicDrawerProps> = ({ open, close }) => {
  const optionsFormRef = useRef<FormInstance>(null);

  const [options, setOptions] = useState<
    {
      id: number;
    }[]
  >([]);

  const handleAddOption = () => {
    setOptions((prev) => [
      ...prev,
      {
        id: id++,
      },
    ]);
  };

  const handleRemoveOption = (idx: number) => {
    setOptions((prev) => {
      prev.splice(idx, 1);
      return [...prev];
    });
  };

  const handleSubmit = async () => {
    if (!(await optionsFormRef.current?.validateFields())) return;

    const options = optionsFormRef.current?.getFieldsValue();
    console.log(options);
  };

  return (
    <Drawer
      title="新增题目"
      placement="right"
      width={500}
      open={open}
      onClose={close}
      extra={
        <Space>
          <Button onClick={close}>取消</Button>
          <Button type="primary" onClick={handleSubmit}>
            保存
          </Button>
        </Space>
      }
    >
      <Form layout="vertical">
        <Form.Item
          label="题目描述"
          name="title"
          rules={[{ required: true, message: "请输入内容" }]}
        >
          <Input.TextArea
            placeholder="请输入内容，最多50字"
            maxLength={50}
            showCount
            rows={4}
          />
        </Form.Item>

        <Form.Item label="类型" name="type">
          <Radio.Group buttonStyle="solid">
            <Radio.Button value="1">单选</Radio.Button>
            <Radio.Button value="2">多选</Radio.Button>
          </Radio.Group>
        </Form.Item>

        <Form.Item label="允许自定义答案" name="cus">
          <Switch />
        </Form.Item>
      </Form>

      <Form ref={optionsFormRef}>
        <Button
          type="primary"
          ghost
          onClick={handleAddOption}
          style={{ marginBottom: "15px" }}
        >
          新增选项
        </Button>

        {options.map((i, idx) => (
          <Form.Item
            key={i.id}
            label={`选项${idx + 1}`}
            name={`option_${i.id}`}
            rules={[{ required: true, message: "请输入" }]}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
              }}
            >
              <Input placeholder="请输入" style={{ marginRight: "10px" }} />
              <Button
                type="text"
                danger
                size="small"
                onClick={handleRemoveOption.bind(undefined, idx)}
              >
                删除
              </Button>
            </div>
          </Form.Item>
        ))}
      </Form>
    </Drawer>
  );
};
