import React, { useEffect, useState, useRef  } from 'react';
import {
  Card,
  Form,
  Select,
  DatePicker,
  Row,
  Col,
  Button,
  notification,
  // Typography
  Space,
  InputNumber,
} from 'antd';
import TextareaInput from '@/components/form/InputTextArea';
import InputText from '@/components/form/InputText';
import { useRouter } from 'next/navigation';
import { addActiveLeads, checkDuplicateLead, reviveLead } from '../service';
import { getLaunch, getLaunchProjects } from '@/app/launches/service';
import { useAllConfigurations } from '@/hooks/useAllConfigurations';
import { convertToShorthand, formatDate } from '@/utills/helper';
import InputSelect from '@/components/form/InputSelect';
import { useDebouncedCallback } from 'use-debounce';
import {
  leadRemarkValidator,
  leadUserNameValidator,
  userEmailValidator,
  userPhoneNoValidator,
} from '@/utills/validator';
import moment from 'moment';
import { POSSESSION, inquiry_sourceOptions } from '../constant';
import { useLeadTags } from '@/hooks/useLeadTags';
import { useWatch } from 'antd/es/form/Form';
import dayjs from 'dayjs';
import InputPhone from '@/components/form/InputPhone';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@/store/store';
import { fetchFilterLaunchList } from '../slice';
import { useCityProjects, filterProjectOptions } from '@/hooks/useCityProjects';
import { dashboardFilter } from '@/app/dashboard/slice';
import DuplicateLeadModal from './DuplicateLeadModal';
import type { DuplicateCheckResponse } from '../interface';

const { Option } = Select;
interface IAddLeads {
  launchId?: number | string | any
  projectId?: number | string
  onClose?: () => void
  onSuccess?: () => void
}

interface ProjectDropDownI {
  value: number
  label: string
  launch_name: string
  launch_id: string
}
interface ConfigurationOptionsI {
  value: string
  label: string
}

interface TeamSalesI {
  value: string
  label: string
  type: string
}

// The phone widget always carries a country code, even when the number is empty.
// Only return it (e.g. "+91") when digits beyond the country code were actually entered.
const countryCodeIfNumberEntered = (field?: { number?: string; callingCode?: string }): string | undefined => {
  const code = field?.callingCode;
  const number = field?.number;
  if (!code || !number) return undefined;
  const enteredDigits = number.replace(/\D/g, '').length - code.replace(/\D/g, '').length;
  return enteredDigits > 0 ? code : undefined;
};

