import { t } from '@lingui/macro';
import { Button, DatePicker, Form, Select } from 'antd';
import { SbtPageHeader } from 'components/page-header';
import { ReportOverViewTable } from 'components/report-detail';
import { Dayjs } from 'dayjs';
import { useOverViewReport } from 'queries/report';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { DownloadOutlined } from '@ant-design/icons';
import { downloadDashboardReport } from 'request/report';

export interface ReportFormValues {
  duration: string;
  dateRange: [Dayjs, Dayjs];
  subsidiary: string;
}

const Dashboard = () => {
  const navigate = useNavigate();
  const [duration, setDuration] = useState<string>('30d');
  const [subsidiary, setSubsidiary] = useState<string>('all');
  const [form] = Form.useForm<ReportFormValues>();
  const [pagination, setPagination] = useState({
    page: 1,
    page_size: 10,
  });
  const [fromData, setFormData] = useState<{
    start_date: string;
    end_date: string;
    subsidiary: string;
  }>({
    start_date: '',
    end_date: '',
    subsidiary: '',
  });
  const { isLoading, data } = useOverViewReport({
    start_date: fromData.start_date,
    end_date: fromData.end_date,
    subsidiary: fromData.subsidiary,
    page: pagination.page,
    page_size: 30,
  });
  const get30dDateRangeDayJS = () => {
    const prev = new Date();
    prev.setDate(prev.getDate() - 30);
    const today = new Date();
    return [prev, today];
  };
  const formatDate = (date: Date) => {
    // YYYY-MM-DDTHH:mm:ssZ
    const formated = date.toISOString().split('.')[0] + '+0000';
    console.log('formated >>>', formated);
    return formated;
  }
  const changeView = () => {
    const dateRange = get30dDateRangeDayJS();
    setFormData({
      start_date: formatDate(dateRange[0]),
      end_date: formatDate(dateRange[1]),
      subsidiary: subsidiary,
    });
  };

  const handleDownloadReport = async () => {
    console.log('duration >>>', duration);
    console.log('subsidiary >>>', subsidiary);
    const {file, filename} = await downloadDashboardReport(duration, subsidiary);
    const anchorElement = document.createElement('a');
    anchorElement.href = URL.createObjectURL(file);
    anchorElement.download = filename;

    document.body.appendChild(anchorElement);
    anchorElement.click();

    // Clean up
    document.body.removeChild(anchorElement);
    URL.revokeObjectURL(anchorElement.href);
  };
  return (
    <>
      <SbtPageHeader
        title={t`Dashboard`}
        extra={
          <>
            <Button type='primary' size='large' icon={<DownloadOutlined />}
              onClick={() => handleDownloadReport()}
            >
              {t`Download`}
            </Button>
            <Button type='primary' size='large' onClick={() => navigate('/reports')}>
              {t`Go to Report page`}
            </Button>
          </>
        }
      />
      <Form
        form={form}
        style={{ display: 'flex', flexDirection: 'row', gap: 10 }}
      >
        <Form.Item
          label={t`Duration`}
          rules={[
            {
              required: true,
              message: 'Please select a duration',
            },
          ]}
          required
        >
          <Select
            placeholder='Select a date range'
            style={{ width: 200 }}
            options={[
              { value: '30d', label: 'Last 30 days' },
            ]}
            value={duration}
            onChange={(value) => {
              setDuration(value);
            }}
          />
        </Form.Item>

        <Form.Item
          name='subsidiary'
          label={t`Subsidiary`}
          required
        >
          <Select
            placeholder='Select a subsidiary'
            style={{ width: 200 }}
            options={[
              { value: 'all', label: 'ALL' },
              { value: 'sesp', label: 'SESP' },
              { value: 'seau', label: 'SEAU' },
            ]}
            defaultValue={'all'}
            value={subsidiary}
            onChange={(value) => {
              setSubsidiary(value);
            }}
          />
        </Form.Item>
        <Form.Item>
          <Button type='primary' style={{ height: 38 }}
            onClick={changeView}
          >
            View
          </Button>
        </Form.Item>
      </Form>
      <ReportOverViewTable
        pagination={pagination}
        setPagination={setPagination}
        isLoading={isLoading}
        data={data}
      />
    </>
  );
};

export default Dashboard;
