import { useRef, useState, useEffect } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProTable, ModalForm, ProFormText, ProFormDigit, ProFormSwitch, ProFormSelect, ProFormDatePicker, ProFormTextArea } from '@ant-design/pro-components';
import type { ProColumns, ActionType, ProFormInstance } from '@ant-design/pro-components';
import { Button, Popconfirm, message, Space, Tag, Row, Col, Radio, Upload, Form } from 'antd';
import { PlusOutlined, UploadOutlined, LinkOutlined, InboxOutlined } from '@ant-design/icons';
import type { UploadFile, UploadChangeParam } from 'antd';
import {
  listAuditReports,
  createAuditReport,
  updateAuditReport,
  deleteAuditReport,
  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 — cleanup failure is non-critical
  }
};

const AuditReportsPage: React.FC = () => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const searchFormRef = useRef<ProFormInstance>();
  const modalFormRef = useRef<ProFormInstance>();
  const searchTimer = useRef<ReturnType<typeof setTimeout>>();
  const [modalOpen, setModalOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<Partial<AdminAPI.AssetAuditReport> | null>(null);
  const [assetMap, setAssetMap] = useState<Record<number, string>>({});

  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 listAuditReports({ asset_id: assetId, pageSize: 100 });
      const max = (res.data ?? []).reduce((m: number, r: AdminAPI.AssetAuditReport) => Math.max(m, r.display_order ?? 0), 0);
      modalFormRef.current?.setFieldValue('display_order', max + 1);
    } catch {}
  };
  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} (ID: ${a.id})`, 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.AssetAuditReport) => {
    setEditRecord(record);
    setUrlMode('link');
    resetUpload();
    savedRef.current = false;
    setModalOpen(true);
  };

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

  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 {
      let reportUrl = values.report_url || '';

      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;
        }
        reportUrl = uploadedUrl;
      }

      const payload = { ...values, report_url: reportUrl };

      if (editRecord?.id) {
        await updateAuditReport(editRecord.id, payload);
        message.success(t('pages.admin.common.updateSuccess'));
      } else {
        await createAuditReport(payload);
        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 columns: ProColumns<AdminAPI.AssetAuditReport>[] = [
    { title: 'ID', dataIndex: 'id', width: 60, search: false },
    { title: t('pages.admin.auditReports.assetId'), dataIndex: 'asset_id', width: 140,
      renderFormItem: () => (
        <ProFormSelect
          name="asset_id"
          options={assetOptions}
          fieldProps={{ showSearch: true, optionFilterProp: 'label', allowClear: true }}
        />
      ),
      render: (_, record) => assetMap[record.asset_id] ? `${assetMap[record.asset_id]} (${record.asset_id})` : record.asset_id,
    },
    { title: t('pages.admin.auditReports.reportType'), dataIndex: 'report_type', width: 120,
      valueEnum: { attestation: 'Attestation', audit: 'Audit', compliance: 'Compliance' } },
    { title: t('pages.admin.auditReports.reportTitle'), dataIndex: 'report_title', width: 200, ellipsis: true, search: false },
    { title: t('pages.admin.auditReports.auditorName'), dataIndex: 'auditor_name', width: 140, search: false },
    { title: t('pages.admin.auditReports.reportDate'), dataIndex: 'report_date', width: 120, search: false,
      render: (v: any) => v ? new Date(v).toLocaleDateString() : '-' },
    { title: t('pages.admin.auditReports.reportUrl'), dataIndex: 'report_url', width: 200, search: false, ellipsis: true,
      render: (v: any) => v ? <a href={v} target="_blank" rel="noopener noreferrer">{v}</a> : '-' },
    { title: t('pages.admin.auditReports.displayOrder'), dataIndex: 'display_order', width: 70, 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 } : {};

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

      <ModalForm
        formRef={modalFormRef}
        title={editRecord ? t('pages.admin.auditReports.edit') : t('pages.admin.auditReports.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"
      >
        <Row gutter={16}>
          <Col span={12}><ProFormSelect name="asset_id" label={t('pages.admin.auditReports.assetId')} rules={[{ required: true }]} options={assetOptions} fieldProps={{ onChange: (v) => { if (v) autoFillDisplayOrder(v); } }} /></Col>
          <Col span={12}>
            <ProFormSelect
              name="report_type"
              label={t('pages.admin.auditReports.reportType')}
              options={[
                { label: 'Attestation', value: 'attestation' },
                { label: 'Audit', value: 'audit' },
                { label: 'Compliance', value: 'compliance' },
              ]}
              rules={[{ required: true }]}
            />
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormText name="report_title" label={t('pages.admin.auditReports.reportTitle')} rules={[{ required: true }]} /></Col>
          <Col span={12}><ProFormDatePicker name="report_date" label={t('pages.admin.auditReports.reportDate')} rules={[{ required: true }]} /></Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}><ProFormText name="auditor_name" label={t('pages.admin.auditReports.auditorName')} /></Col>
          <Col span={12}><ProFormDigit name="display_order" label={t('pages.admin.auditReports.displayOrder')} min={0} initialValue={0} /></Col>
        </Row>

        {/* Report URL — 两种方式 */}
        <Form.Item label={t('pages.admin.auditReports.reportUrl')}>
          <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="report_url" noStyle placeholder="https://..." />
          ) : (
            <>
              <Dragger
                name="file"
                action="/api/admin/upload?category=reports"
                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?.report_url && fileList.length === 0 && (
                <div style={{ marginTop: 8, fontSize: 12, color: '#888' }}>
                  {t('pages.admin.auditReports.currentFile')}：
                  <a href={editRecord.report_url} target="_blank" rel="noopener noreferrer">
                    {editRecord.report_url}
                  </a>
                </div>
              )}
            </>
          )}
        </Form.Item>

        <ProFormTextArea name="summary" label={t('pages.admin.auditReports.summary')} fieldProps={{ rows: 3 }} />
        <ProFormSwitch name="is_active" label={t('pages.admin.common.isActive')} initialValue={true} />
      </ModalForm>
    </PageContainer>
  );
};

export default AuditReportsPage;
