import React, { useEffect, useState } from 'react';
import { Modal, Form, Spin, notification } from 'antd';
import { addRegion, updateRegion } from '../service';
import type { ModalBoxProps } from '../interface';
import InputText from '../../../components/form/InputText';
import MasterCities from '@/components/masterDropdowns/MasterCities';
import { userNameValidator } from '@/utills/validator';

const ModalBox: React.FC<ModalBoxProps> = ({ isModalOpen, handleClose, handleOk, data }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // Explicitly checking if data is defined
  const modalTitle = data === null ? 'Add New Region' : 'Edit Region';

  useEffect(() => {
    if (data !== null && typeof data === 'object' && 'name' in data && 'status' in data) {
      form.setFieldsValue({
        name: data.name,
        city: data.city_id,
        status: data.status,
      });
    } else {
      form.resetFields();
    }
  }, [data, form]);

  const onFinish = (values: { name: string; city: string; }): void => {
    setLoading(true);

    try {
      if (data !== null) {
        updateRegion(data.id, {
          name: values.name,
          city_id: values.city,
          status: 'active',
        })
          .then((response) => {
            const { message } = response?.data || {};
            notification.success({
              message: 'Success',
              description: message,
            });
            form.resetFields();
            handleOk();
          })
          .catch((error) => {
            const { message } = error?.response?.data || {};
            notification.error({
              message: 'Error',
              description: message,
            });
          });
      } else {
        addRegion({
          name: values.name,
          city_id: values.city,
          status: 'active',
        })
          .then((response) => {
            const { message } = response?.data || {};
            notification.success({
              message: 'Success',
              description: message,
            });

            form.resetFields();
            handleOk();
          })
          .catch((error) => {
            const { message } = error?.response?.data || {};
            notification.error({
              message: 'Error',
              description: message,
            });
          });
      }
    } catch (error) {
      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 }}>
          {
            data?.project_count > 0  &&
                    <p className='mb-3 text-red-400' style={{ lineHeight:'24px' }}>You can't change the status and city because these regions are already associated with {data?.project_count} projects.</p>
          }

          <InputText
            name="name"
            label="Name"
            placeholder="Name"
            rules={[{ required: true, validator: userNameValidator('Region') }]}
          />
          <MasterCities
            name='city'
            label='City'
            rules={[{ required: true, message: 'Please Select a City' }]}
            disabled={data?.project_count ? data?.project_count != 0 : false}
            placeholder="City"
            onSelect={(value) => {
              form.setFieldsValue({ city_id: value });
            }}

          />
        </Form>
      </Spin>
    </Modal>
  );
};

export default ModalBox;
