import React, { useEffect, useState } from 'react';
import {
  Button, Card, Form, Input, InputNumber, message, Modal, Popconfirm, Select, Space, Switch, Table, Tag, Typography,
} from 'antd';
import {
  GiftOutlined, PlusOutlined, EditOutlined, DeleteOutlined,
} from '@ant-design/icons';
import { getRechargePackages, saveRechargePackage, deleteRechargePackage } from '../api';

interface PackageItem {
  id: string;
  name: string;
  credits: number;
  price: number;
  bonusCredits: number;
  totalCredits: number;
  description: string | null;
  packageType: string;
  isGift: boolean;
  isActive: boolean;
  sortOrder: number;
}

const TYPE_COLORS: Record<string, string> = {
  normal: 'blue',
  gift: 'green',
  promo: 'purple',
};

const TYPE_LABELS: Record<string, string> = {
  normal: '常规',
  gift: '赠送',
  promo: '促销',
};

const AdminRechargePackages: React.FC = () => {
  const [packages, setPackages] = useState<PackageItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [modal, setModal] = useState<{ open: boolean; item: PackageItem | null }>({ open: false, item: null });
  const [form] = Form.useForm();

  const load = async () => {
    setLoading(true);
    try {
      const data = await getRechargePackages();
      setPackages(data.map((item: any) => ({
        id: item.id,
        name: item.name,
        credits: item.credits,
        price: item.price,
        bonusCredits: item.bonus_credits ?? item.bonusCredits ?? 0,
        totalCredits: item.total_credits ?? item.totalCredits ?? item.credits,
        description: item.description,
        packageType: item.package_type ?? item.packageType ?? 'normal',
        isGift: item.is_gift ?? item.isGift ?? false,
        isActive: item.is_active ?? item.isActive ?? true,
        sortOrder: item.sort_order ?? item.sortOrder ?? 0,
      })));
    } catch {
      message.error('加载充值套餐失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); }, []);

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        name: values.name,
        credits: values.credits,
        price: values.price,
        bonus_credits: values.bonusCredits || 0,
        description: values.description || null,
        package_type: values.packageType || 'normal',
        is_gift: values.isGift || false,
        is_active: values.isActive ?? true,
        sort_order: values.sortOrder ?? 0,
      };
      if (modal.item?.id) {
        await saveRechargePackage({ id: modal.item.id, ...payload });
        message.success('已更新');
      } else {
        await saveRechargePackage(payload);
        message.success('已添加');
      }
      setModal({ open: false, item: null });
      form.resetFields();
      load();
    } catch { /* validation */ }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteRechargePackage(id);
      message.success('已删除');
      load();
    } catch (e: any) {
      message.error(e?.message || '删除失败');
    }
  };

  const openEdit = (item?: PackageItem) => {
    setModal({ open: true, item: item || null });
    if (item) {
      form.setFieldsValue({
        name: item.name,
        credits: item.credits,
        price: item.price,
        bonusCredits: item.bonusCredits,
        description: item.description,
        packageType: item.packageType,
        isGift: item.isGift,
        isActive: item.isActive,
        sortOrder: item.sortOrder,
      });
    } else {
      form.resetFields();
      form.setFieldsValue({ isActive: true, sortOrder: 0, packageType: 'normal', bonusCredits: 0, isGift: false });
    }
  };

  const columns = [
    {
      title: '套餐名称', key: 'name', width: 160,
      render: (_: any, r: PackageItem) => (
        <div>
          <Typography.Text strong>{r.name}</Typography.Text>
          {r.description && <div style={{ color: '#94a3b8', fontSize: 12 }}>{r.description}</div>}
        </div>
      ),
    },
    {
      title: '基础积分', dataIndex: 'credits', width: 100,
      render: (v: number) => <Typography.Text>{v.toLocaleString()}</Typography.Text>,
    },
    {
      title: '赠送积分', dataIndex: 'bonusCredits', width: 100,
      render: (v: number) => v > 0
        ? <Tag color="green">+{v.toLocaleString()}</Tag>
        : <Typography.Text type="secondary">-</Typography.Text>,
    },
    {
      title: '总积分', key: 'total', width: 100,
      render: (_: any, r: PackageItem) => (
        <Typography.Text strong style={{ color: '#6366f1' }}>
          {(r.credits + r.bonusCredits).toLocaleString()}
        </Typography.Text>
      ),
    },
    {
      title: '价格(元)', dataIndex: 'price', width: 100,
      render: (v: number) => <Typography.Text strong>¥{v}</Typography.Text>,
    },
    {
      title: '类型', dataIndex: 'packageType', width: 80,
      render: (v: string) => <Tag color={TYPE_COLORS[v] || 'default'}>{TYPE_LABELS[v] || v}</Tag>,
    },
    {
      title: '状态', dataIndex: 'isActive', width: 80,
      render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '停用'}</Tag>,
    },
    {
      title: '操作', key: 'action', width: 150, fixed: 'right' as const,
      render: (_: any, r: PackageItem) => (
        <Space size={4}>
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => openEdit(r)}>编辑</Button>
          <Popconfirm title="确定删除？" onConfirm={() => handleDelete(r.id)}>
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card variant="outlined" style={{ borderRadius: 12, border: '1px solid #f0f0f5' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <Space>
            <GiftOutlined style={{ fontSize: 18, color: '#6366f1' }} />
            <Typography.Text strong style={{ fontSize: 16 }}>充值套餐管理</Typography.Text>
            <Tag color="purple">{packages.length} 个套餐</Tag>
          </Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => openEdit()} style={{ borderRadius: 8 }}>
            添加套餐
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={packages}
          rowKey="id"
          loading={loading}
          pagination={false}
          scroll={{ x: 900 }}
        />
      </Card>

      <Modal
        title={<Space><GiftOutlined />{modal.item ? '编辑套餐' : '添加套餐'}</Space>}
        open={modal.open}
        onOk={handleSave}
        onCancel={() => { setModal({ open: false, item: null }); form.resetFields(); }}
        okText="保存" cancelText="取消" width={520}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item name="name" label="套餐名称" rules={[{ required: true, message: '请输入套餐名称' }]}>
            <Input placeholder="例如：进阶包" size="large" />
          </Form.Item>
          <div style={{ display: 'flex', gap: 16 }}>
            <Form.Item name="credits" label="基础积分" rules={[{ required: true, message: '请输入积分' }]} style={{ flex: 1 }}>
              <InputNumber min={1} placeholder="2000" size="large" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="price" label="价格(元)" rules={[{ required: true, message: '请输入价格' }]} style={{ flex: 1 }}>
              <InputNumber min={0.01} step={1} placeholder="168" size="large" style={{ width: '100%' }} />
            </Form.Item>
          </div>
          <div style={{ display: 'flex', gap: 16 }}>
            <Form.Item name="bonusCredits" label="赠送积分" initialValue={0} style={{ flex: 1 }}>
              <InputNumber min={0} placeholder="0" size="large" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="packageType" label="套餐类型" initialValue="normal" style={{ flex: 1 }}>
              <Select size="large" options={[
                { value: 'normal', label: '常规' },
                { value: 'gift', label: '赠送' },
                { value: 'promo', label: '促销' },
              ]} />
            </Form.Item>
          </div>
          <Form.Item name="description" label="描述">
            <Input placeholder="套餐描述（可选）" size="large" />
          </Form.Item>
          <div style={{ display: 'flex', gap: 16 }}>
            <Form.Item name="isActive" label="启用状态" valuePropName="checked" initialValue={true} style={{ flex: 1 }}>
              <Switch />
            </Form.Item>
            <Form.Item name="isGift" label="是否赠送" valuePropName="checked" initialValue={false} style={{ flex: 1 }}>
              <Switch />
            </Form.Item>
            <Form.Item name="sortOrder" label="排序" initialValue={0} style={{ flex: 1 }}>
              <InputNumber size="large" style={{ width: '100%' }} />
            </Form.Item>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default AdminRechargePackages;
