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 {
  listSeasons,
  createSeason,
  updateSeason,
  deleteSeason,
} from '@/services/admin/api';
import { getApiErrorMessage } from '@/utils';

const statusColorMap: Record<string, string> = {
  upcoming: 'blue',
  active: 'green',
  ended: 'default',
};

const SeasonsPage: 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.Season> | 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.Season) => {
    setEditRecord(record);
    setModalOpen(true);
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editRecord?.id) {
        await updateSeason(editRecord.id, values);
        message.success(t('pages.admin.common.updateSuccess'));
      } else {
        await createSeason(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 deleteSeason(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.Season>[] = [
    { title: 'ID', dataIndex: 'id', width: 60, search: false },
    { title: '#', dataIndex: 'season_number', width: 60, search: false },
    { title: t('pages.admin.seasons.seasonName'), dataIndex: 'season_name', width: 160 },
    { title: t('pages.admin.seasons.status'), dataIndex: 'status', width: 100,
      valueEnum: { upcoming: 'Upcoming', active: 'Active', ended: 'Ended' },
      render: (v: any) => <Tag color={statusColorMap[v] ?? 'default'}>{v}</Tag> },
    { title: t('pages.admin.seasons.multiplier'), dataIndex: 'multiplier', width: 100, search: false,
      render: (v: any) => `${v}x` },
    { title: t('pages.admin.seasons.totalRewards'), dataIndex: 'total_rewards', width: 130, search: false },
    { title: t('pages.admin.seasons.startTime'), dataIndex: 'start_time', width: 160, search: false,
      render: (v: any) => v ? new Date(v).toLocaleString() : '-' },
    { title: t('pages.admin.seasons.endTime'), dataIndex: 'end_time', width: 160, search: false,
      render: (v: any) => v ? new Date(v).toLocaleString() : '-' },
    { 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 } : {};

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

      <ModalForm
        title={editRecord ? t('pages.admin.seasons.edit') : t('pages.admin.seasons.create')}
        open={modalOpen}
        onOpenChange={setModalOpen}
        onFinish={handleSubmit}
        initialValues={initialValues}
        modalProps={{ destroyOnHidden: true }}
        width={960}
        layout="vertical"
      >
        <Row gutter={16}>
          <Col span={12}><ProFormDigit name="season_number" label={t('pages.admin.seasons.seasonNumber')} rules={[{ required: true }]} min={1} /></Col>
          <Col span={12}><ProFormText name="season_name" label={t('pages.admin.seasons.seasonName')} rules={[{ required: true }]} /></Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <ProFormSelect
              name="status"
              label={t('pages.admin.seasons.status')}
              options={[
                { label: 'Upcoming', value: 'upcoming' },
                { label: 'Active', value: 'active' },
                { label: 'Ended', value: 'ended' },
              ]}
              rules={[{ required: true }]}
              initialValue="upcoming"
            />
          </Col>
          <Col span={12}><ProFormDigit name="multiplier" label={t('pages.admin.seasons.multiplier')} min={0} fieldProps={{ step: 0.1 }} initialValue={1} /></Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormDigit name="total_rewards" label={t('pages.admin.seasons.totalRewards')} min={0} /></Col>
          <Col span={12} />
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormDateTimePicker name="start_time" label={t('pages.admin.seasons.startTime')} rules={[{ required: true }]} /></Col>
          <Col span={12}><ProFormDateTimePicker name="end_time" label={t('pages.admin.seasons.endTime')} rules={[{ required: true }]} /></Col>
        </Row>
        <ProFormTextArea name="description" label={t('pages.admin.common.description')} fieldProps={{ rows: 3 }} />
        <ProFormSwitch name="is_active" label={t('pages.admin.common.isActive')} initialValue={true} />
      </ModalForm>
    </PageContainer>
  );
};

export default SeasonsPage;
