import { useRef, useState } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProTable, ModalForm, ProFormText, ProFormDigit, ProFormSwitch, ProFormSelect, ProFormDateTimePicker, ProFormTextArea } from '@ant-design/pro-components';
import type { ProColumns, ActionType, ProFormInstance } from '@ant-design/pro-components';
import { Button, Popconfirm, message, Space, Tag, Row, Col } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {
  listPointsRules,
  createPointsRule,
  updatePointsRule,
  deletePointsRule,
} from '@/services/admin/api';
import { getApiErrorMessage } from '@/utils';

const isEpochDate = (v: any) => !v || String(v).startsWith('1970-01-01');

const PointsRulesPage: React.FC = () => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const searchFormRef = useRef<ProFormInstance>();
  const searchTimer = useRef<ReturnType<typeof setTimeout>>();
  const [modalOpen, setModalOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<Partial<AdminAPI.PointsRule> | null>(null);

  const t = (id: string) => intl.formatMessage({ id });

  const handleValuesChange = () => {
    clearTimeout(searchTimer.current);
    searchTimer.current = setTimeout(() => searchFormRef.current?.submit(), 500);
  };

  const openCreate = () => {
    setEditRecord(null);
    setModalOpen(true);
  };

  const openEdit = (record: AdminAPI.PointsRule) => {
    setEditRecord(record);
    setModalOpen(true);
  };

  const handleSubmit = async (values: any) => {
    if (values.conditions) {
      try { JSON.parse(values.conditions); } catch {
        message.error('Conditions must be valid JSON');
        return false;
      }
    }
    try {
      if (editRecord?.id) {
        await updatePointsRule(editRecord.id, values);
        message.success(t('pages.admin.common.updateSuccess'));
      } else {
        await createPointsRule(values);
        message.success(t('pages.admin.common.createSuccess'));
      }
      setModalOpen(false);
      actionRef.current?.reload();
      return true;
    } catch (err: any) {
      message.error(getApiErrorMessage(err, t('pages.admin.common.operationFailed')));
      return false;
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await deletePointsRule(id);
      message.success(t('pages.admin.common.deleteSuccess'));
      actionRef.current?.reload();
    } catch (err: any) {
      message.error(getApiErrorMessage(err, t('pages.admin.common.deleteFailed')));
    }
  };

  const columns: ProColumns<AdminAPI.PointsRule>[] = [
    { title: 'ID', dataIndex: 'id', width: 60, search: false },
    { title: t('pages.admin.pointsRules.ruleName'), dataIndex: 'rule_name', width: 160 },
    { title: t('pages.admin.pointsRules.ruleType'), dataIndex: 'rule_type', width: 120,
      valueEnum: { tvl: 'TVL', referral: 'Referral', daily_login: 'Daily Login', task: 'Task' } },
    { title: t('pages.admin.pointsRules.basePoints'), dataIndex: 'base_points', width: 100, search: false },
    { title: t('pages.admin.pointsRules.multiplier'), dataIndex: 'multiplier', width: 100, search: false,
      render: (v: any) => `${v}x` },
    { title: t('pages.admin.pointsRules.priority'), dataIndex: 'priority', width: 80, search: false },
    { title: t('pages.admin.pointsRules.validFrom'), dataIndex: 'valid_from', width: 160, search: false,
      render: (v: any) => {
        if (isEpochDate(v) || v === '0001-01-01T00:00:00Z') return '-';
        const d = new Date(v);
        return isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
      },
    },
    { title: t('pages.admin.pointsRules.validUntil'), dataIndex: 'valid_until', width: 160, search: false,
      render: (v: any) => {
        if (isEpochDate(v) || v === '0001-01-01T00:00:00Z') return '-';
        const d = new Date(v);
        return isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
      },
    },
    { title: t('pages.admin.common.isActive'), dataIndex: 'is_active', width: 80, search: false,
      render: (v: any) => <Tag color={v ? 'green' : 'red'}>{v ? t('pages.admin.common.active') : t('pages.admin.common.inactive')}</Tag> },
    {
      title: t('pages.admin.common.actions'),
      width: 120,
      search: false,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <a onClick={() => openEdit(record)}>{t('pages.admin.common.edit')}</a>
          <Popconfirm title={t('pages.admin.common.confirmDelete')} onConfirm={() => handleDelete(record.id)}>
            <a style={{ color: 'red' }}>{t('pages.admin.common.delete')}</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const initialValues = editRecord ? {
    ...editRecord,
    valid_from: isEpochDate(editRecord.valid_from) ? undefined : editRecord.valid_from,
    valid_until: isEpochDate(editRecord.valid_until) ? undefined : editRecord.valid_until,
  } : {};

  return (
    <PageContainer>
      <ProTable<AdminAPI.PointsRule>
        rowKey="id"
        actionRef={actionRef}
        formRef={searchFormRef}
        search={{ onValuesChange: handleValuesChange }}
        columns={columns}
        request={async (params) => {
          const res = await listPointsRules(params);
          return { data: res.data, success: res.success, total: res.total };
        }}
        toolBarRender={() => [
          <Button key="create" type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            {t('pages.admin.pointsRules.create')}
          </Button>,
        ]}
        scroll={{ x: 1100 }}
        pagination={{ pageSize: 20 }}
      />

      <ModalForm
        title={editRecord ? t('pages.admin.pointsRules.edit') : t('pages.admin.pointsRules.create')}
        open={modalOpen}
        onOpenChange={setModalOpen}
        onFinish={handleSubmit}
        initialValues={initialValues}
        modalProps={{ destroyOnHidden: true }}
        width={960}
        layout="vertical"
      >
        <Row gutter={16}>
          <Col span={12}><ProFormText name="rule_name" label={t('pages.admin.pointsRules.ruleName')} rules={[{ required: true }]} /></Col>
          <Col span={12}>
            <ProFormSelect
              name="rule_type"
              label={t('pages.admin.pointsRules.ruleType')}
              options={[
                { label: 'TVL', value: 'tvl' },
                { label: 'Referral', value: 'referral' },
                { label: 'Daily Login', value: 'daily_login' },
                { label: 'Task', value: 'task' },
                { label: 'Bonus', value: 'bonus' },
              ]}
              rules={[{ required: true }]}
            />
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormDigit name="base_points" label={t('pages.admin.pointsRules.basePoints')} min={0} rules={[{ required: true }]} /></Col>
          <Col span={12}><ProFormDigit name="multiplier" label={t('pages.admin.pointsRules.multiplier')} min={0} fieldProps={{ step: 0.1 }} initialValue={1} /></Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormDigit name="priority" label={t('pages.admin.pointsRules.priority')} min={0} initialValue={0} /></Col>
          <Col span={12}><ProFormText name="description" label={t('pages.admin.common.description')} /></Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormDateTimePicker name="valid_from" label={t('pages.admin.pointsRules.validFrom')} /></Col>
          <Col span={12}><ProFormDateTimePicker name="valid_until" label={t('pages.admin.pointsRules.validUntil')} /></Col>
        </Row>
        <ProFormTextArea
          name="conditions"
          label={t('pages.admin.pointsRules.conditions')}
          fieldProps={{ rows: 3 }}
          placeholder='{"min_tvl": 1000, "chain": "arbitrum"}'
        />
        <ProFormSwitch name="is_active" label={t('pages.admin.common.isActive')} initialValue={true} />
      </ModalForm>
    </PageContainer>
  );
};

export default PointsRulesPage;
