'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import {
    Button, Card, Col, DatePicker, Form, Input, InputNumber, message, 
    Row, Select, Space, Table, Tabs, Typography, Modal
} from 'antd';
import type { TableProps, TablePaginationConfig } from 'antd';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import dayjs, { Dayjs } from 'dayjs';
import { api } from '@/services/api';
import { BaseResponse } from '@/types/api';
import LoadingSpinner from '@/components/LoadingSpinner';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

// --- TypeScript Interfaces ---
interface ActivationCodeVO {
    id: number;
    code: string;
    value: number;
    isUsed: number;
    userId?: number | null;
    userName?: string | null;
    useTime?: string | null;
    expireTime?: string | null;
    batchId?: string | null;
    createTime: string;
    updateTime: string;
}

interface GenerateCodesRequest {
    count: number;
    value: number;
    expireTime?: string | null; // ISO string or null
    batchId?: string | null;
}

interface ActivationCodeQueryFormData extends ActivationCodeQueryRequest {
    expireTimeRange?: [Dayjs | null, Dayjs | null]; // Changed from any
    createTimeRange?: [Dayjs | null, Dayjs | null]; // Changed from any
}

interface ActivationCodeQueryRequest {
    current?: number;
    pageSize?: number;
    code?: string;
    isUsed?: number;
    batchId?: string;
    userId?: number;
    valueMin?: number;
    valueMax?: number;
    expireTimeStart?: string; 
    expireTimeEnd?: string;   
    createTimeStart?: string; 
    createTimeEnd?: string;   
    sortField?: string;
    sortOrder?: string; 
}

interface Page<T> {
    records: T[];
    total: number;
    current: number;
    size: number;
}

