import { useRef, useState, useEffect } from 'react';
import { useIntl } from '@umijs/max';
import {
  PageContainer,
  ProTable,
  ModalForm,
  ProFormText,
  ProFormTextArea,
  ProFormDigit,
  ProFormSwitch,
  ProFormSelect,
} from '@ant-design/pro-components';
import type { ProColumns, ActionType, ProFormInstance } from '@ant-design/pro-components';
import { Alert, Button, Popconfirm, message, Space, Tag, Row, Col, Radio, Upload, Form } from 'antd';
import type { UploadFile, UploadChangeParam } from 'antd';
import { PlusOutlined, LinkOutlined, UploadOutlined, InboxOutlined } from '@ant-design/icons';
import {
  listProductLinks,
  createProductLink,
  updateProductLink,
  deleteProductLink,
  listAssets,
} from '@/services/admin/api';
import { getApiErrorMessage } from '@/utils';
import { getAccessToken } from '@/services/auth/tokenManager';

const { Dragger } = Upload;

const deleteUploadedFile = async (url: string) => {
  try {
    await fetch(`/api/admin/upload?path=${encodeURIComponent(url)}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${getAccessToken() || ''}` },
    });
  } catch {
    // silent
  }
};

const DISPLAY_AREA_OPTIONS = [
  { label: '仅协议面板', value: 'protocol' },
  { label: '仅底部验证卡片', value: 'verification' },
  { label: '两处均显示', value: 'both' },
];

const DISPLAY_AREA_TAG: Record<string, { color: string; label: string }> = {
  protocol:     { color: 'blue',   label: '协议面板' },
  verification: { color: 'green',  label: '底部验证卡片' },
  both:         { color: 'purple', label: '两处均显示' },
};

function DisplayAreaTag({ area }: { area: string }) {
  const cfg = DISPLAY_AREA_TAG[area] ?? { color: 'default', label: area || '未设置' };
  return <Tag color={cfg.color}>{cfg.label}</Tag>;
}

