import React, { useEffect, useRef, useState } from 'react';
import { Form, Button, Card, notification, Typography, DatePicker, Row, Col } from 'antd';
import { useRouter, useSearchParams } from 'next/navigation';
import InputSelect from '@/components/form/InputSelect';
import { addLeadRequests } from '../service';
import { formatDate } from '@/utills/helper';
import MasterLaunchProjects, {
  type MasterLaunchProjectsProps,
} from '@/components/masterDropdowns/MasterLaunchProjects';
import { getProjectsConfiguration } from '@/app/launches/service';
import InputText from '@/components/form/InputText';
import { useSession } from 'next-auth/react';
import { type RangePickerProps } from 'antd/es/date-picker';
import moment from 'moment';
import MasterCreateLeadRequestLaunchs from '@/components/masterDropdowns/MasterCreateLeadRequestLaunchs';
import { useDispatch, useSelector } from 'react-redux';
import { fetchProject } from '@/app/launches/slice';
import { AppDispatch } from '@/store/store';

const { Title, Link } = Typography;
interface options {
    value: number
    label: string
}
const AddLeadRequests: React.FC<{ id?: string }> = ({ id }) => {
  const [form] = Form.useForm();
  const router = useRouter();
  const queryParams = useSearchParams();
  const dispatch: AppDispatch = useDispatch();
  const [loading, setLoading] = useState<boolean>(false);
  const launchProjects = useRef<MasterLaunchProjectsProps>(null);
  const [configOptions, setConfigOptions] = useState<options[]>([]);
  const { data: session } = useSession();
  const { projects } = useSelector((state: any) => state?.launches);

  useEffect(() => {
    if (id !== null) {
      dispatch(fetchProject({ id: id ?? '' }));
    }
  }, []);
  const user = session?.user;

  const onFinish = (formData: { start_date: string | number | Date; }): void => {
    setLoading(true);
    const formattedValues = {
      ...formData,
      start_date: formatDate(new Date(formData.start_date), 'YYYY-MM-DD'),
      new_project_id: id,
      status: 'pending',
      city_id: user?.cities?.[0]?.city_id,
    };

    addLeadRequests(formattedValues)
      .then((response) => {
        notification.success({
          message: 'Success',
          description: response.message,
        });
        router.back();
        setLoading(false);
      })
      .catch((error) => {
        notification.error({
          message: 'Error',
          description: error.message,
        });
        setLoading(false);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const leadStatus = [
    { value: 1, label: 'All leads except fake & broker' },
    { value: 2, label: 'Visit done but not booked' },
  ];

  const getConfigurations = async(project_id = '') => {
    await getProjectsConfiguration(project_id).then((res) => {
      const mp = res.data.map(
        (item: { configuration_id: number; configuration_name: string }) => ({
          value: item.configuration_id,
          label: item.configuration_name,
        })
      );

      if (projects?.configuration && projects?.configuration?.length > 0) {
        const filteredConfigOptions = mp?.filter((option: { value: string; }) =>
          projects?.configuration.some((conf: { configuration_id: string; }) => conf.configuration_id === option?.value)
        );
        if (filteredConfigOptions?.length === 0) {
          notification.error({
            message: 'Error',
            description: `The matching configuration is not available in the "${projects.name}" Please select other project.`,
          });
          setConfigOptions([]);
        } else {
          setConfigOptions(filteredConfigOptions);
        }
      }
    });
  };
  const disabledDate: RangePickerProps['disabledDate'] = (current) => {
    // Can not select days before today and today
    return current && current < moment().startOf('day');
  };
  return (
    <div>
      <Link
        onClick={() => {
          router.back();
        }}>
                Go back
      </Link>
      <Title level={3}>Generate Lead Request</Title>

      <Card>
        <Title level={4}>Launch - {queryParams.get('launch_name')}</Title>
        <Form
          form={form}
          name="validateOnly"
          layout="vertical"
          autoComplete="off"
          onFinish={onFinish}>
          <Row gutter={16}>
            <Col span={24} md={12}>
              <MasterCreateLeadRequestLaunchs
                exclude={queryParams.get('launch_id') as string}
                name="launch_id"
                label="Select Launch From Which You Need Leads"
                rules={[{ required: true, message: 'Please Select Launch' }]}
                placeholder="Select launch"
                onSelect={(value) => {
                  form.setFieldsValue({
                    launch_id: value,
                  });
                  if (launchProjects.current?.reload) {
                    launchProjects.current?.reload(value);
                    form.setFieldsValue({
                      project_id: undefined,
                      project_configuration_id: undefined,
                    });
                  }
                }}
              />
            </Col>
            <Col span={24} md={12}>
              <MasterLaunchProjects
                ref={launchProjects}
                name="project_id"
                label="Project"
                rules={[{ required: true, message: 'Please Select Project' }]}
                id={15}
                placeholder="Select project"
                onSelect={(value) => {
                  form.setFieldsValue({
                    project_id: value,
                    project_configuration_id: undefined,
                  });
                  getConfigurations(value as string);
                }}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24} md={12}>
              <InputSelect
                options={leadStatus}
                label="Lead Status"
                onSelect={(value) => {
                  form.setFieldsValue({ lead_status_id: value });
                }}
                rules={[{ required: true, message: 'Please Select Lead Status' }]}
                name="lead_status_id"
                placeholder="Select lead status"
              />
            </Col>
            <Col span={24} md={12}>
              <InputSelect
                name="project_configuration_id"
                label="Configuration"
                rules={[{ required: true, message: 'Please Select Configuration' }]}
                placeholder="Select configuration"
                onSelect={(value) => {
                  form.setFieldsValue({
                    project_configuration_id: value,
                  });
                }}
                mode="multiple"
                options={configOptions}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24} md={12}>
              <Form.Item
                key={'date'}
                label={'Start Date To Receive Lead'}
                name={'start_date'}
                rules={[{ required: true, message: 'Please Select Start Date' }]}>
                <DatePicker
                  disabledDate={disabledDate}
                  style={{ width: '100%' }}
                  format={'DD MMM, YYYY'}
                />
              </Form.Item>
            </Col>
            <Col span={24} md={12}>
              <InputText
                placeholder="Enter count"
                name={'lead_count'}
                label={'Lead Count Per Day/Per Team Member'}
                rules={[
                  {
                    required: true,
                    message: 'Please Enter Lead Count',
                  },
                  {
                    validator: async(_, value) => {
                      if (value) {
                        if (!/^\d+$/.test(value)) {
                          return await Promise.reject(
                            new Error('Please Enter Numeric Value Only')
                          );
                        }
                        const numericValue = parseInt(value, 10);
                        if (numericValue <= 0) {
                          return await Promise.reject(
                            new Error(
                              'Please Enter a Numeric Value Greater Than 0'
                            )
                          );
                        }
                        if (value && value.length > 12) {
                          return await Promise.reject(
                            new Error('Maximum 12 Digits Allowed')
                          );
                        }
                      }
                      await Promise.resolve();
                    },
                  },
                ]}
              />
            </Col>
          </Row>
          <Form.Item wrapperCol={{ span: 24 }}>
            <div
              style={{
                display: 'flex',
                justifyContent: 'flex-end',
                marginTop: '20px',
              }}>
              <Button
                type="default"
                onClick={() => {
                  router.back();
                }}>
                                Cancel
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                style={{ marginLeft: '10px' }}>
                                Save
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default AddLeadRequests;