const AddLead: React.FC<IAddLeads> = ({ launchId: _launchId, onClose, onSuccess }) => {
  const [form] = Form.useForm();
  const { manualOptionsFor: tagOptionsFor, toStored: tagsToStored } = useLeadTags();
  const router = useRouter();
  const dispatch: AppDispatch = useDispatch();
  const [submitionLoading, setSubmitionLoading] = useState(false);
  // const [showAdditionalInput, setShowAdditionalInput] = useState(false);
  const [duplicateResponse, setDuplicateResponse] = useState<DuplicateCheckResponse | null>(null);
  const [isDuplicateModalOpen, setIsDuplicateModalOpen] = useState(false);
  const [isReviving, setIsReviving] = useState(false);
  const [launch, setLaunch] = useState<ProjectDropDownI | null>(null);
  const [launchDetail, setLaunchDetail] = useState<any>();
  const configurationOptions = useAllConfigurations();
  const [projectOptions, setProjectOptions] = useState<ProjectDropDownI[]>([]);
  const [projectPage, setProjectPage] = useState(1);
  const [projectSearch, setProjectSearch] = useState('');
  const [hasMoreProjects, setHasMoreProjects] = useState(true);
  const [isProjectsLoading, setIsProjectsLoading] = useState(false);
  const [totalProjects, setTotalProjects] = useState(0);
  // Watch form fields
  const maxBudget = useWatch('max_budget', form);
  const minBudget = useWatch('min_budget', form);
  const maxValue = 9007199254740991;
  const filterLaunchLList = useSelector((state: RootState) => state?.allLeads?.filterLaunchLList);
  const launchListOptions = filterLaunchLList?.map((project: { launch_id: string; launch_name: string; }) => ({
    value: project.launch_id,
    label: project.launch_name,
  }));
  const prevLaunchRef = useRef<string | null>(null);
  const cityProjects = useCityProjects();
  const cityScopedRef = useRef(cityProjects);
  cityScopedRef.current = cityProjects;
  const isSubmittingRef = useRef(false);
  // City list arrived after a launch was already picked - fill the project dropdown.
  useEffect(() => {
    const launchId = form.getFieldValue('launch_list');
    if (cityProjects.isCityScoped && launchId) handleGetProject(launchId, 1, projectSearch, false);
  }, [cityProjects.options]); // eslint-disable-line react-hooks/exhaustive-deps
  // Fetch projects and set initial form values on component mount
  useEffect(() => {
    // handleGetProject();
    fetchLaunchList();
    form.setFieldValue('inquiry_date', dayjs());
  }, []);

  // Function to fetch launch details
  const handleGetLaunch = (id: number) => {
    getLaunch(id)
      .then((res) => {
        const sales = res.data.launch_sales;
        const launch_sales_Ids: Set<number> = new Set();
        const sales_team: TeamSalesI[] = [];
        sales.map((item: any) => {
          // Inactive/blocked users must not be assignable (a revived lead would become invisible)
          const fieldSalesAssignable = item.field_sales_status !== 'inactive' && !item.field_sales_is_blocked;
          const preSalesAssignable = item.pre_sales_status !== 'inactive' && !item.pre_sales_is_blocked;
          if (fieldSalesAssignable && !launch_sales_Ids.has(item.field_sales_id)) {
            sales_team.push({
              type: 'field-sales',
              value: item.field_sales_id,
              label: `${item.field_sales_name}`,
            });
            launch_sales_Ids.add(item.field_sales_id);
          }
          if (preSalesAssignable && item.pre_sales_id != null && item.pre_sales_id !== 0 &&
            item.pre_sales_name != null && item.pre_sales_name.trim() !== '' &&
            !launch_sales_Ids.has(item.pre_sales_id)) {
            sales_team.push({
              type: 'pre-sales',
              value: item.pre_sales_id,
              label: `${item.pre_sales_name}`,
            });
            launch_sales_Ids.add(item.pre_sales_id);
          }
        });

        setLaunchDetail({ ...res.data, sales_team: sales_team });
      })
      .catch((err) => {
        console.error('Error', err);
        setLaunchDetail(null);
      });
  };

  // Function to fetch projects based on user (Now using getLaunchProjects for specific launch with pagination)
  const handleGetProject = (selectedLaunchId?: string, page: number = 1, search: string = '', append: boolean = false) => {
    if (!selectedLaunchId) {
      setProjectOptions([]);
      setProjectPage(1);
      setHasMoreProjects(false);
      return;
    }

    // Non-super-admin: the city's projects are already loaded once - no per-launch API call.
    if (cityScopedRef.current.isCityScoped) {
      if (append) return;
      const all = cityScopedRef.current.options;
      setProjectOptions(filterProjectOptions(all, search).map((o) => ({ ...o, launch_id: selectedLaunchId })) as any);
      setProjectPage(1);
      setTotalProjects(all.length);
      setHasMoreProjects(false);
      if (prevLaunchRef.current !== selectedLaunchId) {
        form.setFieldsValue({ project_id: null, assigned_user_id: null });
        handleGetLaunch(Number(selectedLaunchId));
      }
      prevLaunchRef.current = selectedLaunchId;
      return;
    }

    setIsProjectsLoading(true);
    getLaunchProjects(selectedLaunchId, { page, pageSize: 10, search })
      .then((res) => {
        const newProjects = res.data?.map((item: any) => ({
          value: item.project_id,
          label: item.project_name,
          launch_id: item.launch_id,
        }));

        if (append) {
          setProjectOptions((prev) => [...prev, ...newProjects]);
        } else {
          setProjectOptions(newProjects);
        }

        setProjectPage(page);
        setTotalProjects(res.meta?.total || 0);
        setHasMoreProjects(res.data?.length === 10);

        if (!append) {
          // If launch actually changed -> reset project & assigned user
          if (prevLaunchRef.current !== selectedLaunchId) {
            form.setFieldsValue({ project_id: null, assigned_user_id: null });
          }
          prevLaunchRef.current = selectedLaunchId;
          handleGetLaunch(Number(selectedLaunchId));
        }
      })
      .catch((error) => {
        notification.error({
          message: 'Error',
          description: error?.response?.data?.message || 'Failed to fetch projects',
        });
      })
      .finally(() => {
        setIsProjectsLoading(false);
      });
  };

  const handleProjectScroll = (event: any) => {
    const { target } = event;
    const isAtBottom = Math.ceil(target.scrollTop + target.offsetHeight) >= target.scrollHeight;

    if (isAtBottom && hasMoreProjects && !isProjectsLoading) {
      const selectedLaunchId = form.getFieldValue('launch_list');
      handleGetProject(selectedLaunchId, projectPage + 1, projectSearch, true);
    }
  };

  const debouncedProjectSearch = useDebouncedCallback((value: string) => {
    setProjectSearch(value);
    const selectedLaunchId = form.getFieldValue('launch_list'); // Fixed field name
    handleGetProject(selectedLaunchId, 1, value, false);
  }, 500);

  // Keep the picked project for the UI title. Configurations are not fetched per project any more -
  // the dropdown always lists every configuration (see useAllConfigurations).
  const handleGetConfig = (value: string | number) => {
    // Do NOT clear assigned_user_id here — assign sales depends only on launch
    const project = projectOptions.find((item) => item.value === value);

    // Keep project info for UI title etc.
    if (project) {
      setLaunch(project);
    } else {
      setLaunch(null);
    }

  };
  // const handleLinkClick = () => {
  //   setShowAdditionalInput(true);
  // };

  // Builds the payload from form data (shared by initial submit and post-duplicate-check)
  const buildPayload = (formData: any) => {
    const assigned_user_role = launchDetail.sales_team.filter(
      (i: TeamSalesI) => i.value == formData.assigned_user_id
    )[0].type;

    const formattedValues: any = {
      meta_data: {},
      source: formData?.source,
      status_id: formData?.status_id,
      launch_id: launch?.launch_id,
      project_id: formData?.project_id,
      inquiry_date: formatDate(new Date(formData?.inquiry_date), 'YYYY-MM-DD'),
      assigned_user_id: formData?.assigned_user_id,
      assigned_user_role,
    };
    formattedValues.meta_data = {
      full_name: formData?.full_name,
      // Numbers are saved without the country code and without "+" (area code + number, digits only);
      // the country code goes in phone_country_code / whatsapp_country_code below
      phone_number: formData?.phone_number?.nationalNumber || undefined,
      whatsApp_number: formData?.whatsApp_number?.nationalNumber || undefined,
      remark: formData?.remark,
      country: formData?.whatsApp_number?.country,
    };
    // Country calling codes (e.g. "+91") go in their own keys; only sent when a number was actually entered
    const phoneCountryCode = countryCodeIfNumberEntered(formData?.phone_number);
    const whatsappCountryCode = countryCodeIfNumberEntered(formData?.whatsApp_number);
    if (phoneCountryCode) formattedValues.meta_data.phone_country_code = phoneCountryCode;
    if (whatsappCountryCode) formattedValues.meta_data.whatsapp_country_code = whatsappCountryCode;
    if (formData?.email) formattedValues.meta_data.email = formData?.email;
    // if (formData?.additional_number) formattedValues.meta_data.additional_number = formData?.additional_number.number;
    // if (formData?.alternate_number) formattedValues.meta_data.alternate_number = formData?.alternate_number.number;
    if (formData?.possession) formattedValues.meta_data.possession = formData?.possession;
    if (formData?.max_budget) formattedValues.meta_data.max_budget = formData?.max_budget;
    if (formData?.min_budget) formattedValues.meta_data.min_budget = formData?.min_budget;
    if (formData?.which_configuration_you_are_looking_for_ && formData?.which_configuration_you_are_looking_for_.length > 0) {
      formattedValues.meta_data.which_configuration_you_are_looking_for_ =
        formData?.which_configuration_you_are_looking_for_.join(', ');
    }
    // Only Super Hot is picked by hand; it is saved as its id (Last 72 Hr and Cross are automatic)
    const pickedTags = tagsToStored(formData?.tag);
    if (pickedTags) formattedValues.meta_data.tag = pickedTags;
    return formattedValues;
  };

  // Submits the lead after all duplicate checks have cleared
  const submitLead = (payload: any) => {
    setSubmitionLoading(true);
    addActiveLeads(payload)
      .then((el: any) => {
        notification.success({
          message: 'Success',
          description: el?.message,
        });
        if (onSuccess) {
          // onSuccess()
          setTimeout(() => {
            window.location.href = '/enquiries?tabkey=fresh_lead';
          }, 1000);
        } else if (onClose) {
        setSubmitionLoading(false);
          
        isSubmittingRef.current = false;
          onClose();
        } else {
          router.push('/enquiries');
        }
      })
      .catch((error: any) => {
        const responseData = error?.response?.data || {};
        const { message } = responseData;
        notification.error({
          message: 'Error',
          description: message,
        });
        isSubmittingRef.current = false;
        setSubmitionLoading(false);
      });
  };

  // Function to handle form submission — runs duplicate check first, then creates lead
  const onFinish = async(formData: any): Promise<void> => {
    if (isSubmittingRef.current) return;
    isSubmittingRef.current = true;

    // The duplicate check needs the full international number (with the country code): the backend compares
    // its last 10 digits with wa_number_normalized, which is built from the country code + number
    const whatsappNumber = formData?.whatsApp_number?.number;
    const selectedLaunchId = form.getFieldValue('launch_list');
    const assignedUserId = form.getFieldValue('assigned_user_id');

    setSubmitionLoading(true);

    try {
      const result: DuplicateCheckResponse = await checkDuplicateLead(whatsappNumber, selectedLaunchId, assignedUserId);

      if (result?.isDuplicate) {
        // Duplicate found — store response, store pending payload, open modal, stop
        setDuplicateResponse(result);
        setIsDuplicateModalOpen(true);
        isSubmittingRef.current = false;
        setSubmitionLoading(false);
        return;
      }
    } catch {
      // If duplicate-check API fails, proceed with lead creation normally
    }

    const payload = buildPayload(formData);
    submitLead(payload);
  };

  // ─── Modal action handlers ────────────────────────────────────────────────

  const handleCloseDuplicateModal = () => {
    setIsDuplicateModalOpen(false);
    setDuplicateResponse(null);
  };

  const handleGoToLead = (leadId: number) => {
    window.open(`/enquiries?id=${leadId}`, '_blank');
  };

  const handleIgnore = () => {
    handleCloseDuplicateModal();
  };

  const handleRevive = async (leadId: number) => {
    setIsReviving(true);
    try {
      // For Scenario 3 (self_different_launch), we pass the launchId and project id also where we want to move the lead TO
      const isSelfDiffLaunch = duplicateResponse?.duplicateType === 'self_different_launch';
      const selectedLaunchId = form.getFieldValue('launch_list');
      const selectedProjectId = form.getFieldValue('project_id');
      const assignedUserId = form.getFieldValue('assigned_user_id');
      const userRemark = form.getFieldValue('remark') || '';

      let pre_sales_id: number | null = null;
      let field_sales_id: number | null = null;

      if (assignedUserId && launchDetail?.sales_team) {
        const assignedUser = launchDetail.sales_team.find((u: any) => u.value == assignedUserId);
        if (!assignedUser) {
          notification.error({
            message: 'Invalid sales person',
            description: 'The selected sales person is not available for this launch. Please select another one.',
          });
          return;
        }
        if (assignedUser?.type === 'pre-sales') {
          pre_sales_id = assignedUserId;
        } else if (assignedUser?.type === 'field-sales') {
          field_sales_id = assignedUserId;
        }
      }

      const result = await reviveLead(
        leadId,
        selectedLaunchId,
        selectedProjectId,
        'creating',
        userRemark,
        pre_sales_id,
        field_sales_id
      );
      if (result?.success) {
        notification.success({
          message: 'Lead Revived',
          description: result?.message || 'Lead has been revived successfully.',
        });

        const isSelfSameLaunch = duplicateResponse?.duplicateType === 'self';

        if (isSelfSameLaunch) {
          // Scenario 1B: Close modal and drawer, refresh list
          handleCloseDuplicateModal();
          if (onSuccess) {
            setTimeout(() => {
              window.location.href = '/enquiries?tabkey=fresh_lead';
            }, 800);
          } else if (onClose) {
            onClose();
          }
        } else {
          // Scenario 2B (team) or 3 (self_diff_launch): open the revived lead in a new tab
          window.open(`/enquiries?id=${leadId}`, '_blank');
          handleCloseDuplicateModal();
        }
      } else {
        notification.error({
          message: 'Error',
          description: result?.message || 'Failed to revive lead.',
        });
      }
    } catch (error: any) {
      const msg = error?.response?.data?.message || 'Failed to revive lead.';
      notification.error({ message: 'Error', description: msg });
    } finally {
      setIsReviving(false);
    }
  };
  const filteredSalesTeam = launchDetail?.sales_team.filter((option: { label: string; value: number }) => option.label !== 'null' && option.value !== 0);
  const resetLaunchList = () => {
    form.resetFields(['launch_list']);
  };
  const fetchLaunchList = (): void => {
    dispatch(fetchFilterLaunchList(dashboardFilter));
  };

  const selectedLaunchList = useWatch('launch_list', form);
  return (
    <div>
      {/* <PageHeader title="Create New Lead" /> */}
      <Form
        name="Customer Information"
        onFinish={onFinish}
        layout="vertical"
        form={form}
        initialValues={{
          inquiry_date: dayjs(),
        }}>
        <Space direction="vertical" className="w-full" size="middle">
          <Card title="Customer Information">
            <Row gutter={16}>
              <Col span={24} md={12}>
                <InputText
                  label="Name"
                  name="full_name"
                  placeholder="Name"
                  rules={[
                    {
                      required: true,
                      validator: leadUserNameValidator(' '),
                    },
                  ]}
                />
              </Col>
              <Col span={24} md={12}>
                <InputText
                  label="Email"
                  name="email"
                  placeholder="Email"
                  rules={[
                    {
                      validator: userEmailValidator(' ', false),
                    },
                  ]}
                />
              </Col>
              <Col span={24} md={12}>
                <InputPhone
                  label="Phone Number"
                  name="phone_number"
                  defaultCountry='in'
                  enableSearch
                  // The country can be chosen from the flag dropdown; the +code in the input can't be edited
                  lockCountryCode
                  rules={[
                    {
                      validator: userPhoneNoValidator('Phone', false),
                    },
                  ]}
                />
              </Col>
              <Col span={24} md={12}>
                <InputPhone
                  label="WhatsApp Number"
                  name="whatsApp_number"
                  defaultCountry='in'
                  enableSearch
                  // The country can be chosen from the flag dropdown; the +code in the input can't be edited
                  lockCountryCode
                  rules={[
                    {
                      required: true,
                      validator: userPhoneNoValidator('WhatsApp'),
                    },
                  ]}
                />
              </Col>
              {/* <Col span={24} md={12}>
                <InputPhone
                  label="Alternate Phone"
                  name="alternate_number"
                  defaultCountry='in'
                  enableSearch
                  rules={[
                    {
                      validator: userPhoneNoValidator('Alternate', false),
                    },
                  ]}
                />
                <Typography.Link onClick={handleLinkClick} style={{ marginTop: '-21px' }}>
                  Click here to add another number
                </Typography.Link>
              </Col>
              {showAdditionalInput && (
                <Col span={24} md={12}>
                  <InputPhone
                    label="Additional Number"
                    name="additional_number"
                    defaultCountry='in'
                    enableSearch
                    rules={[
                      {
                        validator: userPhoneNoValidator('Additional', false),
                      },
                    ]}
                  />
                </Col>
              )} */}
            </Row>
          </Card>
          <Card title={launch?.launch_name ? `Inquiry Detail - ${launch.launch_name}` : 'Inquiry Detail'}>
            <Row gutter={16}>
              <Col span={24} md={12} lg={8} xl={6}>
                <Form.Item
                  label="Inquiry Date"
                  name="inquiry_date"
                  rules={[
                    { required: true, message: 'Please Select an Inquiry Date' },
                  ]}>
                  <DatePicker
                    className="w-full"
                    placeholder="Select Date"
                    format={'DD MMM, YYYY'}
                    disabledDate={(currentDate) => {
                      return (
                        currentDate < moment().subtract(5, 'years') ||
                        currentDate > moment().add(1, 'years')
                      );
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={24} md={12} lg={8} xl={6}>
                <InputSelect
                  isSearchable={true}
                  name="source"
                  options={inquiry_sourceOptions}
                  placeholder="Source"
                  label="Inquiry Source"
                  rules={[{ required: true, message: 'Please Select a Inquiry Source' }]}
                  onClear={() => {
                    form.setFieldValue('source', null);
                  }}
                />
              </Col>
              <Col span={24} md={12} lg={8} xl={6}>
                <InputSelect
                  options={launchListOptions}
                  className="project-list-select"
                  label="Launches"
                  name="launch_list"
                  placeholder="Launch List"
                  isSearchable
                  onSelect={(value) => {
                    form.setFieldsValue({ launch_list: value });
                    handleGetProject(value as string, 1, '', false);
                  }}
                  onClear={() => {
                    resetLaunchList();
                  }}
                />
              </Col>
              <Col span={24} md={12} lg={8} xl={6}>
                <InputSelect
                  isSearchable={true}
                  name="project_id"
                  options={projectOptions}
                  placeholder="Project"
                  label="Project"
                  disabled={!selectedLaunchList}
                  loading={isProjectsLoading}
                  rules={[{ required: true, message: 'Please Select a Project' }]}
                  onSelect={(val) => {
                    handleGetConfig(val);
                  }}
                  onSearch={debouncedProjectSearch}
                  onPopupScroll={handleProjectScroll}
                  filterOption={false}
                  onClear={() => {
                    //Do not reset sales here; configurations no longer depend on the project
                    setLaunch(null);
                  }}
                />
              </Col>
              <Col span={24} md={12} lg={8} xl={6}>
                <InputSelect
                  isSearchable={true}
                  onChange={(value: any) => {
                    form.setFieldsValue({ assigned_user_id: value });
                  }}
                  name="assigned_user_id"
                  label="Assign Sales"
                  placeholder="Assign sales"
                  rules={[{ required: true, message: 'Please Select a Sales' }]}
                  options={filteredSalesTeam}
                />
              </Col>

              <Col span={24} md={12} lg={8} xl={6}>
                <InputSelect
                  name="which_configuration_you_are_looking_for_"
                  label="Config Type"
                  placeholder="Configuration"
                  options={configurationOptions}
                  onSelect={(value) => {
                    form.setFieldsValue({
                      which_configuration_you_are_looking_for_: value,
                    });
                  }}
                  mode="multiple"
                  isSearchable={true}
                />
              </Col>

              <Col span={24} md={12} lg={8} xl={6}>
                <Form.Item label="Possession" name="possession">
                  <Select
                    placeholder="Possession"
                    allowClear={true}
                    showSearch={true}>
                    {POSSESSION?.map((p) => (
                      <Option key={p} value={p}>{p}</Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={24} md={24} lg={24} xl={12}>
                <Space direction="horizontal" size="middle" className="min-max-budget-fields">
                  <Space.Compact>
                    <Form.Item
                      key={'min_budget'}
                      label={'Min Budget'}
                      name={'min_budget'}
                      rules={[{ required: maxBudget, message: 'Please Enter Min Budget' }]}

                    >
                      <InputNumber
                        min={1}
                        precision={2}
                        max={maxBudget}
                        style={{ width: '100%' }}
                        placeholder="Min Budget"
                        addonAfter={convertToShorthand(
                          Number(minBudget) || 0
                        )}
                      // addonBefore={'Min'}
                      />
                    </Form.Item>
                  </Space.Compact>
                  <Space.Compact className="text-to">
                    TO
                  </Space.Compact>
                  <Space.Compact>
                    <Form.Item
                      key={'max_budget'}
                      label={'Max Budget'}
                      name={'max_budget'}
                      rules={[{ required: minBudget, message: 'Please Enter Max Budget' }]}

                    >
                      <InputNumber
                        min={minBudget}
                        precision={2}
                        max={maxValue}
                        style={{ width: '100%' }}
                        placeholder="Max Budget"
                        addonAfter={convertToShorthand(
                          Number(maxBudget) || 0
                        )}
                      />
                    </Form.Item>
                  </Space.Compact>
                </Space>
              </Col>
              <Col span={24} md={12} lg={8} xl={6}>
                <InputSelect
                  name="tag"
                  label="Tag"
                  placeholder="Select Tags"
                  mode="multiple"
                  options={tagOptionsFor()}
                  isSearchable={true}
                  onClear={() => {
                    form.setFieldValue('tag', []);
                  }}
                />
              </Col>
            </Row>
            <TextareaInput
              autoSize={{ minRows: 4, maxRows: 12 }}
              name="remark"
              label="Remark"
              placeholder="Remark"
              rules={[
                {
                  required: true,
                  validator: leadRemarkValidator('Remark'),
                },
              ]}
            />
            <div className="d-flex justify-content-end">
              <Button
                type="default"
                onClick={() => {
                  if (onClose) {
                    onClose();
                  } else {
                    router.push('/enquiries');
                  }
                }}>
                Cancel
              </Button>
              <Button
                className="ml-3"
                type="primary"
                htmlType="submit"
                loading={submitionLoading}>
                Save & Create
              </Button>
            </div>
          </Card>
        </Space>
      </Form>

      {/* Duplicate Lead Modal — shown when Save & Create detects a duplicate */}
      <DuplicateLeadModal
        open={isDuplicateModalOpen}
        duplicateResponse={duplicateResponse}
        onClose={handleCloseDuplicateModal}
        onGoToLead={handleGoToLead}
        onRevive={handleRevive}
        onIgnore={handleIgnore}
        reviving={isReviving}
      />
    </div>
  );
};

export default AddLead;
