import { createContext, useEffect, useState } from 'react';
import { Table, Form, Modal, Button, InputNumber, Select, DatePicker, Popconfirm } from 'antd';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import BatchImportPrice from './BatchImportPrice';
import { useDatePresets, useWeekdays } from '@/hooks/useDatePresets';

const { RangePicker } = DatePicker;
const ProductInfoQuotation = ({ editable, formInstance, ...props }) => {
  const { t } = useTranslation();
  const presets = useDatePresets();
  const weekdaySets = useWeekdays();
  const [batchImportPriceVisible, setBatchImportPriceVisible] = useState(false);
  const [quotationTableVisible, setQuotationTableVisible] = useState(false);
  const [editIndex, setEditIndex] = useState(null);
  const [quotation, setQuotation] = useState([]);
  const [batchImportData, setBatchImportData] = useState([]);
  const [weekdays, setWeekdays] = useState([]);
  const [selectedDays, setSelectedDays] = useState([]);
  const [currentQuotationRecord, setCurrentQuotationRecord] = useState({
    use_dates_start: null,
    use_dates_end: null,
  });
  const edit = (record, index) => {
    setQuotationTableVisible(true);
    setEditIndex(index);
    setCurrentQuotationRecord(record);
  };
  const handleAdd = () => {
    const newData = {
      adult_cost: 0,
      child_cost: 0,
      currency: '',
      group_size_min: 0,
      group_size_max: 0,
      id: '',
      lastedit_changed: '',
      use_dates_start: '',
      use_dates_end: '',
      weekdays: '',
      tempKey: Math.random(),
    };
    setQuotation([...quotation, newData]);
    const index = [...quotation, newData].length - 1;
    edit(newData, index);
  };
  const handleBatchImportData = (data) => {
    setBatchImportData(data);
  };

  const handleBatchImport = () => {
    setBatchImportPriceVisible(true);
  };
  const handleBatchImportOK = () => {
    const tempBatchImportData = batchImportData.map((item) => {
      const { tag, validPeriod, ...rest } = item;
      return rest;
    });
    const newData = [...quotation, ...tempBatchImportData];
    const sortedData = [...newData].sort((a, b) => {
      if (a.group_size_min !== b.group_size_min) {
        return a.group_size_min - b.group_size_min;
      }

      return a.group_size_max - b.group_size_max;
    });

    setQuotation(sortedData);
    setBatchImportPriceVisible(false);
  };
  const quotationTableVisibleOK = () => {
    currentQuotationRecord.use_dates_start = dayjs(currentQuotationRecord.use_dates_start).format('YYYY-MM-DD');
    currentQuotationRecord.use_dates_end = dayjs(currentQuotationRecord.use_dates_end).format('YYYY-MM-DD');
    const tempQuotation = [...quotation];
    tempQuotation[editIndex] = { ...currentQuotationRecord, weekdays: weekdays };
    const sortedData = [...tempQuotation].sort((a, b) => {
      const aValidPeriod = dayjs(a.use_dates_end).diff(dayjs(a.use_dates_start));
      const bValidPeriod = dayjs(b.use_dates_end).diff(dayjs(b.use_dates_start));

      if (aValidPeriod !== bValidPeriod) {
        return aValidPeriod - bValidPeriod;
      }
      const aGroupSize = a.group_size_max - a.group_size_min;
      const bGroupSize = b.group_size_max - b.group_size_min;

      return aGroupSize - bGroupSize;
    });
    setQuotation(sortedData);
    setQuotationTableVisible(false);
  };
  const quotationTableVisibleCancel = () => {
    setQuotationTableVisible(false);
  };
  const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
  const handleDayClick = (dayOfWeek) => {

    setSelectedDays((prevSelectedDays) => {
      const updatedDays = prevSelectedDays.includes(dayOfWeek) ? prevSelectedDays.filter((d) => d !== dayOfWeek) : [...prevSelectedDays, dayOfWeek];
      const weekdaysString = updatedDays.sort().join(',');
      setWeekdays(weekdaysString);
      return updatedDays;
    });
  };

  const handleDelete = (index) => {
    const newData = [...quotation];
    newData.splice(index, 1);
    const sortedData = [...newData].sort((a, b) => {
      const aValidPeriod = dayjs(a.use_dates_end).diff(dayjs(a.use_dates_start));
      const bValidPeriod = dayjs(b.use_dates_end).diff(dayjs(b.use_dates_start));
      if (aValidPeriod !== bValidPeriod) {
        return aValidPeriod - bValidPeriod;
      }
      const aGroupSize = a.group_size_max - a.group_size_min;
      const bGroupSize = b.group_size_max - b.group_size_min;

      return aGroupSize - bGroupSize;
    });
    setQuotation(sortedData);
  };
  const columns = [
    { title: t('products:adultPrice'), dataIndex: 'adult_cost', width: '4rem' },
    { title: t('products:childrenPrice'), dataIndex: 'child_cost', width: '4rem' },
    { title: t('products:currency'), dataIndex: 'currency', width: '4rem' },
    {
      title: t('products:Types'),
      dataIndex: 'unit',
      width: '4rem',
      render: (text) => (text === '0' ? '每人' : text === '1' ? '每团' : text),
    },
    {
      title: t('products:number'),
      dataIndex: 'group_size',
      width: '4rem',
      render: (_, record) => `${record.group_size_min}-${record.group_size_max}`,
    },

    {
      title: t('products:validityPeriod'),
      dataIndex: 'validityPeriod',
      width: '6rem',
      render: (_, record) => `${record.use_dates_start}-${record.use_dates_end}`,
    },

    { title: t('products:Weekdays'), dataIndex: 'weekdays', width: '4rem' },
    ...(editable
      ? [
          {
            title: t('products:operation'),
            dataIndex: 'operation',
            width: '6rem',
            render: (_, record, index) => {
              const canEdit = true; // record.audit_state_id === -1; // todo:
              return (
                <span>
                  {canEdit ? (
                    <a onClick={() => edit(record, index)} style={{ marginRight: 8 }}>
                      {t('Edit')}
                    </a>
                  ) : (
                    <span style={{ color: 'gray', marginRight: 8 }}>{t('Edit')}</span>
                  )}
                  {canEdit ? (
                    <Popconfirm title={t('sureDelete')} onConfirm={() => handleDelete(index)}>
                      <a>{t('Delete')}</a>
                    </Popconfirm>
                  ) : (
                    <span style={{ color: 'gray' }}>{t('Delete')}</span>
                  )}
                </span>
              );
            },
          },
        ]
      : []),
  ];
  return (
    <>
      <h2>{t('products:EditComponents.Quotation')}</h2>
      <Form.Item name='quotation'>
        <Table
          rowKey={'tempKey'}
          bordered
          dataSource={quotation}
          columns={columns}
          rowClassName='editable-row'
          // pagination={{ onChange: cancel }}
        />
        {
          editable &&
          <Button onClick={handleAdd} type='primary' ghost style={{ marginTop: 16 }}>
            {t('products:addQuotation')}
          </Button>
        }

        {
          editable &&
          <Button onClick={handleBatchImport} type='primary' ghost style={{ marginTop: 16, marginLeft: 16 }}>
            批量添加
          </Button>
        }
      </Form.Item>

      <Modal title='批量设置价格' open={batchImportPriceVisible} onOk={handleBatchImportOK} onCancel={() => setBatchImportPriceVisible(false)} width={'90%'}>
        <BatchImportPrice onBatchImportData={handleBatchImportData} />
      </Modal>

      <Modal title='编辑供应商报价' open={quotationTableVisible} onOk={quotationTableVisibleOK} onCancel={quotationTableVisibleCancel}>
        <h3>成人价</h3>
        <InputNumber value={currentQuotationRecord.adult_cost} onChange={(e) => setCurrentQuotationRecord({ ...currentQuotationRecord, adult_cost: e })} />
        <h3>儿童价</h3>
        <InputNumber value={currentQuotationRecord.child_cost} onChange={(e) => setCurrentQuotationRecord({ ...currentQuotationRecord, child_cost: e })} />
        <h3>币种</h3>
        <Select style={{ width: '30%' }} value={currentQuotationRecord.currency} onChange={(e) => setCurrentQuotationRecord({ ...currentQuotationRecord, currency: e })}>
          <Select.Option value='rmb'>rmb</Select.Option>
          <Select.Option value='usd'>usd</Select.Option>
        </Select>
        <h3>类型</h3>
        <Select style={{ width: '30%' }} value={currentQuotationRecord.unit} onChange={(e) => setCurrentQuotationRecord({ ...currentQuotationRecord, unit: e })}>
          <Select.Option value='0'>每人</Select.Option>
          <Select.Option value='1'>每团</Select.Option>
        </Select>

        <h3>人等</h3>
        <td style={{ display: 'flex', alignItems: 'center' }}>
          <InputNumber
            min={0}
            value={currentQuotationRecord.group_size_min}
            onChange={(e) => setCurrentQuotationRecord({ ...currentQuotationRecord, group_size_min: e })}
            style={{ width: '50%', marginRight: '10px' }}
          />
          <span>-</span>
          <InputNumber
            min={0}
            value={currentQuotationRecord.group_size_max}
            onChange={(e) => setCurrentQuotationRecord({ ...currentQuotationRecord, group_size_max: e })}
            style={{ width: '50%', marginLeft: '10px' }}
          />
        </td>
        <h3>有效期</h3>
        <RangePicker
          allowClear={true}
          inputReadOnly={true}
          presets={presets}
          placeholder={['From', 'Thru']}
          // value={startDate && endDate ? [startDate, endDate] : null}
          onChange={(dates) => {
            setCurrentQuotationRecord({
              ...currentQuotationRecord,
              use_dates_start: dates[0],
              use_dates_end: dates[1],
            });
          }}
        />
        <h3>周末</h3>
        {weekdaySets.map((day, index) => (
          <Button key={day.value} type={selectedDays.includes(day.value) ? 'primary' : 'default'} onClick={() => handleDayClick(day.value)} style={{ margin: '5px' }}>
            {day.label}
          </Button>
        ))}
      </Modal>
    </>
  );
};
export default ProductInfoQuotation;
