import { useParams } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { Row, Col, Space, Button, Table, Input, Typography, Modal, Tag, App } from 'antd'
import {
  FileOutlined
} from '@ant-design/icons'
import { usingStorage } from '@/hooks/usingStorage'
import useReservationStore from '@/stores/Reservation'
import { useTranslation } from 'react-i18next'
import BackBtn from '@/components/BackBtn'

const { Title, Paragraph } = Typography
const { TextArea } = Input

function Detail() {
  const { t } = useTranslation()

  const confirmationListColumns = [
    {
      title: 'Notes & Changes',
      dataIndex: 'PCI_Changetext',
    },
    {
      title: t('group:ResSendingDate'),
      dataIndex: 'PCI_SendDate',
    },
    {
      title: t('group:ConfirmationDetails'),
      render: detailTextRender
    },
    {
      title: t('group:Attachments'),
      render: attachmentRender
    },
    {
      title: t('group:ConfirmationDate'),
      dataIndex: 'PCI_ConfirmDate',
    },
    {
      title: '',
      render: confirmRender
    },
  ];

  function detailTextRender(text, confirm) {
    const formattedText = confirm.PCI_ConfirmText;//.replace(/\;/g, '\n——————————————————————\n');
    return (
      <div className='whitespace-pre-line'>
      {formattedText}
      </div>
    );
  }

  function attachmentRender(text, confirm) {
    return (
      <>
      {confirm.attachmentList.map(attch => {
        return (
          <Tag bordered={false} icon={<FileOutlined />}><a href={attch.file_url} target='_blank'>{attch.file_name}</a></Tag>
        )}
      )}
      </>
    );
  }

  function confirmRender(text, confirm) {
    return (
      <Button type='link' onClick={() => showConfirmModal(confirm)}>{t('Confirm')}</Button>
    );
  }

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [confirmText, setConfirmText] = useState('');
  const [newConfirmText, setNewConfirmText] = useState('');
  const [dataLoading, setDataLoading] = useState(false);
  const { notification } = App.useApp();
  const { reservationId } = useParams();

  const { travelAgencyId, loginToken } = usingStorage()

  const [getReservationDetail, reservationDetail, confirmationList, selectConfirmation, submitConfirmation] =
    useReservationStore((state) =>
      [state.getReservationDetail, state.reservationDetail, state.confirmationList, state.selectConfirmation, state.submitConfirmation])

  const officeWebViewerUrl =
    'https://view.officeapps.live.com/op/embed.aspx?wdPrint=1&wdHideGridlines=0&wdHideComments=1&wdEmbedCode=0&src=';
  // 测试文档：https://www.chinahighlights.com/public/reservationW220420009.doc
  const reservationUrl =
    `https://p9axztuwd7x8a7.mycht.cn/service-fileServer/DownloadPlanDoc?GRI_SN=${reservationId}&VEI_SN=${travelAgencyId}&token=${loginToken}&FileType=1`;
  const nameCardUrl =
    `https://p9axztuwd7x8a7.mycht.cn/service-fileServer/DownloadPlanDoc?GRI_SN=${reservationId}&VEI_SN=${travelAgencyId}&token=${loginToken}&FileType=2`;

  const reservationPreviewUrl = officeWebViewerUrl + encodeURIComponent(reservationUrl);
  const nameCardPreviewUrl = officeWebViewerUrl + encodeURIComponent(nameCardUrl);

  const showConfirmModal = (confirm) => {
    setIsModalOpen(true);
    const formattedText = confirm.PCI_ConfirmText;//.replace(/\;/g, '\n——————————————————————\n');
    setConfirmText(formattedText);
    selectConfirmation(confirm);
  };

  const handleOk = () => {
    setConfirmLoading(true);
    submitConfirmation(confirmText + '\n——————————————————————\n' +newConfirmText)
      .finally(() => {
        setNewConfirmText('');
        setIsModalOpen(false);
        setConfirmLoading(false);
      });
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  useEffect(() => {
    setDataLoading(true);
    getReservationDetail(reservationId)
      .catch(ex => {
        notification.error({
          message: `Notification`,
          description: ex.message,
          placement: 'top',
          duration: 4,
        });
      })
      .finally(() => {
        setDataLoading(false);
      });
  }, [reservationId]);

  return (
    <>
    <Modal
        centered
        confirmLoading={confirmLoading}
        open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
      >
        <Title level={4}>{t('group:ConfirmationDetails')}</Title>
        <Paragraph>
          <blockquote>
            <div className='whitespace-pre-line'>
              {confirmText}
            </div>
          </blockquote>
        </Paragraph>

        <TextArea
          value={newConfirmText}
          onChange={(e) => setNewConfirmText(e.target.value)}
          autoSize={{
            minRows: 5,
            maxRows: 8,
          }}
        />
      </Modal>
    <Space direction='vertical' className='w-full'>
    <Row gutter={{ md: 24 }}>
        <Col span={20}>
      <Title level={4}>{t('group:RefNo')}: {reservationDetail.referenceNumber}; {t('group:ArrivalDate')}: {reservationDetail.arrivalDate};</Title>
        </Col>
        <Col span={4}>
          <BackBtn to={'/reservation/newest?back'} />
        </Col>
      </Row>
      <Row gutter={{ md: 24 }}>
        <Col span={12} className='w-full'>
        <iframe id='msdoc-iframe-reservation' title='msdoc-iframe-reservation'
        src={reservationPreviewUrl} frameBorder='0' className='w-full h-[600px]'></iframe>
          <Button type='link' target='_blank' href={reservationUrl}>{t('Download')} Itinerary</Button>
        </Col>
        <Col span={12} className='w-full'>
        <iframe id='msdoc-iframe-name-card' title='msdoc-iframe-name-card'
        src={nameCardPreviewUrl} frameBorder='0' className='w-full h-[600px]'></iframe>
          <Button type='link' target='_blank' href={nameCardUrl}>{t('Download')} Name Card</Button>
        </Col>
      </Row>
      <Row>
        <Col span={24}><Space direction='vertical' className='w-full'>
          <Table
            bordered
            loading={dataLoading}
            pagination={false}
            dataSource={confirmationList} columns={confirmationListColumns}
          />
          </Space>
        </Col>
      </Row>
    </Space>
    </>
  );
}

export default Detail;