const ProductLinksPage: React.FC = () => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const searchFormRef = useRef<ProFormInstance>();
  const modalFormRef = useRef<ProFormInstance>();
  const searchTimer = useRef<ReturnType<typeof setTimeout>>();

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

  const autoFillDisplayOrder = async (assetId: number) => {
    if (editRecord?.id) return;
    try {
      const res = await listProductLinks({ asset_id: assetId, pageSize: 100 });
      const max = (res.data ?? []).reduce((m: number, r: AdminAPI.ProductLink) => Math.max(m, r.display_order ?? 0), 0);
      modalFormRef.current?.setFieldValue('display_order', max + 1);
    } catch {}
  };
  const [modalOpen, setModalOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<Partial<AdminAPI.ProductLink> | null>(null);
  const [assetMap, setAssetMap] = useState<Record<number, string>>({});
  const [assetOptions, setAssetOptions] = useState<{ label: string; value: number }[]>([]);
  const [urlMode, setUrlMode] = useState<'link' | 'upload'>('link');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploadedUrl, setUploadedUrl] = useState<string>('');
  const savedRef = useRef(false);

  useEffect(() => {
    listAssets({ pageSize: 100 }).then((res) => {
      if (res.data) {
        const map: Record<number, string> = {};
        const opts: { label: string; value: number }[] = [];
        res.data.forEach((a) => {
          map[a.id] = a.name || a.asset_code;
          opts.push({ label: `${a.name || a.asset_code} (${a.asset_code})`, value: a.id });
        });
        setAssetMap(map);
        setAssetOptions(opts);
      }
    });
  }, []);

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

  const resetUpload = () => {
    setFileList([]);
    setUploadedUrl('');
  };

  const openCreate = () => {
    setEditRecord(null);
    setUrlMode('link');
    resetUpload();
    savedRef.current = false;
    setModalOpen(true);
  };

  const openEdit = (record: AdminAPI.ProductLink) => {
    setEditRecord(record);
    setUrlMode('link');
    resetUpload();
    savedRef.current = false;
    setModalOpen(true);
  };

  const handleUploadChange = ({ file, fileList: newList }: UploadChangeParam) => {
    setFileList(newList);
    if (file.status === 'done') {
      const url = file.response?.data?.url;
      if (url) {
        setUploadedUrl(url);
        message.success(t('pages.admin.auditReports.uploadSuccess'));
      } else {
        message.error(t('pages.admin.auditReports.uploadFailed'));
      }
    } else if (file.status === 'error') {
      setUploadedUrl('');
      message.error(file.response?.message || t('pages.admin.auditReports.uploadFailed'));
    } else if (file.status === 'removed') {
      if (uploadedUrl) deleteUploadedFile(uploadedUrl);
      setUploadedUrl('');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (urlMode === 'upload') {
        if (!uploadedUrl) {
          const uploading = fileList.some((f) => f.status === 'uploading');
          message.error(uploading
            ? t('pages.admin.auditReports.waitForUpload')
            : t('pages.admin.auditReports.pleaseUploadFile')
          );
          return false;
        }
        values.link_url = uploadedUrl;
      }

      if (editRecord?.id) {
        await updateProductLink(editRecord.id, values);
        message.success(t('pages.admin.common.updateSuccess'));
      } else {
        await createProductLink(values);
        message.success(t('pages.admin.common.createSuccess'));
      }
      savedRef.current = true;
      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 deleteProductLink(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.ProductLink>[] = [
    { title: 'ID', dataIndex: 'id', width: 60, search: false },
    {
      title: t('pages.admin.productLinks.asset'),
      dataIndex: 'asset_id',
      width: 180,
      renderFormItem: () => (
        <ProFormSelect
          name="asset_id"
          options={assetOptions}
          fieldProps={{
            showSearch: true,
            optionFilterProp: 'label',
            allowClear: true,
            onChange: () => searchFormRef.current?.submit(),
          }}
        />
      ),
      render: (_, record) =>
        assetMap[record.asset_id]
          ? `${assetMap[record.asset_id]} (ID:${record.asset_id})`
          : record.asset_id,
    },
    {
      title: t('pages.admin.productLinks.linkText'),
      dataIndex: 'link_text',
      width: 160,
      search: false,
    },
    {
      title: t('pages.admin.productLinks.location'),
      dataIndex: 'display_area',
      width: 160,
      search: false,
      render: (v: string) => <DisplayAreaTag area={v} />,
    },
    {
      title: t('pages.admin.productLinks.linkUrl'),
      dataIndex: 'link_url',
      width: 240,
      search: false,
      ellipsis: true,
      render: (_, record) => (
        <a href={record.link_url} target="_blank" rel="noreferrer">
          <LinkOutlined /> {record.link_url}
        </a>
      ),
    },
    {
      title: t('pages.admin.productLinks.description'),
      dataIndex: 'description',
      width: 220,
      search: false,
      ellipsis: true,
    },
    { title: t('pages.admin.productLinks.displayOrder'), dataIndex: 'display_order', width: 80, search: false },
    {
      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 }
    : { display_order: 0, is_active: true, display_area: 'protocol' };

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

      <ModalForm
        formRef={modalFormRef}
        title={editRecord ? t('pages.admin.productLinks.edit') : t('pages.admin.productLinks.create')}
        open={modalOpen}
        onOpenChange={(open) => {
          setModalOpen(open);
          if (!open) {
            if (!savedRef.current && uploadedUrl) deleteUploadedFile(uploadedUrl);
            resetUpload();
          }
        }}
        onFinish={handleSubmit}
        initialValues={initialValues}
        modalProps={{ destroyOnHidden: true }}
        width={960}
        layout="vertical"
      >
        <Alert
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
          message={t('pages.admin.productLinks.locationHint')}
          description={
            <ul style={{ margin: '4px 0 0', paddingLeft: 16, fontSize: 13 }}>
              <li>{t('pages.admin.productLinks.locationHintPanel')}</li>
              <li>{t('pages.admin.productLinks.locationHintCard')}</li>
            </ul>
          }
        />
        <Row gutter={16}>
          <Col span={12}>
            <ProFormSelect
              name="asset_id"
              label={t('pages.admin.productLinks.asset')}
              rules={[{ required: true }]}
              options={assetOptions}
              fieldProps={{ showSearch: true, optionFilterProp: 'label', onChange: (v) => { if (v) autoFillDisplayOrder(v); } }}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="link_text"
              label={t('pages.admin.productLinks.linkText')}
              rules={[{ required: true }]}
              placeholder="Smart Contract / Compliance / Proof of Reserves"
            />
          </Col>
        </Row>

        <Form.Item label={t('pages.admin.productLinks.linkUrl')} required>
          <Radio.Group
            value={urlMode}
            onChange={(e) => { setUrlMode(e.target.value); resetUpload(); }}
            style={{ marginBottom: 12 }}
          >
            <Radio.Button value="link"><LinkOutlined /> {t('pages.admin.auditReports.inputUrl')}</Radio.Button>
            <Radio.Button value="upload"><UploadOutlined /> {t('pages.admin.auditReports.uploadFile')}</Radio.Button>
          </Radio.Group>

          {urlMode === 'link' ? (
            <ProFormText
              name="link_url"
              noStyle
              rules={[{ required: true }, { type: 'url', message: 'Enter a valid URL' }]}
              placeholder="https://..."
            />
          ) : (
            <>
              <Dragger
                name="file"
                action="/api/admin/upload?category=links"
                headers={{ Authorization: `Bearer ${getAccessToken() || ''}` }}
                accept=".pdf,.png,.jpg,.jpeg,.doc,.docx,.txt,.xls,.xlsx"
                maxCount={1}
                fileList={fileList}
                onChange={handleUploadChange}
                beforeUpload={(file) => {
                  const allowed = [
                    'application/pdf',
                    'image/png',
                    'image/jpeg',
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'text/plain',
                    'application/vnd.ms-excel',
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                  ];
                  if (!allowed.includes(file.type)) {
                    message.error('Only PDF / PNG / JPG / Word / TXT / Excel allowed');
                    return Upload.LIST_IGNORE;
                  }
                  return true;
                }}
              >
                <p className="ant-upload-drag-icon"><InboxOutlined /></p>
                <p className="ant-upload-text">{t('pages.admin.auditReports.dragOrClick')}</p>
                <p className="ant-upload-hint">PDF / PNG / JPG / Word / TXT / Excel，max 20MB</p>
              </Dragger>
              {editRecord?.link_url && fileList.length === 0 && (
                <div style={{ marginTop: 8, fontSize: 12, color: '#888' }}>
                  {t('pages.admin.auditReports.currentFile')}：
                  <a href={editRecord.link_url} target="_blank" rel="noopener noreferrer">
                    {editRecord.link_url}
                  </a>
                </div>
              )}
            </>
          )}
        </Form.Item>

        <ProFormTextArea
          name="description"
          label={t('pages.admin.productLinks.description')}
          fieldProps={{ rows: 2 }}
          placeholder="e.g. Audited by OpenZeppelin & Certik for security and reliability."
        />
        <ProFormSelect
          name="display_area"
          label={t('pages.admin.productLinks.displayArea')}
          options={DISPLAY_AREA_OPTIONS}
          rules={[{ required: true }]}
        />
        <Row gutter={16}>
          <Col span={12}>
            <ProFormDigit
              name="display_order"
              label={t('pages.admin.productLinks.displayOrder')}
              min={0}
              initialValue={0}
            />
          </Col>
          <Col span={12}><ProFormSwitch name="is_active" label={t('pages.admin.common.isActive')} initialValue={true} /></Col>
        </Row>
      </ModalForm>
    </PageContainer>
  );
};

export default ProductLinksPage;
