import React, { useEffect, useState } from 'react';
import { Modal, Form, Spin, notification, Switch } from 'antd';
import { addRole, updateRole } from '../service';
import InputText from '../../../components/form/InputText';
import type { ModalBoxProps, City, AllCurrentRoles, ScopingType } from '../interface';
import { cityDropDownValidator, reportingToValidator } from '@/utills/validator';
import InputSelectAndSearch from '@/components/form/InputSelectAndSearch';
import { transformLabel } from '@/utills/helper';
import { NAME_CONVERSION_METHOD } from '@/utills/constant';
const ModalBox: React.FC<ModalBoxProps> = ({ isModalOpen, handleClose, handleOk, data, cities, allRoles, scopingTypes }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [reportingTo, setReportingTo] = useState<number| string | null>(null);
  const [isManagerRole, setIsManagerRole] = useState(true);

  const scopingTypeOptions = (scopingTypes ?? []).map((item: ScopingType) => ({
    value: item.id,
    label: item.name,
  }));

  const allCitiesOptions = cities?.map((item: City) => ({
    value: item.id,
    label: item.name,
  }));

  const allCurrentOptions = allRoles?.map((item: AllCurrentRoles) => ({
    value: item.id,
    label: item.label,
  }));

  const modalTitle = data !== null ? 'Edit Role' : 'Add New Role';

  useEffect(() => {
    if (data !== null  && data !== undefined) {
      const cityIdsArray = typeof data.city_id === 'string'
      ? data.city_id.split(',').map((id: string) => Number(id))
      : [];

      const managerIdsArray = data.subordinate_role_id ? (typeof data.subordinate_role_id === 'string'
      ? data.subordinate_role_id.split(',').map((id: string) => Number(id))
      : []) : [];

      form.setFieldsValue({
        label: data.label,
        manager_role_id: data.manager_role_id,
        subordinate_role_id: managerIdsArray,
        city_id: cityIdsArray,
        is_manager: data.is_manager,
        can_own_leads: data.can_own_leads,
        scoping_type_id: data.scoping_type_id,
      });
      setReportingTo(data.manager_role_id || null);
      setIsManagerRole(managerIdsArray.length > 0 ? true: false)
    } else {
      form.resetFields();
      setReportingTo(null);
    }
  }, [data]);

  const validateLabel = (_: unknown, value: string): Promise<void> => {
    if (!value || value.trim() === '') {
      return Promise.reject(new Error('Please Enter Role Label'));
    } else if (!/^[A-Za-z ]*$/.test(value)) {
      return Promise.reject(new Error('Please Enter Alphabets Only'));
    } else if (value.trim() !== value || value.includes('  ')) {
      return Promise.reject(new Error('Only Single Spaces Allowed In Between Words'));
    } else if (value.length < 2) {
      return Promise.reject(new Error('Minimum 2 Characters Required'));
    } else if (value.length > 50) {
      return Promise.reject(new Error('Maximum 50 Characters Allowed'));
    } else if (!/^([A-Z][a-z]*)( [A-Z][a-z]*)*$/.test(value)) {
      return Promise.reject(new Error('Each Word Must Start With A Capital Letter'));
    } else {
      return Promise.resolve();
    }
  };

  const onFinish = (values: { name: string; label: string, city_id: [], subordinate_role_id: [] }): void => {
    setLoading(true);
    let updatedValues = { ...values, city_id: values.city_id.join(','), subordinate_role_id: values.subordinate_role_id? values.subordinate_role_id.join(',') : null, name:  transformLabel(values.label, NAME_CONVERSION_METHOD.CONVERT) }

    try {
      if (data !== null) {
        updateRole({ ...updatedValues, id: data?.id }).then((response) => {
          notification.success({
            message: 'Success',
            description: response?.data?.message,
          });
          form.resetFields();
          handleOk();
        }).catch((error) => {
          notification.error({
            message: 'Error',
            description: error?.response?.data?.message,
          });
        });
      } else {
        addRole(updatedValues).then((response) => {
          notification.success({
            message: 'Success',
            description: response?.data?.message,
          });
          form.resetFields();
          handleOk();
        }).catch((error) => {
          notification.error({
            message: 'Error',
            description: error?.response?.data?.message,
          });
        });
      }
    } catch (error) {
      notification.error({
        message: 'Error',
        description: 'There was an error processing your request.',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleReportingToSelect = (value: number | string) => {
    setReportingTo(value);

    const currentSubordinatesRaw = form.getFieldValue('subordinate_role_id');
    const currentSubordinates = Array.isArray(currentSubordinatesRaw)
      ? currentSubordinatesRaw
      : currentSubordinatesRaw !== null && currentSubordinatesRaw !== undefined
        ? [currentSubordinatesRaw]
        : [];

        // Make sure both sides are strings for comparison
        const valueStr = value;
        const cleanedSubordinates = currentSubordinates
        .map(String) // Convert all to strings
        .filter((id) => id !== valueStr);

    if (cleanedSubordinates.length !== currentSubordinates.length) {
      form.setFieldsValue({
        subordinate_role_id: cleanedSubordinates,
      });
    }
  };

  const filteredSubordinatesOptions = allCurrentOptions?.filter(
    (item) => String(item.value) !== String(reportingTo)
  );
  // console.log('filteredSubordinatesOptions', filteredSubordinatesOptions)
  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, validator: userNameValidator('Role') }]}
          /> */}
          <InputText
            name="label"
            label="Label"
            placeholder="Label"
            rules={[{ required: true, validator: validateLabel }]}
          />

          <Form.Item
            label="City *"
            className="label-showing-data-for">

            <InputSelectAndSearch
                mode="multiple"
                label=""
                name="city_id"
                placeholder="City"
                options={allCitiesOptions!}
                style={{ width: '100%' }}
                rules={[{ required: true, validator: cityDropDownValidator }]}
              />
            </Form.Item>

          <Form.Item
            label="Reporting To *"
            className="label-showing-data-for">
            <InputSelectAndSearch
              label=""
              name="manager_role_id"
              placeholder="Reporting To"
              options={allCurrentOptions!}
              style={{ width: '100%' }}
              allowClear
              onSelect={handleReportingToSelect}
              onClear={() => setReportingTo(null)}
              rules={[{ required: true, validator: reportingToValidator }]}
            />
          </Form.Item>

          {isManagerRole && <Form.Item
            label="Manager Of"
            className="label-showing-data-for">

            <InputSelectAndSearch
                mode="multiple"
                label=""
                name="subordinate_role_id"
                placeholder="Manager Of"
                options={filteredSubordinatesOptions!}
                style={{ width: '100%' }}
                rules={[{ required: false }]}
              />
            </Form.Item>}

            <Form.Item
              label="Is Manager"
              name="is_manager"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>

            <Form.Item
              label="Can Own Leads"
              name="can_own_leads"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>

            <Form.Item
              label="Scoping Type *"
              className="label-showing-data-for"
            >
              <InputSelectAndSearch
                label=""
                name="scoping_type_id"
                placeholder="Select Scoping Type"
                options={scopingTypeOptions}
                style={{ width: '100%' }}
                rules={[
                  {
                    required: true,
                    message: 'Please select Scoping Type',
                  },
                ]}
              />
            </Form.Item>

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

export default ModalBox;
