import React, { useEffect, useState } from 'react';
import { Modal, Form, Spin, notification } from 'antd';
import { addCustomer, updateCustomer } from '../service';

import type { ModalBoxProps } from '../interface';
import InputText from '../../../components/form/InputText';
import InputSelect from '@/components/form/InputSelect';
const ModalBox: React.FC<ModalBoxProps> = ({ isModalOpen, handleClose, handleOk, data }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const statusOptions = [
    { value: 'active', label: 'Active' },
    { value: 'inactive', label: 'Inactive' },
  ];
  // Explicitly checking if data is defined
  const modalTitle = data === null ? 'Add New Customer' : 'Edit Customer';

  useEffect(() => {
    if (data !== null && data !== undefined) {
      form.setFieldsValue({
        name: data.name,
        email: data.email,
        phone: data.phone,
        status: data.status,
        address: data.address,
      });
    } else {
      form.resetFields();
    }
  }, [data, form]);

  const onFinish = (values: { name: string; email: string; phone: string; address: string; status: boolean; }): void => {
    setLoading(true);
    try {
      if (data !== null) {
        updateCustomer(data.id, {
          name: values.name,
          email: values.email,
          phone: values.phone,
          address: values.address,
          status: values.status,
        })
          .then((response) => {
            const { message } = response.data;
            notification.success({
              message: 'Success',
              description: message,
            });
            form.resetFields();
            handleOk();
          })
          .catch((error) => {
            notification.error({
              message: 'Error',
              description: error?.response?.data?.message,
            });
          });
      } else {
        addCustomer({
          name: values.name,
          email: values.email,
          phone: values.phone,
          address: values.address,
          status: values.status,
        })
          .then((response) => {
            const { message } = response.data;
            notification.success({
              message: 'Success',
              description: message,
            });
            form.resetFields();
            handleOk();
          })
          .catch((error) => {
            notification.error({
              message: 'Error',
              description: error?.response?.data?.message,
            });
          });
      }
    } catch (error) {
      // This catch block will not catch errors from promises
      console.error('Non-promise error:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={modalTitle}
      open={isModalOpen}
      onOk={() => {
        form.submit();
      }}
      okText={data !== null ? 'Update' : 'Save'}
      onCancel={() => {
        form.resetFields();
        handleClose();
      }}
      confirmLoading={loading}
      className="custom-new-modal">
      <Spin spinning={loading}>
        <Form
          form={form}
          onFinish={onFinish}
          colon={false}
          labelAlign="left"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}>
          <InputText
            name="name"
            label="Name"
            placeholder="Name"
            rules={[
              {
                required: true,
                message: 'Please Enter Customer Name',
                whitespace: true,
                transform: (value: any) => value?.trim(),
              },
              {
                min: 2,
                message: 'Minimum 2 Characters Required',
              },
              {
                max: 100,
                message: 'Maximum 100 Characters Allowed',
              },
              {
                pattern: /^[A-Za-z ]*$/,
                message: 'Please Enter Alphabets Only',
              },
              {
                pattern: /^\S/,
                message: 'Leading Blank Space is not Allowed',
              },
            ]}
          />
          <InputText
            name="email"
            label="Email"
            placeholder="Email"
            rules={[
              { required: true, message: 'Please Enter Customer Email' },
              {
                type: 'email',
                message: 'Please Enter a Valid Email',
              },
            ]}
          />
          <InputText
            name="phone"
            label="Phone"
            placeholder="Phone"
            rules={[
              { required: true, message: 'Please Enter Customer Phone Number' },
              {
                pattern: /^[0-9]*$/,
                message: 'Please Enter Numeric Value Only',
              },
              {
                min: 10,
                message: 'Minimum 10 Digits Required',
              },
              {
                max: 10,
                message: 'Maximum 10 Digits Allowed',
              },
            ]}
          />
          <InputText
            name="address"
            label="Address"
            placeholder="Address"
            rules={[
              {
                required: true,
                message: 'Please Enter Customer Address',
                whitespace: true,
                transform: (value: any) => value?.trim(),
              },
              {
                min: 2,
                message: 'Minimum 2 Characters Required',
              },
              {
                max: 100,
                message: 'Maximum 100 Characters Allowed',
              },
              {
                pattern: /^\S/,
                message: 'Leading Blank Space is not Allowed',
              },
            ]}
          />
          <InputSelect
            name="status"
            placeholder="Status"
            label="Status"
            rules={[{ required: true, message: 'Please Select a Status' }]}
            options={statusOptions}
            onSelect={(value) => {
              form.setFieldsValue({ status: value });
            }}
          />
        </Form>
      </Spin>
    </Modal>
  );
};

export default ModalBox;
