import { NavLink, useLocation } from "react-router-dom";
import { useState, useEffect } from 'react';
import { observer } from "mobx-react";
import { toJS } from "mobx";
import { Row, Col, Space, Button, Table, Input, Typography, DatePicker, Modal, App, Select } from 'antd';
import dayjs from "dayjs";
import { useStore } from '@/stores/StoreContext.js';
import { isEmpty, objectMapper } from "@/utils/commons";
import { useTranslation } from 'react-i18next';
import usePresets from '@/hooks/usePresets';
import useAuthStore from '@/stores/Auth'
import useReservationStore from '@/stores/Reservation'
import SearchForm from '@/components/SearchForm';

const { Title } = Typography;

function Newest() {
  const { t } = useTranslation();
  const presets = usePresets();
  const reservationListColumns = [
    {
      title: t('group:RefNo'),
      dataIndex: 'referenceNumber',
      key: 'Reference number',
      render: (text, record) => {
        const after3Dayjs = dayjs().add(3, 'day');
        const lastDayjs = dayjs().subtract(1, 'day');
        const arrivalDatejs = dayjs(record.arrivalDate);
        const requiredHighlight = (arrivalDatejs.isAfter(lastDayjs) && arrivalDatejs.isBefore(after3Dayjs, 'day')) && isEmpty(record.guide);
        const linkClassName = requiredHighlight ? 'reservation-highlight' : '';
        return (
          <NavLink className={linkClassName} to={`/reservation/${record.reservationId}`}>{text}</NavLink>
        )
      },
    },
    {
      title: t('group:ArrivalDate'),
      dataIndex: 'arrivalDate',
      key: 'Arrival date',
			render: (text, record) => (isEmpty(text) ? '' : dayjs(text).format('YYYY-MM-DD')),
    },
    {
      title: t('group:Pax'),
      key: 'Pax',
      dataIndex: 'pax'
    },
    {
      title: t('group:Status'),
      key: 'Status',
      dataIndex: 'status'
    },
    {
      title: t('group:ResSendingDate'),
      key: 'Reservation date',
      dataIndex: 'reservationDate',
			render: (text, record) => (isEmpty(text) ? '' : dayjs(text).format('YYYY-MM-DD')),
    },
    {
      title: t('group:Guide'),
      key: 'Guide',
      dataIndex: 'guide',
      render: guideRender
    },
  ];

  function guideRender(text, reservation) {
    if (reservation.guide === '') {
      return (
        <Space size="middle">
          <Button type="link" onClick={() => showCityGuideModal(reservation)}>{t('Add')}</Button>
        </Space>
      );
    } else {
      return (
        <Space size="middle">
          <span>{reservation.guide}</span>
          <Button type="link" onClick={() => showCityGuideModal(reservation)}>{t('Edit')}</Button>
        </Space>
      );
    }
  }

  function cityGuideRender(text, city) {
    return (
      <Select
        showSearch
        style={{
          width: 280,
        }}
        bordered={false}
        allowClear
        placeholder="Select a guide"
        optionFilterProp="children"
        defaultValue={(guideSelectOptions.length == 0 || city.tourGuideId == 0) ? null : city.tourGuideId}
        onChange={(guideId) => {
          reservationStore.setupCityGuide(city.cityId, guideId);
        }}
        onSearch={(value) => {
          // console.log('search:', value);
        }}
        filterOption={(input, option) =>
          (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
        }
        options={toJS(guideSelectOptions)}
      />
    );
  }

	const location = useLocation();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [dataLoading, setDataLoading] = useState(false);
  const [guideSelectOptions, setGuideSelectOptions] = useState([]);
  const { reservationStore } = useStore();
  const loginUser = useAuthStore((state) => state.loginUser)

  const [fetchAllGuideList, fetchReservationList, reservationList] =
    useReservationStore((state) => [state.fetchAllGuideList, state.fetchReservationList, state.reservationList])

  const { reservationPage, cityList } = reservationStore;
  const { notification } = App.useApp();

  useEffect (() => {
    if (location.search !== '?back') {
      // 第一页，未确认计划
      onSearchClick(1, 1);
    }
    fetchAllGuideList(loginUser.travelAgencyId)
      .then((guideList) => {
        const selectOptions = guideList.map((data, index) => {
          return {
            value: data.guideId,
            label: data.guideName
          }
        });
        // setGuideSelectOptions(selectOptions);
      });
    return () => {
      // unmount...
    };
  }, []);

  const showCityGuideModal = (reservation) => {
    setDataLoading(true);
    setIsModalOpen(true);
    reservationStore.editReservation(reservation);
    reservationStore.fetchCityList(reservation.reservationId)
      .catch(ex => {
        notification.error({
          message: `Notification`,
          description: ex.message,
          placement: 'top',
          duration: 4,
        });
      })
      .finally(() => {
        setDataLoading(false);
      });
  };
  const handleOk = () => {
    reservationStore.updateReservationGuide()
      .finally(() => {
        setIsModalOpen(false);
        setDataLoading(false);
      });
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    setDataLoading(false);
  };

  // 默认重新搜索第一页，所有状态的计划
  const onSearchClick = (current=1, status=null) => {
    setDataLoading(true)
    fetchReservationList(loginUser.travelAgencyId, current, status)
      .catch(ex => {
        notification.error({
          message: `Notification`,
          description: ex.message,
          placement: 'top',
          duration: 4,
        });
      })
      .finally(() => {
        setDataLoading(false)
      })
  }

  return (
    <>
      <Modal
        centered
        open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Row>
            <Col span={24}>
              <Table
                bordered
                loading={dataLoading}
                pagination={false}
                columns={[
                  {
                    title: t('group:City'),
                    dataIndex: 'cityName',
                    key: 'cityName'
                  },
                  {
                    title: t('group:Guide'),
                    dataIndex: 'tourGuide',
                    key: 'tourGuide',
                    render: cityGuideRender,
                  }
                ]}
                dataSource={toJS(cityList)}
              />
            </Col>
          </Row>
        </Space>
      </Modal>
      <Space direction="vertical" style={{ width: '100%' }}>
        <Title level={3}></Title>
        <SearchForm
          // initialValue={
          //   {
          //   }
          // }
          defaultValue={{
            shows: ['referenceNo', 'dates'],
            fieldProps: {
              dates: { label: t('group:ArrivalDate') },
            },
          }}
          onSubmit={(err, formVal, filedsVal) => {
            setDataLoading(true)
            fetchReservationList(loginUser.travelAgencyId, formVal)
              .catch(ex => {
                notification.error({
                  message: `Notification`,
                  description: ex.message,
                  placement: 'top',
                  duration: 4,
                });
              })
              .finally(() => {
                setDataLoading(false)
              })
          }}
        />
        <Title level={3}></Title>
        <Row>
          <Col span={24}>
            <Table
              title={() => t('group:3DGuideTip')}
              bordered
              loading={dataLoading}
              pagination={{
                position: ['bottomCenter'],
                current: reservationPage.current,
                pageSize: reservationPage.size,
                total: reservationPage.total,
                simple: true
              }}
              onChange={(pagination, filters, sorter, extra) => {onSearchClick(pagination.current)}}
              columns={reservationListColumns} dataSource={reservationList}
            />
          </Col>
        </Row>
      </Space>
    </>
  );
}

export default observer(Newest);
