import { Form, FormInstance, Input, InputRef } from "antd";
import React, { useContext, useEffect, useRef, useState } from "react";
import './index.less'

export const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface Item {
    key: string;
    name: string;
    age: string;
    address: string;
}
interface EditableCellProps {
    title: React.ReactNode;
    editable: boolean;
    children: React.ReactNode;
    dataIndex: keyof Item;
    record: Item;
    handleSave: (record: Item) => void;
}
const EditableCell: React.FC<EditableCellProps> = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
}) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef<InputRef>(null);
    const form = useContext(EditableContext)!;

    useEffect(() => {
        if (editing) {
            inputRef.current!.focus();
        }
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();
            if (values?.adgroupName !== (record as any)?.adgroupName) {
                handleSave({ ...record, ...values });
            }
            toggleEdit();
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = children;

    if (editable) {
        childNode = editing ? (<Form.Item
            style={{ margin: 0 }}
            name={dataIndex}
            rules={[{ required: true, message: `${title} is required.` }]}
        >
            <Input ref={inputRef} size="small" onPressEnter={save} onBlur={save} bordered/>
        </Form.Item>) : (<div className="editable-cell-value-wrap ellipsisText" onClick={toggleEdit}>
            {children}
        </div>);
    }

    return <td {...restProps}>{childNode}</td>;
};


export default React.memo(EditableCell)