import { useState, useEffect, useRef } from 'react';
import apiFetch from '@wordpress/api-fetch';
import {
    Panel,
    PanelBody,
    PanelRow,
    TextControl,
    TextareaControl,
    Button,
    Spinner,
    Notice
} from '@wordpress/components';

export default function Admin() {
    const [options, setOptions] = useState({ webhook_url: '', message_template: '' });
    const [isLoading, setIsLoading] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [isTesting, setIsTesting] = useState(false);
    const formRef = useRef(null);
    const [notice, setNotice] = useState(null);
    const [isFormValid, setIsFormValid] = useState(true);

    useEffect(() => {
        apiFetch({ path: '/instcowe/v1/options' }).then((data) => {
            setOptions(data);
            setIsLoading(false);
        });
    }, []);

    useEffect(() => {
        setIsFormValid(formRef.current ? formRef.current.checkValidity() : true);
    }, [options]);

    const handleSave = (event) => {
        event.preventDefault();
        setIsSaving(true);
        apiFetch({
            path: '/instcowe/v1/options',
            method: 'POST',
            data: options,
        }).then(() => {
            setNotice({ status: 'success', message: '设置已保存' });
        }).catch((error) => {
            setNotice({ status: 'error', message: `保存失败: ${error.message}` });
        }).finally(() => {
            setIsSaving(false);
        });
    };

    const handleTest = () => {
        setNotice(null);
        setIsTesting(true);
        const url = new URL(options.webhook_url);
        const token = url.searchParams.get("key");

        apiFetch({
            path: '/instcowe/v1/test-notification',
            method: 'POST',
            data: { ...options, token },
        }).then(() => {
            setNotice({ status: 'success', message: '测试通知已发送' });
        }).catch((error) => {
            setNotice({ status: 'error', message: `测试失败: ${error.message}` });
        }).finally(() => {
            setIsTesting(false);
        });
    };

    const handleInputChange = (name, value) => {
        setOptions({ ...options, [name]: value });
    };

    if (isLoading) {
        return <Spinner />;
    }

    return (
        <form ref={formRef}>
            <Panel>
                <PanelBody title="WooCommerce 企业微信通知" initialOpen={true}>
                    {notice && (
                        <Notice status={notice.status} onRemove={() => setNotice(null)}>
                            {notice.message}
                        </Notice>
                    )}
                    <PanelRow>
                        <TextControl
                            label="企业微信 Webhook URL"
                            type="url"
                            value={options.webhook_url}
                            onChange={(value) => handleInputChange('webhook_url', value)}
                            placeholder="请输入 Webhook URL"
                            help={
                                <>
                                    文档:{' '}
                                    <a
                                        href="https://developer.work.weixin.qq.com/document/path/91770"
                                        target="_blank"
                                        rel="noreferrer"
                                    >
                                        https://developer.work.weixin.qq.com/document/path/91770
                                    </a>
                                </>
                            }
                        />
                    </PanelRow>
                    <PanelRow>
                        <TextareaControl
                            label="通知消息模板"
                            value={options.message_template}
                            onChange={(value) => handleInputChange('message_template', value)}
                            rows="10"
                            cols="50"
                            help={
                                <>
                                    <p>可用变量:</p>
                                    <ul>
                                        <li><code>[order_id]</code> - 订单ID</li>
                                        <li><code>[order_total]</code> - 订单总金额</li>
                                        <li><code>[customer_name]</code> - 客户姓名</li>
                                        <li><code>[order_items]</code> - 订单商品列表</li>
                                        <li><code>[payment_method_title]</code> - 支付方式</li>
                                        <li><code>[order_status]</code> - 订单状态</li>
                                    </ul>
                                </>
                            }
                        />
                    </PanelRow>
                    <PanelRow>
                        <div style={{ display: 'flex', gap: '15px' }}>
                            <Button variant="primary" type="submit" onClick={handleSave} disabled={!isFormValid || isSaving}>
                                {isSaving && <Spinner />} 保存
                            </Button>
                            <Button variant="secondary" onClick={handleTest} disabled={!options.webhook_url || !isFormValid || isTesting}>
                                {isTesting && <Spinner />} 测试发送
                            </Button>
                        </div>
                    </PanelRow>
                </PanelBody>
            </Panel>
        </form>
    );
}