import { useState } from 'react';
import {
  Alert, Button, Card, Col, Form, Input, InputNumber, Row, Space, Tabs, Typography, message,
} from 'antd';
import { request } from '../lib/api';

type ApiResult = Record<string, unknown>;

function ResultBox({ data }: { data: ApiResult | null }) {
  if (!data) return <Typography.Text type="secondary">调用后在此显示结果</Typography.Text>;
  return (
    <pre style={{
      margin: 0, padding: 12, background: '#f5f5f5', borderRadius: 4,
      maxHeight: 320, overflow: 'auto', fontSize: 12,
    }}>
      {JSON.stringify(data, null, 2)}
    </pre>
  );
}

export default function RedeemDebugPage() {
  const [createForm] = Form.useForm();
  const [previewForm] = Form.useForm();
  const [confirmForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [createResult, setCreateResult] = useState<ApiResult | null>(null);
  const [previewResult, setPreviewResult] = useState<ApiResult | null>(null);
  const [confirmResult, setConfirmResult] = useState<ApiResult | null>(null);

  async function invoke(
    path: string,
    body: unknown,
    setResult: (v: ApiResult | null) => void,
    successMsg: string,
  ) {
    setLoading(true);
    setResult(null);
    try {
      const res = await request<ApiResult>(path, {
        method: 'POST',
        body: JSON.stringify(body),
      });
      setResult(res);
      message.success(successMsg);
      if (path.includes('create-token') && res.token) {
        previewForm.setFieldsValue({ token: res.token });
        confirmForm.setFieldsValue({ token: res.token });
      }
    } catch (e) {
      message.error(e instanceof Error ? e.message : '调用失败');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      <Typography.Title level={4}>核销调试</Typography.Title>
      <Alert
        type="warning"
        showIcon
        style={{ marginBottom: 16 }}
        message="仅用于 preV1 联调"
        description="模拟 C 端生成核销码、门店预览与确认核销。确认核销会真实扣减权益并写入核销记录。"
      />

      <Tabs
        items={[
          {
            key: 'create',
            label: '1. 生成核销码',
            children: (
              <Row gutter={16}>
                <Col xs={24} lg={10}>
                  <Card size="small" title="参数">
                    <Form form={createForm} layout="vertical">
                      <Form.Item name="userId" label="用户 ID" rules={[{ required: true }]}>
                        <Input placeholder="用户表 id" />
                      </Form.Item>
                      <Form.Item name="amount" label="核销金额" rules={[{ required: true }]}>
                        <InputNumber min={0.01} max={500} step={1} style={{ width: '100%' }} />
                      </Form.Item>
                      <Form.Item name="couponId" label="指定券 ID（可选）">
                        <Input placeholder="不填则自动分摊" />
                      </Form.Item>
                      <Form.Item name="storeId" label="绑定门店 ID（可选）">
                        <Input placeholder="绑定后仅该门店可核销" />
                      </Form.Item>
                      <Button
                        type="primary"
                        loading={loading}
                        onClick={() => {
                          const values = createForm.getFieldsValue();
                          void invoke('/admin/redeem/debug/create-token', values, setCreateResult, '核销码已生成');
                        }}
                      >
                        生成核销码
                      </Button>
                    </Form>
                  </Card>
                </Col>
                <Col xs={24} lg={14}>
                  <Card size="small" title="响应">
                    <ResultBox data={createResult} />
                  </Card>
                </Col>
              </Row>
            ),
          },
          {
            key: 'preview',
            label: '2. 预览核销',
            children: (
              <Row gutter={16}>
                <Col xs={24} lg={10}>
                  <Card size="small" title="参数">
                    <Form form={previewForm} layout="vertical">
                      <Form.Item name="storeId" label="门店 ID" rules={[{ required: true }]}>
                        <Input />
                      </Form.Item>
                      <Form.Item name="token" label="核销码" rules={[{ required: true }]}>
                        <Input />
                      </Form.Item>
                      <Button
                        loading={loading}
                        onClick={() => {
                          const values = previewForm.getFieldsValue();
                          void invoke('/admin/redeem/debug/preview', values, setPreviewResult, '预览成功');
                        }}
                      >
                        预览
                      </Button>
                    </Form>
                  </Card>
                </Col>
                <Col xs={24} lg={14}>
                  <Card size="small" title="响应">
                    <ResultBox data={previewResult} />
                  </Card>
                </Col>
              </Row>
            ),
          },
          {
            key: 'confirm',
            label: '3. 确认核销',
            children: (
              <Row gutter={16}>
                <Col xs={24} lg={10}>
                  <Card size="small" title="参数">
                    <Form form={confirmForm} layout="vertical">
                      <Form.Item name="storeId" label="门店 ID" rules={[{ required: true }]}>
                        <Input />
                      </Form.Item>
                      <Form.Item name="token" label="核销码" rules={[{ required: true }]}>
                        <Input />
                      </Form.Item>
                      <Space>
                        <Button
                          type="primary"
                          danger
                          loading={loading}
                          onClick={() => {
                            const values = confirmForm.getFieldsValue();
                            void invoke('/admin/redeem/debug/confirm', values, setConfirmResult, '核销成功');
                          }}
                        >
                          确认核销
                        </Button>
                      </Space>
                    </Form>
                  </Card>
                </Col>
                <Col xs={24} lg={14}>
                  <Card size="small" title="响应">
                    <ResultBox data={confirmResult} />
                  </Card>
                </Col>
              </Row>
            ),
          },
        ]}
      />
    </div>
  );
}
