import dayjs from 'dayjs';
import { Button, Card, Col, Flex, InputNumber, Modal, Row, Form } from 'antd';
import { Fragment, useEffect, useState } from 'react';
import axios from 'axios';
import { notificationError } from '@pos/base';
import { makeColorTextValue } from '../helpers';

export default function DefaultValue() {
  const [loadingDefault, setLoadingDefault] = useState(false);
  const [loadingActive, setLoadingActive] = useState(false);

  const [loadingSave, setLoadingSave] = useState(false);
  const [defaultPercentage, setDefaultPercentage] = useState<number>();
  const [currentPercentage, setCurrentPercentage] = useState<number>();
  const [errorDefaultPercentage, setErrorDefaultPercentage] = useState<string>();
  const [errorCurrentPercentage, setErrorCurrentPercentage] = useState<string>();

  const [form] = Form.useForm();
  const [openModal, setOpenModal] = useState(false);

  const onCloseModal = async () => {
    await form.resetFields();
    setOpenModal(false);
  };

  const onOpenModal = async () => {
    await form.setFieldsValue({ default_value: defaultPercentage });
    setOpenModal(true);
  };

  const handleSaveData = async () => {
    try {
      const payload = await form.validateFields();
      setLoadingSave(true);
      await axios
        .post('v1/data-scheduling-default', payload)
        .then(async (resp) => {
          const value = resp.data?.data?.default_value;
          await form.setFieldsValue({ default_value: value });
          await handleGetDataActive();
          setDefaultPercentage(value);
          setLoadingSave(false);
          onCloseModal();
        })
        .catch((err) => {
          const message = err.message;
          if (message) notificationError(message);
          setLoadingSave(false);
        });
    } catch (error) {
      console.error(error);
    }
  };

  const handleGetDataActive = async () => {
    setLoadingActive(true);
    await axios
      .get('v1/transaction-setting/detail', { params: { date: dayjs().format('YYYY-MM-DD') } })
      .then((resp) => {
        const value = resp.data?.data?.value;
        form.setFieldsValue({ value: value });
        setCurrentPercentage(value);
        setErrorCurrentPercentage(null as any);
      })
      .catch((err) => {
        const message = err.message;
        setCurrentPercentage(null as any);
        setErrorCurrentPercentage(message);
        if (message) notificationError(message);
      })
      .finally(() => {
        setLoadingActive(false);
      });
  };

  const handleGetDataDefault = async () => {
    setLoadingDefault(true);
    await axios
      .get('v1/data-scheduling-default')
      .then((resp) => {
        const value = resp.data?.data?.default_value;
        form.setFieldsValue({ default_value: value });
        setDefaultPercentage(value);
        setErrorDefaultPercentage(null as any);
      })
      .catch((err) => {
        const message = err.message;
        setDefaultPercentage(null as any);
        setErrorDefaultPercentage(message);
        if (message) notificationError(message);
      })
      .finally(() => {
        setLoadingDefault(false);
      });
  };

  const handleGetData = async () => {
    await Promise.all([handleGetDataDefault(), handleGetDataActive()]);
  };

  useEffect(() => {
    handleGetData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Fragment>
      <Modal
        open={openModal}
        onCancel={onCloseModal}
        onOk={handleSaveData}
        okButtonProps={{ loading: loadingSave }}
        cancelButtonProps={{ disabled: loadingSave }}
        okText="Save"
        title={<div className="text-lg font-bold">DEFAULT PERCENTAGE</div>}
      >
        <Form form={form}>
          <Flex justify="center">
            <Flex align="baseline">
              <Form.Item
                name={'default_value'}
                rules={[
                  { required: true, message: 'Value harus diisi!' },
                  { type: 'number', max: 100, message: 'Value maksimal 100%!' },
                  {
                    validator(_, value) {
                      if (value <= 0) return Promise.reject(new Error('Value harus lebih dari 0!'));
                      return Promise.resolve();
                    },
                  },
                ]}
              >
                <InputNumber style={{ fontSize: 45, width: 120, fontWeight: 'bold' }} />
              </Form.Item>
              <div className="text-[50px] font-extrabold ml-4">{`%`}</div>
            </Flex>
          </Flex>
          <div style={{ fontSize: 11, fontWeight: 400, color: 'rgba(0,0,0,0.4)', fontStyle: 'italic' }}>
            {`*Value akan diterapkan otomatis jika tidak ada pengaturan khusus pada tanggal tersebut.`}
          </div>
        </Form>
      </Modal>
      <Row gutter={[8, 8]}>
        <Col span={12}>
          <Card loading={loadingDefault} styles={{ body: { padding: '6px 12px 6px 12px' } }}>
            <Flex vertical gap={8} justify="space-between">
              <div style={{ fontSize: 12, fontWeight: 600, color: 'rgba(0,0,0,0.4)' }}>DEFAULT PERCENTAGE</div>
              <Flex gap={12}>
                {defaultPercentage ? (
                  <>
                    <div
                      style={{ fontSize: 24, fontWeight: 600 }}
                      className={`${makeColorTextValue(defaultPercentage)}`}
                    >{`${defaultPercentage >= 0 ? `${defaultPercentage} %` : '-'}`}</div>
                    <Button type="link" onClick={onOpenModal}>
                      Edit
                    </Button>
                  </>
                ) : (
                  <div>
                    {errorDefaultPercentage ? (
                      <div className="text-red-500 bg-red-100 p-3" style={{ borderRadius: 6 }}>
                        <div className="italic font-semibold">{`Error:`}</div>
                        <div className="italic">{errorDefaultPercentage}</div>
                      </div>
                    ) : (
                      <div>{`-`}</div>
                    )}
                  </div>
                )}
              </Flex>
              <div style={{ fontSize: 11, fontWeight: 400, color: 'rgba(0,0,0,0.4)', fontStyle: 'italic' }}>
                {`Value otomatis jika tak ada setelan khusus.`}
              </div>
            </Flex>
          </Card>
        </Col>
        <Col span={12}>
          <Card loading={loadingActive} styles={{ body: { padding: '6px 12px 6px 12px' } }}>
            <Flex vertical gap={8} justify="space-between">
              <div style={{ fontSize: 12, fontWeight: 600, color: 'rgba(0,0,0,0.4)' }}>CURRENT PERCENTAGE</div>
              <Flex gap={12}>
                {currentPercentage ? (
                  <>
                    <div
                      style={{ fontSize: 24, fontWeight: 600 }}
                      className={`${makeColorTextValue(currentPercentage)}`}
                    >{`${currentPercentage >= 0 ? `${currentPercentage} %` : '-'}`}</div>
                    <Button type="link" onClick={handleGetDataActive}>
                      Reload
                    </Button>
                  </>
                ) : (
                  <div>
                    {errorCurrentPercentage ? (
                      <div className="text-red-500 bg-red-100 p-3" style={{ borderRadius: 6 }}>
                        <div className="italic font-semibold">{`Error:`}</div>
                        <div className="italic">{errorCurrentPercentage}</div>
                      </div>
                    ) : (
                      <div>{`-`}</div>
                    )}
                  </div>
                )}
              </Flex>
              <div style={{ fontSize: 11, fontWeight: 400, color: 'rgba(0,0,0,0.4)', fontStyle: 'italic' }}>
                {`Value yang di terapkan hari ini ${dayjs().format('DD-MM-YYYY')}.`}
              </div>
            </Flex>
          </Card>
        </Col>
      </Row>
    </Fragment>
  );
}