const AdminActivationCodesPage = () => {
    const { user, isAuthenticated, isLoading: authLoading } = useAuth();
    const router = useRouter();

    const [generateForm] = Form.useForm<GenerateCodesRequest>();
    const [queryForm] = Form.useForm<ActivationCodeQueryFormData>();

    const [generatedCodes, setGeneratedCodes] = useState<string[]>([]);
    const [isGenerating, setIsGenerating] = useState(false);
    
    const [activationCodes, setActivationCodes] = useState<ActivationCodeVO[]>([]);
    const [totalCodes, setTotalCodes] = useState(0);
    const [codesLoading, setCodesLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
    });

    // 添加删除Modal的状态
    const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
    const [currentCodeId, setCurrentCodeId] = useState<number | null>(null);

    // 权限检查和重定向
    useEffect(() => {
        if (!authLoading) {
            if (!isAuthenticated) {
                router.replace('/login');
            } else if (user?.role !== 'admin') {
                message.error('您没有权限访问此页面。');
                router.replace('/dashboard'); // 或者其他非管理员默认页
            }
        }
    }, [authLoading, isAuthenticated, user, router]);

    // --- Generate Codes Logic ---
    const handleGenerateCodes = async (values: GenerateCodesRequest) => {
        setIsGenerating(true);
        setGeneratedCodes([]);
        try {
            const requestPayload = {
                ...values,
                expireTime: values.expireTime ? dayjs(values.expireTime).toISOString() : null,
            };
            const response = await api.post<BaseResponse<string[]>>('/activation-code/admin/generate', requestPayload);
            if (response.data.code === 0 && response.data.data) {
                setGeneratedCodes(response.data.data);
                message.success(`成功生成 ${response.data.data.length} 个激活码！`);
                generateForm.resetFields();
                fetchActivationCodes({ current: 1 });
            } else {
                message.error(response.data.message || '生成激活码失败');
            }
        } catch (error: unknown) {
            let errorMessage = '生成激活码时发生错误';
            if (typeof error === 'object' && error !== null) {
                const potentialError = error as { response?: { data?: { message?: string } }, message?: string };
                errorMessage = potentialError.response?.data?.message || potentialError.message || errorMessage;
            }
            message.error(errorMessage);
        }
        setIsGenerating(false);
    };

    // --- List Codes Logic ---
    const fetchActivationCodes = useCallback(async (params: Partial<ActivationCodeQueryRequest> = {}) => {
        setCodesLoading(true);
        try {
            const formValues = queryForm.getFieldsValue();
            const queryParams: ActivationCodeQueryRequest = {
                current: pagination.current,
                pageSize: pagination.pageSize,
                ...formValues,
                ...params,
            };

            if (formValues.expireTimeRange && formValues.expireTimeRange[0] && formValues.expireTimeRange[1]) {
                queryParams.expireTimeStart = formValues.expireTimeRange[0].toISOString();
                queryParams.expireTimeEnd = formValues.expireTimeRange[1].toISOString();
            }
            delete (queryParams as ActivationCodeQueryFormData).expireTimeRange;

            if (formValues.createTimeRange && formValues.createTimeRange[0] && formValues.createTimeRange[1]) {
                queryParams.createTimeStart = formValues.createTimeRange[0].toISOString();
                queryParams.createTimeEnd = formValues.createTimeRange[1].toISOString();
            }
            delete (queryParams as ActivationCodeQueryFormData).createTimeRange;

            const response = await api.post<BaseResponse<Page<ActivationCodeVO>>>('/activation-code/admin/list/page', queryParams);
            if (response.data.code === 0 && response.data.data) {
                setActivationCodes(response.data.data.records || []);
                setTotalCodes(response.data.data.total || 0);
            } else {
                message.error(response.data.message || '获取激活码列表失败');
                setActivationCodes([]);
                setTotalCodes(0);
            }
        } catch (error: unknown) {
            let errorMessage = '获取激活码列表时发生错误';
            if (typeof error === 'object' && error !== null) {
                const potentialError = error as { response?: { data?: { message?: string } }, message?: string };
                errorMessage = potentialError.response?.data?.message || potentialError.message || errorMessage;
            }
            message.error(errorMessage);
            setActivationCodes([]);
            setTotalCodes(0);
        }
        setCodesLoading(false);
    }, [pagination, queryForm]);

    useEffect(() => {
        if (isAuthenticated && user?.role === 'admin') {
            fetchActivationCodes();
        }
    }, [fetchActivationCodes, isAuthenticated, user]);

    const handleTableChange = (newPagination: TablePaginationConfig, filters: Record<string, FilterValue | null>, sorter: SorterResult<ActivationCodeVO> | SorterResult<ActivationCodeVO>[]) => {
        const sortParams: Partial<ActivationCodeQueryRequest> = {};
        
        const currentSorter = Array.isArray(sorter) ? sorter[0] : sorter;

        if (currentSorter && currentSorter.field && currentSorter.order) {
            sortParams.sortField = String(currentSorter.field);
            sortParams.sortOrder = currentSorter.order === 'ascend' ? 'asc' : 'desc';
        }
        
        const newPager = {
            current: newPagination.current || 1,
            pageSize: newPagination.pageSize || pagination.pageSize,
        };
        setPagination(newPager);
        fetchActivationCodes({ 
            ...newPager,
            ...sortParams
         });
    };
    
    const onQueryFinish = () => {
        const newPager = {...pagination, current: 1};
        setPagination(newPager);
        fetchActivationCodes({current: 1});
    }

    const handleDeleteCode = (codeId: number) => {
        console.log('handleDeleteCode called with ID:', codeId);
        setCurrentCodeId(codeId);
        setIsDeleteModalVisible(true);
        console.log('Delete modal state set to visible');
    };

    // 处理删除确认
    const handleDeleteConfirm = () => {
        if (currentCodeId) {
            console.log('Delete confirmed for ID:', currentCodeId);
            
            // 实际执行删除的代码
            api.post<BaseResponse<boolean>>(
                `/activation-code/admin/delete`,
                { id: currentCodeId }
            ).then(response => {
                if (response.data.code === 0 && response.data.data === true) {
                    message.success('激活码删除成功！');
                    fetchActivationCodes({ current: pagination.current }); // 刷新当前页
                } else {
                    message.error(response.data.message || '删除失败');
                }
            }).catch(error => {
                message.error(error.message || '删除激活码时发生网络错误');
            });
        }
        setIsDeleteModalVisible(false);
    };

    // 处理取消
    const handleDeleteCancel = () => {
        console.log('Delete cancelled');
        setIsDeleteModalVisible(false);
    };

    // --- Columns for Activation Codes Table ---
    const columns: TableProps<ActivationCodeVO>['columns'] = [
        { title: 'ID', dataIndex: 'id', key: 'id', sorter: true },
        { title: '激活码', dataIndex: 'code', key: 'code' },
        { title: '面值', dataIndex: 'value', key: 'value', sorter: true, render: (val: number) => `¥${val.toFixed(2)}` },
        {
            title: '状态', dataIndex: 'isUsed', key: 'isUsed', sorter: true,
            render: (isUsed: number) => isUsed === 1 ? <Text type="danger">已使用</Text> : <Text type="success">未使用</Text>,
            filters: [
                { text: '未使用', value: 0 },
                { text: '已使用', value: 1 },
            ],
        },
        { title: '使用者ID', dataIndex: 'userId', key: 'userId', sorter: true },
        { title: '使用者', dataIndex: 'userName', key: 'userName' },
        { title: '使用时间', dataIndex: 'useTime', key: 'useTime', sorter: true, render: (time: string) => time ? new Date(time).toLocaleString() : '-' },
        { title: '过期时间', dataIndex: 'expireTime', key: 'expireTime', sorter: true, render: (time: string) => time ? new Date(time).toLocaleString() : '永不' },
        { title: '批次号', dataIndex: 'batchId', key: 'batchId' },
        { title: '创建时间', dataIndex: 'createTime', key: 'createTime', sorter: true, defaultSortOrder: 'descend', render: (time: string) => new Date(time).toLocaleString() },
        {
            title: '操作',
            key: 'action',
            render: (_: unknown, record: ActivationCodeVO) => (
                <Space size="middle">
                    <Button type="link" danger onClick={() => handleDeleteCode(record.id)}>
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    if (authLoading) return <LoadingSpinner />;
    if (!isAuthenticated || user?.role !== 'admin') return null; // 或显示权限不足的组件

    return (
        <div style={{ padding: '24px' }}>
            <Title level={2} style={{ marginBottom: '24px' }}>激活码管理中心</Title>

            <Tabs defaultActiveKey="1">
                <TabPane tab="生成激活码" key="1">
                    <Card title="批量生成激活码" style={{ marginBottom: 24 }}>
                        <Form form={generateForm} layout="vertical" onFinish={handleGenerateCodes}>
                            <Row gutter={16}>
                                <Col xs={24} sm={12} md={8}>
                                    <Form.Item name="count" label="生成数量" rules={[{ required: true, message: '请输入生成数量' }]}>
                                        <InputNumber min={1} max={1000} style={{ width: '100%' }} placeholder="例如: 100" />
                                    </Form.Item>
                                </Col>
                                <Col xs={24} sm={12} md={8}>
                                    <Form.Item name="value" label="激活码面值 (元)" rules={[{ required: true, message: '请输入激活码面值' }]}>
                                        <InputNumber min={0.01} step={0.01} style={{ width: '100%' }} placeholder="例如: 10.00" />
                                    </Form.Item>
                                </Col>
                                <Col xs={24} sm={12} md={8}>
                                    <Form.Item name="expireTime" label="过期时间 (可选)">
                                        <DatePicker showTime style={{ width: '100%' }} placeholder="选择日期和时间" format="YYYY-MM-DD HH:mm:ss" />
                                    </Form.Item>
                                </Col>
                                <Col xs={24} sm={12} md={8}>
                                    <Form.Item name="batchId" label="批次号 (可选)">
                                        <Input placeholder="例如: spring_promo_2024" />
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Form.Item>
                                <Button type="primary" htmlType="submit" loading={isGenerating} disabled={isGenerating}>
                                    {isGenerating ? '正在生成...' : '立即生成'}
                                </Button>
                            </Form.Item>
                        </Form>
                        {generatedCodes.length > 0 && (
                            <Card title="本次生成的激活码" type="inner" style={{ marginTop: 16 }}>
                                <Space direction="vertical" style={{width: '100%'}}>
                                {generatedCodes.map((code, index) => (
                                    <Text copyable key={index}>{code}</Text>
                                ))}
                                </Space>
                                <Text type="secondary" style={{marginTop: 8, display: 'block'}}>共生成 {generatedCodes.length} 个。请妥善保管。</Text>
                            </Card>
                        )}
                    </Card>
                </TabPane>

                <TabPane tab="管理激活码列表" key="2">
                    <Card title="筛选查询" style={{ marginBottom: 24 }}>
                        <Form form={queryForm} layout="vertical" onFinish={onQueryFinish}>
                            <Row gutter={16}>
                                <Col xs={24} sm={12} md={6}><Form.Item name="code" label="激活码"><Input placeholder="模糊查询" /></Form.Item></Col>
                                <Col xs={24} sm={12} md={6}>
                                    <Form.Item name="isUsed" label="使用状态">
                                        <Select allowClear placeholder="全部状态">
                                            <Select.Option value={0}>未使用</Select.Option>
                                            <Select.Option value={1}>已使用</Select.Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col xs={24} sm={12} md={6}><Form.Item name="batchId" label="批次号"><Input placeholder="精确查询" /></Form.Item></Col>
                                <Col xs={24} sm={12} md={6}><Form.Item name="userId" label="使用者ID"><InputNumber style={{ width: '100%' }} placeholder="精确查询" /></Form.Item></Col>
                                <Col xs={24} sm={12} md={6}><Form.Item name="valueMin" label="最小面值"><InputNumber style={{ width: '100%' }} /></Form.Item></Col>
                                <Col xs={24} sm={12} md={6}><Form.Item name="valueMax" label="最大面值"><InputNumber style={{ width: '100%' }} /></Form.Item></Col>
                                <Col xs={24} sm={12} md={6}><Form.Item name="expireTimeRange" label="过期时间范围">
                                    <RangePicker showTime style={{ width: '100%' }} format="YYYY-MM-DD HH:mm:ss" />
                                </Form.Item></Col>
                                <Col xs={24} sm={12} md={6}><Form.Item name="createTimeRange" label="创建时间范围">
                                    <RangePicker showTime style={{ width: '100%' }} format="YYYY-MM-DD HH:mm:ss" />
                                </Form.Item></Col>
                            </Row>
                            <Form.Item>
                                <Button type="primary" htmlType="submit" loading={codesLoading}>查询</Button>
                                <Button style={{ marginLeft: 8 }} onClick={() => { queryForm.resetFields(); onQueryFinish(); }}>重置</Button>
                            </Form.Item>
                        </Form>
                    </Card>
                    <Table
                        columns={columns}
                        dataSource={activationCodes}
                        loading={codesLoading}
                        rowKey="id"
                        pagination={{
                            current: pagination.current,
                            pageSize: pagination.pageSize,
                            total: totalCodes,
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: ['10', '20', '50', '100'],
                        }}
                        onChange={handleTableChange}
                        scroll={{ x: 'max-content' }}
                    />
                </TabPane>
            </Tabs>

            {/* 删除确认对话框 */}
            <Modal
                title="确认删除"
                open={isDeleteModalVisible}
                onOk={handleDeleteConfirm}
                onCancel={handleDeleteCancel}
                okText="确认删除"
                cancelText="取消"
                okType="danger"
            >
                <p>您确定要删除这个激活码 (ID: {currentCodeId}) 吗？此操作不可恢复。</p>
            </Modal>
        </div>
    );
};

export default AdminActivationCodesPage; 