import { useEffect, useState } from 'react';
import { useParams, Link, useNavigate, useLocation } from 'react-router-dom';
import { App, Button, Divider, Popconfirm, Select } from 'antd';
import { useProductsAuditStatesMapVal } from '@/hooks/useProductsSets';
import { useTranslation } from 'react-i18next';
import useProductsStore, { postProductsQuoteAuditAction, postAgencyAuditAction } from '@/stores/Products/Index';
import { isEmpty, objectMapper } from '@/utils/commons';
import useAuthStore from '@/stores/Auth';
import RequireAuth from '@/components/RequireAuth';
// import PrintContractPDF from './PrintContractPDF';
import { PERM_PRODUCTS_OFFER_AUDIT, PERM_PRODUCTS_OFFER_PUT } from '@/config';
import dayjs from 'dayjs';
import VendorSelector from '@/components/VendorSelector';
import AuditStateSelector from '@/components/AuditStateSelector';

const Header = ({ refresh, newActionable, ...props }) => {
  const location = useLocation();
  const isEditPage = location.pathname.includes('edit');
  const showEditA = !location.pathname.includes('edit');
  const showAuditA = !location.pathname.includes('audit');
  const { travel_agency_id, use_year, audit_state } = useParams();
  const { t } = useTranslation();
  const isPermitted = useAuthStore((state) => state.isPermitted);
  const [activeAgency, setActiveAgency] = useProductsStore((state) => [state.activeAgency, state.setActiveAgency]);
  const [switchParams, setSwitchParams] = useProductsStore((state) => [state.switchParams, state.setSwitchParams]);
  const [activeAgencyState] = useProductsStore((state) => [state.activeAgencyState]);
  const stateMapVal = useProductsAuditStatesMapVal();
  const { message, notification } = App.useApp();
  const navigate = useNavigate();

  const yearOptions = [];
  const currentYear = switchParams.use_year || dayjs().year();
  const baseYear = use_year ? Number(use_year === 'all' ? currentYear : use_year) : currentYear;
  for (let i = currentYear - 5; i <= baseYear + 5; i++) {
    yearOptions.push({ label: i, value: i });
  }

  const [param, setParam] = useState({ pick_year: baseYear, pick_agency: travel_agency_id });
  const [pickYear, setPickYear] = useState(baseYear);
  const [pickAgency, setPickAgency] = useState({ value: activeAgency.travel_agency_id, label: activeAgency.travel_agency_name });
  const [pickAuditState, setPickAuditState] = useState();
  useEffect(() => {
    const _param = objectMapper(param, { pick_year: 'use_year', pick_agency: 'travel_agency_id', pick_state: 'audit_state' });
    setSwitchParams({ ..._param });
    refresh(param);

    return () => {};
  }, [param]);

  const emptyPickState = { value: '', label: t('products:State') };
  useEffect(() => {
    const baseState = audit_state ? (audit_state === 'all' ? emptyPickState : stateMapVal[`${audit_state}`]) : emptyPickState;
    if (isEmpty(pickAuditState)) {
      setPickAuditState(baseState);
    }
    return () => {};
  }, [audit_state, stateMapVal]);

  const handleYearChange = (value) => {
    setPickYear(value);
    setParam((pre) => ({ ...pre, ...{ pick_year: value } }));
  };
  const handleAuditStateChange = (labelValue) => {
    const { value } = labelValue || emptyPickState;
    setPickAuditState(labelValue || emptyPickState);
    setParam((pre) => ({ ...pre, ...{ pick_state: value } }));
  };

  const handleAgencyChange = ({ label, value }) => {
    setPickAgency({ label, value });
    setActiveAgency({ travel_agency_id: value, travel_agency_name: label });
    setParam((pre) => ({ ...pre, ...{ pick_agency: value } }));
  };

  const handleAuditItem = (state, row) => {
    postProductsQuoteAuditAction(state, { id: row.id, travel_agency_id: activeAgency.travel_agency_id })
      .then((json) => {
        if (json.errcode === 0) {
          message.success(json.errmsg);
          if (typeof refresh === 'function') {
            refresh(param);
          }
        }
      })
      .catch((ex) => {
        notification.error({
          message: 'Notification',
          description: ex.message,
          placement: 'top',
          duration: 4,
        });
      });
  };

  const handleSubmitForAudit = () => {
    postAgencyAuditAction(activeAgency.travel_agency_id, switchParams.use_year)
      .then((json) => {
        if (json.errcode === 0) {
          message.success(t('Success'));
          if (typeof refresh === 'function') {
            refresh(param);
            const auditPagePath = isPermitted(PERM_PRODUCTS_OFFER_AUDIT)
              ? `/products/${activeAgency.travel_agency_id}/${switchParams.use_year}/all/audit`
              : isPermitted(PERM_PRODUCTS_OFFER_PUT)
              ? `/products/audit`
              : '';
            navigate(auditPagePath);
          }
        }
      })
      .catch((ex) => {
        notification.error({
          message: 'Notification',
          description: ex.message,
          placement: 'top',
          duration: 4,
        });
      });
  };

  return (
    <div className='flex justify-end items-center gap-4 h-full'>
      <div className='grow'>
        <h2 className='m-0 leading-tight'>
          {isPermitted(PERM_PRODUCTS_OFFER_AUDIT) ? (
            <VendorSelector
              value={{ label: activeAgency.travel_agency_name, value: activeAgency.travel_agency_id }}
              onChange={handleAgencyChange}
              allowClear={false}
              mode={null}
              className='w-72'
              size='large'
              variant={'borderless'}
            />
          ) : (
            activeAgency.travel_agency_name
          )}
          <Divider type={'vertical'} />
          <Select options={yearOptions} variant={'borderless'} className='w-24' size='large' value={pickYear} onChange={handleYearChange} />
          <Divider type={'vertical'} />
          <AuditStateSelector variant={'borderless'} className='w-32' size='large' value={pickAuditState} onChange={handleAuditStateChange} />
          {/* <Divider type={'vertical'} />
           {(use_year || '').replace('all', '')} */}
        </h2>
      </div>
      {showEditA && (
        <Link className='px-2' to={isPermitted(PERM_PRODUCTS_OFFER_AUDIT) ? `/products/${activeAgency.travel_agency_id}/${pickYear}/${audit_state}/edit` : `/products/edit`}>
          {t('Edit')}
        </Link>
      )}
      {showAuditA && (
        <Link className='px-2' to={isPermitted(PERM_PRODUCTS_OFFER_AUDIT) ? `/products/${activeAgency.travel_agency_id}/${pickYear}/${audit_state}/audit` : `/products/audit`}>
          {t('products:AuditRes')}
        </Link>
      )}
      <RequireAuth subject={PERM_PRODUCTS_OFFER_AUDIT}>
        <Button size='small' type={'primary'} onClick={() => handleAuditItem('2', activeAgency)}>
          {t('products:auditStateAction.Published')}
        </Button>
      </RequireAuth>
      {/* <Button size='small' type={'primary'} ghost onClick={() => handleAuditItem('2', agency)}>
        {t('products:auditStateAction.Approved')}
      </Button> */}
      <RequireAuth subject={PERM_PRODUCTS_OFFER_AUDIT}>
        <Button size='small' type={'primary'} danger ghost onClick={() => handleAuditItem('3', activeAgency)}>
          {t('products:auditStateAction.Rejected')}
        </Button>
      </RequireAuth>
      {/* todo: export, 审核完成之后才能导出 */}
      <RequireAuth subject={PERM_PRODUCTS_OFFER_AUDIT}>
        <Button size='small'>{t('Print')} PDF</Button>
        {/* <PrintContractPDF /> */}
      </RequireAuth>
      {/* 编辑 */}
      <Divider type='vertical' />
      {isEditPage && (
        <RequireAuth subject={PERM_PRODUCTS_OFFER_PUT}>
          <Button size='small' type={'primary'} onClick={props.handleNewProduct}>
            {t('New')}
            {t('products:#')}
          </Button>
        </RequireAuth>
      )}
      {/* {activeAgencyState === 0 && ( */}
        <>
          <RequireAuth subject={PERM_PRODUCTS_OFFER_PUT}>
            <Popconfirm title={t('products:sureSubmitAudit')} onConfirm={handleSubmitForAudit} okText={t('Yes')} placement={'bottomLeft'}>
              <Button size='small' type={'primary'} >
                {t('Submit')}
                {t('Audit')}
              </Button>
            </Popconfirm>
          </RequireAuth>
        </>
      {/* )} */}
    </div>
  );
};
export default Header;
