'use client';
import React, { useEffect, useRef, useState } from 'react';
import { useWatch } from 'antd/es/form/Form';
import { Card, Descriptions, Collapse, Button, Form, Row, Col, Typography, DatePicker, InputNumber, Input, Modal, Upload, notification, Drawer } from 'antd';
import { EditOutlined, PlusOutlined, PhoneOutlined, WhatsAppOutlined } from '@ant-design/icons';
import DynamicStatusForm from '../../components/ActionForm';
import { useDispatch, useSelector } from 'react-redux';
import type { AppDispatch, RootState } from '@/store/store';
import { getLeadDetailById, leadsDataUpdate } from '../../slice';
import { convertToShorthand, displayDate, displayTime, getRoleIdMap } from '@/utills/helper';
import { originateCall } from '@/app/manage-sip/service';
import { useRoles } from '@/hooks/useRoles';
import InputText from '@/components/form/InputText';
import { leadRemarkValidator, leadUserNameValidator, userEmailValidator, userPhoneNoValidator } from '@/utills/validator';
import RemarkPanel from '../../components/RemarkPanel';
import { useSession } from 'next-auth/react';
import { DEAD_LEAD_STATUS, LEADS_STATUS, TAB_LABEL_MAP } from '@/utills/constant';
import Link from 'next/link';
import FormattedAmount, { FormattedBudget } from '@/components/amountFormat/AmountFormatter';
import PageLoader from '@/components/pageLoader/page';
import ChatView from '@/app/messages/components/ChatView';
import { fetchRoles } from '@/app/role/slice';
import InputPhone from '@/components/form/InputPhone';
import { AgreementAmountInput } from '../../components/AgreementAmountInput';
import TextareaInput from '@/components/form/InputTextArea';
import moment from 'moment';
import dayjs from 'dayjs';
import { uploadBookingImages, deleteBookingImage, createLeadBooking, updateLeadBooking, cancelLeadBooking } from '../../service';
import { useLeadTags } from '@/hooks/useLeadTags';
import { decryptPhoneNumber } from '@/utills/decryption';
import CallIcon from '@/components/CallIcon';
import { type IBooking } from '../../interface';
import BookingApplicants, { applicantsToFormValues, buildApplicantsPayload, applicantPanelsWithErrors } from '../../components/BookingApplicants';
import LaunchProjectSelect from '../../components/LaunchProjectSelect';
const { Panel } = Collapse;

interface Props {
  params: {
    id: string
  }
  getLeads: () => void
  onClose: () => void
  onSuccess: () => void
}

const LeadDetailsPage: React.FC<Props> = ({ params, getLeads, onClose, onSuccess }) => {
  const [form] = Form.useForm();
  const { labelsOf: tagLabelsOf } = useLeadTags();
  const { data: session } = useSession();
  const dispatch: AppDispatch = useDispatch();
  const [editMode, setEditMode] = useState<boolean>(false);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [collapseActiveKey, setCollapseActiveKey] = useState<string[]>([]);
  const [callingNumber, setCallingNumber] = useState<string | null>(null);
  const [agentNotRegisteredModal, setAgentNotRegisteredModal] = useState<{
    visible: boolean
    message: string
    phoneNumber: string | null
  }>({ visible: false, message: '', phoneNumber: null });
  const { leadDetailById, listLoading } = useSelector((state: RootState) => state.allLeads);
  // Only used by the Additional Number "add another number" flow, which is currently hidden.
  // const [showAdditionalInput, setShowAdditionalInput] = useState<boolean>(false);

  const userRoleName = session?.user?.role?.name;
  const canShowPlainNumber = userRoleName === 'super_admin';
  const canCallNumber = ['team_lead', 'field_sales', 'pre_sales'].includes(userRoleName || '');
  const [decryptedPhoneNumber, setDecryptedPhoneNumber] = useState<string | null>(null);
  const [decryptedWhatsAppNumber, setDecryptedWhatsAppNumber] = useState<string | null>(null);

  // "+61 416198185": the number is saved without its country code, so put the code (e.g. "+61") in front.
  // Older rows may still carry the code inside the number ("+91…"); those are shown as they are.
  const withCountryCode = (code: string | null | undefined, number: string | null | undefined): string | null => {
    if (!number) return null;
    const trimmed = String(number).trim();
    if (!code || trimmed.startsWith('+')) return trimmed;
    return `${code} ${trimmed}`;
  };

  const maskPhoneNumber = (number: string | undefined | null): string => {
    if (!number) return '-';
    return 'XXXXXXXXXX';
  };

  // decrypt the number
  const resolveDisplayNumber = async(value: string | null | undefined): Promise<string | null> => {
    if (!value) return null;
    const parts = value.split(':');
    const isEncryptedFormat = parts.length === 2 && parts.every((part) => /^[0-9a-fA-F]+$/.test(part));
    if (!isEncryptedFormat) {
      return value;
    }
    const decrypted = await decryptPhoneNumber(value);
    return decrypted ?? value;
  };

  // Only super_admin sees the plain phone_number / whatsApp_number, so decrypt/resolve both
  useEffect(() => {
    const encryptedPhoneNumber = leadDetailById?.meta_data?.phone_number;
    const encryptedWhatsAppNumber = leadDetailById?.meta_data?.whatsApp_number;

    if (!canShowPlainNumber) {
      setDecryptedPhoneNumber(null);
      setDecryptedWhatsAppNumber(null);
      return;
    }

    let cancelled = false;
    Promise.all([
      resolveDisplayNumber(encryptedPhoneNumber),
      resolveDisplayNumber(encryptedWhatsAppNumber),
    ])
      .then(([phoneValue, whatsAppValue]) => {
        if (!cancelled) {
          setDecryptedPhoneNumber(phoneValue);
          setDecryptedWhatsAppNumber(whatsAppValue);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setDecryptedPhoneNumber(null);
          setDecryptedWhatsAppNumber(null);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [canShowPlainNumber, leadDetailById?.meta_data?.phone_number, leadDetailById?.meta_data?.whatsApp_number]);

  const handleMakeCall = (phoneNumber: string | undefined | null, callType: string) => {
    if (!phoneNumber) {
      notification.warning({
        message: 'Warning',
        description: 'Phone number is not available.',
      });
      return;
    }
    // No SIP credential (webrtc_credential_id) assigned to this user means no number to call from
    if (!session?.user?.webrtc_username) {
      notification.warning({
        message: 'No number assigned',
        description: 'No number is assigned to you for calling the lead. Please contact admin.',
      });
      return;
    }
    setCallingNumber(phoneNumber);

    const formatNumber = (number: string) => {
      let formattedNumber = (number || '').trim();
      if (formattedNumber.startsWith('+91')) {
        return formattedNumber;
      }
      if (formattedNumber.startsWith('91')) {
        formattedNumber = '+91' + formattedNumber.slice(2);
      } else if (formattedNumber.startsWith('0')) {
        formattedNumber = '+91' + formattedNumber.slice(1);
      }
      return formattedNumber;
    };

    const userOfficeNumber = session?.user?.webrtc_office_assigned_number || '';
    const userDidNumber = session?.user?.webrtc_did_number || '';
    const userWebrtcUsername = session?.user?.webrtc_username || '';
    let payload = {};
    if (callType === "agent") {
      payload = {
        call_initiate: "webcall",
        call_type: 'agent',
        internal_callerid: formatNumber(userOfficeNumber),
        internal_agent: userWebrtcUsername,
        outbound_callerid: formatNumber(userDidNumber),
        outbound_customer_number: phoneNumber,
      };
    }
    if (callType === "mobile") {
      payload = {
        call_initiate: "webcall",
        call_type: 'mobile',
        internal_callerid: formatNumber(userDidNumber),
        internal_agent: formatNumber(userOfficeNumber),
        outbound_callerid: formatNumber(userDidNumber),
        outbound_customer_number: phoneNumber,
      };
    }

    originateCall(payload)
      .then((response) => {
        const { message } = response?.data || {};
        notification.success({
          message: 'Call Initiated',
          description: message || `Call request sent successfully for ${phoneNumber}.`,
        });
        setAgentNotRegisteredModal({ visible: false, message: '', phoneNumber: null })
      })
      .catch((error) => {
        const { message, details } = error?.response?.data || {};
        const detailMsg = details?.message || message || 'Failed to originate call.';

        if (details?.error?.code === 'agent_not_registered') {
          setAgentNotRegisteredModal({
            visible: true,
            message: Array.isArray(detailMsg) ? detailMsg.join(', ') : detailMsg,
            phoneNumber,
          });
          return;
        }

        notification.error({
          message: 'Call Failed',
          description: Array.isArray(detailMsg) ? detailMsg.join(', ') : detailMsg,
        });
      })
      .finally(() => {
        setCallingNumber(null);
      });
  };

  const { roles } = useSelector((state: RootState) => state.roles);
  // Only one booking can be being added/edited at a time page-wide - 'new' means
  // the "Add Another Booking" form, a number means editing that booking's id,
  // null means the accordion is in its plain read-only state.
  const [editingBookingId, setEditingBookingId] = useState<number | 'new' | null>(null);
  const [submittingBooking, setSubmittingBooking] = useState<boolean>(false);
  // Applicant 1 starts expanded; Applicant 2 (optional) starts collapsed.
  const [applicantKeys, setApplicantKeys] = useState<string[]>(['applicant1']);
  const [bookingConfirmVisible, setBookingConfirmVisible] = useState<boolean>(false);
  const [pendingBookingPayload, setPendingBookingPayload] = useState<any>(null);
  const [pendingBookingValues, setPendingBookingValues] = useState<any>(null);
  const [bookingImagePreviewOpen, setBookingImagePreviewOpen] = useState<boolean>(false);
  const [bookingImagePreviewUrl, setBookingImagePreviewUrl] = useState<string>('');
  const [cancellingBooking, setCancellingBooking] = useState<IBooking | null>(null);
  const [cancelBookingRemark, setCancelBookingRemark] = useState<string>('');
  const [cancellingBookingSubmitting, setCancellingBookingSubmitting] = useState<boolean>(false);
  // Raw {key, url, original_name, ...} shape - not persisted to the DB until the booking
  // is actually saved, when it's sent as part of the submit payload (see handleSaveBookingEdit).
  // Shared across whichever single booking is currently being added/edited - reseeded by
  // handleAddBooking / handleBookingEditFor each time the target changes.
  const [bookingImageList, setBookingImageList] = useState<any[]>([]);
  const bookingImageListRef = useRef<any[]>(bookingImageList);
  const persistedBookingImageKeysRef = useRef<Set<string>>(new Set());
  const brokerage = useWatch('brokerage', form);
  const agreement_value = useWatch('agreement_value', form);
  const booking_amount = useWatch('booking_amount', form);
  const passback_amount = useWatch('passback_amount', form);
  const [roleFilters, setRoleFilters] = useState<any>({
    page: 1,
    sortColumn: 'sort_order',
  });
  const maxValue = 9007199254740991;
  const [isChatModalVisible, setIsChatModalVisible] = useState(false);

  useEffect(() => {
    if (roles?.length === 0) {
      dispatch(fetchRoles(roleFilters));
    }
  }, [roles]);
  const [prevState, setPrevState] = useState<boolean>(false);

  const { getRoleByName } = useRoles();
  const allRoles = {
    pre_sales: getRoleByName('pre_sales')?.id,
    field_sales: getRoleByName('field_sales')?.id,
    team_lead: getRoleByName('team_lead')?.id,
  };
  const isRestrictedRole = [allRoles?.pre_sales, allRoles?.field_sales, allRoles?.team_lead].includes(Number(session?.user?.role?.id));
  // Trigger fetching lead details when params.id changes
  useEffect(() => {
    handleLeadDetails({ id: params.id });
  }, [params.id]);

  // Set form fields value when in edit mode and lead details are available
  useEffect(() => {
    if (editMode && leadDetailById?.meta_data) {
      form.setFieldsValue({
        ...leadDetailById.meta_data,
        booked_at: leadDetailById?.meta_data?.booked_at
          ? dayjs(leadDetailById.meta_data.booked_at)
          : null,
      });
    }
  }, [editMode, leadDetailById?.meta_data, form]);

  useEffect(() => {
    form.setFieldsValue({
      ...leadDetailById.meta_data,
      booked_at: leadDetailById?.meta_data?.booked_at
        ? dayjs(leadDetailById.meta_data.booked_at)
        : null,
    });
  }, [prevState]);

  // Function to fetch lead details by ID
  const handleLeadDetails = (params: { id: string }): void => {
    dispatch(getLeadDetailById(params.id));
  };

  // Function to handle customer edit button click
  const handleCustomerEdit = (e: React.MouseEvent<HTMLButtonElement>): void => {
    e.stopPropagation();
    setCollapseActiveKey((i) => [...i, 'leadDetail']);
    setEditMode(true);
  };

  // Function to cancel edit mode
  const handleCancelEdit = () => {
    setEditMode(false);
  };

  // Handle booking edit
  // --- your handlers (you already provided these) ---
  const toNum = (val: any) => (val != null && val !== '' ? Number(val) : null);

    // Drops any images uploaded to storage during this edit session that were never saved,
    // and resets the staged list back to whatever is currently persisted for the target.
    const discardUnsavedBookingImages = (persistedImages: any[]) => {
      bookingImageListRef.current
        .filter((img: any) => !persistedBookingImageKeysRef.current.has(img.key))
        .forEach((img: any) => {
          deleteBookingImage(params.id, img.key).catch(() => {});
        });
      setBookingImageList(persistedImages || []);
    };

    // Project a fresh additional booking starts with: the most recent booking's project
    // (bookings come newest-first), falling back to the lead's own project.
    const defaultNewBookingProjectId = () =>
      (leadDetailById?.bookings || []).find((b: IBooking) => b.project_id)?.project_id ?? leadDetailById?.project_id ?? undefined;

    const seedBookingForm = (booking: Partial<IBooking> | null) => {
      // Clear stale values/errors from a previously opened booking before seeding this one.
      form.resetFields(['project_id', ['applicant1', 'client_name'], ['applicant1', 'client_mobile'], ['applicant1', 'client_email'],
        ['applicant2', 'client_name'], ['applicant2', 'client_mobile'], ['applicant2', 'client_email']]);
      setApplicantKeys(['applicant1']);
      const saved = applicantsToFormValues(booking?.applicants);
      form.setFieldsValue({
        project_id: booking ? (booking.project_id ?? undefined) : defaultNewBookingProjectId(),
        applicant1: { client_name: saved.applicant1?.client_name ?? '', client_mobile: saved.applicant1?.client_mobile ?? '', client_email: saved.applicant1?.client_email ?? '' },
        applicant2: { client_name: saved.applicant2?.client_name ?? '', client_mobile: saved.applicant2?.client_mobile ?? '', client_email: saved.applicant2?.client_email ?? '' },
        booked_at: booking?.booked_at ? dayjs(booking.booked_at) : null,
        booking_amount: toNum(booking?.booking_amount),
        brokerage: toNum(booking?.brokerage),
        agreement_value: toNum(booking?.agreement_value),
        passback_amount: toNum(booking?.passback_amount),
        carpet_area: booking?.carpet_area,
        unit: booking?.unit,
        remark: booking?.remark,
      });
      const images = Array.isArray(booking?.booking_images) ? booking.booking_images : [];
      setBookingImageList(images);
      persistedBookingImageKeysRef.current = new Set(images.map((img: any) => img.key));
    };

    // "Add Another Booking" - only valid once the lead already has at least
    // one active booking (i.e. is already Booking Done).
    const handleAddBooking = () => {
      setCollapseActiveKey((i) => [...i, 'new']);
      setEditingBookingId('new');
      seedBookingForm(null);
    };

    const handleBookingEditFor = (booking: IBooking, e: React.MouseEvent<HTMLElement>) => {
      e.stopPropagation();
      setCollapseActiveKey((i) => [...i, String(booking.id)]);
      setEditingBookingId(booking.id);
      seedBookingForm(booking);
    };

    const handleBookingCancel = () => {
      const target = editingBookingId === 'new'
        ? null
        : (leadDetailById?.bookings || []).find((b: IBooking) => b.id === editingBookingId);
      discardUnsavedBookingImages(target?.booking_images || []);
      setEditingBookingId(null);
    };

    const handleSaveBookingEdit = async() => {
      const values = await form.validateFields();
      if (bookingImageList.length === 0) {
        notification.error({
          message: 'Booking Image Required',
          description: 'Please upload at least one booking image before saving.',
        });
        return;
      }
      const payload = {
        project_id: values?.project_id ?? null,
        applicants: buildApplicantsPayload({ applicant1: values?.applicant1, applicant2: values?.applicant2 }),
        booked_at: values?.booked_at ? dayjs(values.booked_at).format('YYYY-MM-DD HH:mm:ss') : null,
        booking_amount: values?.booking_amount,
        brokerage: values?.brokerage,
        passback_amount: values?.passback_amount,
        agreement_value: values?.agreement_value,
        carpet_area: values?.carpet_area,
        unit: values?.unit,
        remark: values?.remark,
        booking_images: bookingImageList,
      };
      setPendingBookingPayload(payload);
      setPendingBookingValues(values);
      setBookingConfirmVisible(true);
    };

    const handleConfirmBookingSubmit = async() => {
      setSubmittingBooking(true);
      try {
        const res = editingBookingId === 'new'
          ? await createLeadBooking(params.id, pendingBookingPayload)
          : await updateLeadBooking(params.id, editingBookingId as number, pendingBookingPayload);
        if (res.success) {
          // Any previously-persisted image that didn't make it into this save was
          // removed by the user - the DB row no longer references it, so clean up
          // the now-orphaned file in Spaces too.
          const savedKeys = new Set(
            (pendingBookingPayload?.booking_images || []).map((img: any) => img.key)
          );
          persistedBookingImageKeysRef.current.forEach((key) => {
            if (!savedKeys.has(key)) {
              deleteBookingImage(params.id, key).catch(() => {});
            }
          });
          setBookingConfirmVisible(false);
          setEditingBookingId(null);
          handleLeadDetails({ id: params.id });
        }
      } catch (error) {
        console.error('Booking save failed: ', error);
      } finally {
        setSubmittingBooking(false);
      }
    };

    // Cancel one specific booking - the cancellation remark is mandatory.
    const handleCancelBookingConfirm = async() => {
      if (!cancellingBooking) return;
      const remark = cancelBookingRemark.trim();
      if (!remark) {
        notification.error({ message: 'Cancellation remark is required' });
        return;
      }
      setCancellingBookingSubmitting(true);
      try {
        const res = await cancelLeadBooking(params.id, cancellingBooking.id, remark);
        if (res.success) {
          setCancellingBooking(null);
          setCancelBookingRemark('');
          handleLeadDetails({ id: params.id });
        }
      } catch (error) {
        console.error('Booking cancel failed: ', error);
      } finally {
        setCancellingBookingSubmitting(false);
      }
    };

  useEffect(() => {
    bookingImageListRef.current = bookingImageList;
  }, [bookingImageList]);

  const bookingImageFileList = bookingImageList.map((img: any) => ({
    uid: img.key,
    name: img.original_name || img.key,
    status: 'done' as const,
    url: img.url,
  }));

  const handleBookingImageUpload = async({ file, onSuccess, onError }: any) => {
    try {
      const formData = new FormData();
      formData.append('images', file as File);
      const res = await uploadBookingImages(params.id, formData);
      setBookingImageList((prev) => [...prev, ...(res?.data || [])]);
      onSuccess?.(res);
    } catch (error: any) {
      notification.error({
        message: 'Upload Failed',
        description: error?.response?.data?.message || 'Failed to upload booking image',
      });
      onError?.(error);
    }
  };

  const handleBookingImageRemove = async(file: any) => {
    setBookingImageList((prev) => prev.filter((img) => img.key !== file.uid));
    // Already-saved images are just left out of the next save payload; only clean up
    // storage immediately for images uploaded this session that were never persisted.
    if (persistedBookingImageKeysRef.current.has(file.uid)) {
      return;
    }
    try {
      await deleteBookingImage(params.id, file.uid);
    } catch (error: any) {
      notification.error({
        message: 'Delete Failed',
        description: error?.response?.data?.message || 'Failed to delete booking image',
      });
    }
  };

  const handleBookingImagePreview = (file: any) => {
    setBookingImagePreviewUrl(file.url || file.thumbUrl || file.preview);
    setBookingImagePreviewOpen(true);
  };

  const validateBookingImageSize = (file: any) => {
    const isUnderLimit = file.size < 1024 * 1024;
    if (!isUnderLimit) {
      notification.error({
        message: 'Upload Failed',
        description: 'Image must be smaller than 1MB',
      });
      return Upload.LIST_IGNORE;
    }
    return true;
  };

  // Function to save edited lead data
  const handleSaveEdit = async () => {
    const values = await form.validateFields();
    // Alternate Number and Additional Number fields are hidden from the edit form (see JSX
    // below), so they no longer come through `values`. Preserve their existing values from
    // the already-loaded lead instead of sending undefined and wiping them out on save.
    const payload = {
      meta_data: {
        full_name: values?.full_name,
        // whatsApp_number: values?.whatsApp_number?.number ?? values?.whatsApp_number,
        // phone_number: values?.phone_number?.number ?? values?.phone_number, // ?? returns the right-hand value only if the left-hand side is null or undefined

        // number updates were disabled
        // phone_number: leadDetailById?.meta_data?.phone_number,
        // whatsApp_number: leadDetailById?.meta_data?.whatsApp_number,
        // alternate_number: leadDetailById?.meta_data?.alternate_number,
        // additional_number: leadDetailById?.meta_data?.additional_number,
        email: values?.email,
        country: values?.whatsApp_number?.country,
      },
    };
    setSubmitting(true);
    dispatch(leadsDataUpdate({ id: params.id, data: payload }))
      .then((el) => {
        setSubmitting(false);
        handleLeadDetails({ id: params.id });
        if (el?.payload) {
          setEditMode(false);
        }
      })
      .catch((err) => {
        console.error('err: ', err);
        setSubmitting(false);
      });
  };

  // Function to handle additional input link click
  // Commented out along with the Alternate/Additional Number fields it supported (see below).
  // const handleLinkClick = () => {
  //   return;
  //   setShowAdditionalInput(true);
  // };
  const handleNameClick = () => {
    onClose();
  };

  const disabledAfterDate = (current: any) => {
    return current && current.isAfter(moment().endOf('day'));
  };

  // Calculate brokerage amount
  let brokerageAmount = (brokerage / 100) * agreement_value;
  // Check if the result is NaN, if so, fallback to 0
  if (isNaN(brokerageAmount)) {
    brokerageAmount = 0;
  } else {
    // If brokerageAmount is not NaN, round it to 2 decimal places
    brokerageAmount = Number(brokerageAmount.toFixed(2));
  }

  const renderApplicant = (a: { client_name: string, client_mobile: string, client_email: string }) => (
    <div>
      <div>Name: {a.client_name}</div>
      <div>Contact: {a.client_mobile}</div>
      {a.client_email && <div>Email: {a.client_email}</div>}
    </div>
  );

  // Shared add/edit form, reused for whichever single booking is currently
  // targeted by editingBookingId ('new' or a specific booking id) - both the
  // in-place edit panel and the "Add Another Booking" panel render this same
  // JSX, driven by the same form instance and bookingImageList state.
  const bookingEditForm = (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSaveBookingEdit}
      onFinishFailed={({ errorFields }) => {
        const failed = applicantPanelsWithErrors(errorFields as any);
        if (failed.length) setApplicantKeys((prev) => Array.from(new Set([...prev, ...failed])));
      }}>
      <Row gutter={16}>
        {/* Project is optional here; each booking stores its own project_id */}
        <Col span={24} md={12}>
          <LaunchProjectSelect
            launchId={leadDetailById?.launch_id}
            associatedProjects={leadDetailById?.associated_projects}
            extraOptions={(leadDetailById?.bookings || [])
              .filter((b: IBooking) => b.project_id)
              .map((b: IBooking) => ({ value: b.project_id as number, label: b.project_name || String(b.project_id) }))}
          />
        </Col>
        <Col span={24}>
          <BookingApplicants activeKey={applicantKeys} onChange={setApplicantKeys} />
        </Col>
        <Col span={24} md={12}>
          <Form.Item
            key={'booked_at'}
            label={'Booking Date'}
            name={'booked_at'}
            rules={[{ required: true, message: 'Please Select a Booking Date' }]}>
            <DatePicker
              disabledDate={disabledAfterDate}
              className="w-full"
              format="DD MMM, YYYY"
            />
          </Form.Item>
        </Col>

        <Col span={24} md={12}>
          <Form.Item
            key={'booking_amount'}
            label={'Booking Amount'}
            name={'booking_amount'}
            rules={[{ required: true, message: 'Please Enter a Booking Amount' }]}>
            <InputNumber
              min={1}
              precision={2}
              max={maxValue}
              style={{ width: '100%' }}
              placeholder="Booking amount"
              addonAfter={convertToShorthand(Number(booking_amount) || 0)}
            />
          </Form.Item>
        </Col>

        <Col span={24} md={12}>
          <Form.Item
            key={'brokerage'}
            label={'Brokerage %'}
            name={'brokerage'}
            rules={[{ required: true, message: 'Please Enter a Brokerage' }]}>
            <InputNumber
              min={1}
              max={99.99}
              onChange={() => form.validateFields(['passback_amount'])}
              precision={2}
              style={{ width: '100%' }}
              placeholder="Brokerage percentage"
            />
          </Form.Item>
        </Col>

        <Col span={24} md={12}>
          <Form.Item
            key={'passback_amount'}
            label={'Passback Amount'}
            name={'passback_amount'}
            help={`Passback Amount should less then or equal of Brokerage ${brokerageAmount}`}
            rules={[
              {
                type: 'number',
                max: brokerageAmount,
                message: `Passback Amount should less then or equal of Brokerage ${brokerageAmount}`,
              },
            ]}>
            <InputNumber
              disabled={form.getFieldValue('brokerage') < 0 && form.getFieldValue('agreement_value') < 0}
              min={0}
              placeholder="Passback amount"
              max={brokerageAmount}
              precision={2}
              style={{ width: '100%' }}
              addonAfter={convertToShorthand(Number(passback_amount) || 0)}
            />
          </Form.Item>
        </Col>

        <AgreementAmountInput
          maxValue={maxValue}
          agreement_value={agreement_value}
        />

        <Col span={24} md={12}>
          <Form.Item
            key={'carpet_area'}
            label={'Carpet Area'}
            name={'carpet_area'}
            rules={[{ required: true, message: 'Please Enter a Carpet Area' }]}>
            <InputNumber
              min={1}
              max={99999999999}
              style={{ width: '100%' }}
              placeholder="Carpet area"
            />
          </Form.Item>
        </Col>

        <Col span={24} md={12}>
          <Form.Item
            key={'unit'}
            label={'Tower & Flat Number'}
            name={'unit'}
            rules={[
              { required: true, message: 'Please Enter a Unit' },
              {
                pattern: /^[A-Za-z0-9-\s]+$/,
                message: 'Unit can only contain letters, numbers, and hyphens',
              },
            ]}>
            <Input style={{ width: '100%' }} placeholder="Tower & Flat Number" />
          </Form.Item>
        </Col>
        <Col span={24} style={{ marginBottom: 16 }}>
          <Typography.Text strong>Booking Images <span style={{ color: '#ff4d4f' }}>*</span></Typography.Text>
          <div style={{ marginTop: 8 }}>
            <Upload
              listType="picture-card"
              fileList={bookingImageFileList}
              customRequest={handleBookingImageUpload}
              onRemove={handleBookingImageRemove}
              onPreview={handleBookingImagePreview}
              beforeUpload={validateBookingImageSize}
              accept="image/jpeg,image/jpg,image/png,image/webp,image/gif"
              multiple>
              {bookingImageFileList.length >= 5 ? null : (
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>Upload</div>
                </div>
              )}
            </Upload>
          </div>
        </Col>
        <Col span={24}>
          <TextareaInput
            autoSize={{ minRows: 4, maxRows: 12 }}
            name="remark"
            label="Remark"
            placeholder="Remark"
            rules={[
              {
                required: true,
                validator: leadRemarkValidator('Remark'),
              },
            ]}
          />
        </Col>
      </Row>

      <div style={{ textAlign: 'right', marginTop: 24 }}>
        <Button onClick={handleBookingCancel}>Cancel</Button>
        <Button
          loading={submittingBooking}
          key="submit"
          type="primary"
          htmlType="submit"
          style={{ marginLeft: 8 }}>
          Save
        </Button>
      </div>
    </Form>
  );

  return (
    <div>
      {/* <PageHeader title="Lead Detail" /> */}
      {listLoading ? (
        <PageLoader />
      ) : (
        <>
          <Collapse
            expandIconPosition="end"
            className="custom-collapse"
            onChange={(e) => {
              setCollapseActiveKey(e as string[]);
              setPrevState(true);
            }}
            activeKey={collapseActiveKey}>
            <Panel
              header={`${leadDetailById?.meta_data?.full_name}`}
              key="leadDetail"
              className="lead-detail-panel-with-btn"
              extra={
                <div className="lead-action-btns" onClick={(e) => e.stopPropagation()}>
                  {isRestrictedRole && (
                    <>
                      <Button
                        key="whatsapp"
                        type="text"
                        title="WhatsApp"
                        aria-label="WhatsApp"
                        icon={<WhatsAppOutlined style={{ color: '#25D366', fontSize: '22px' }} />}
                        onClick={(e) => {
                          e.stopPropagation();
                          setIsChatModalVisible(true);
                        }}
                        style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                      />
                      {/* Calls the phone number; if the lead has none, the WhatsApp number is used */}
                      <Button
                        key="call"
                        type="text"
                        title="Call"
                        aria-label="Call"
                        icon={<CallIcon />}
                        loading={
                          callingNumber === (leadDetailById?.meta_data?.phone_number || leadDetailById?.meta_data?.whatsApp_number)
                        }
                        onClick={(e) => {
                          e.stopPropagation();
                          handleMakeCall(
                            leadDetailById?.meta_data?.phone_number || leadDetailById?.meta_data?.whatsApp_number,
                            'agent'
                          );
                        }}
                        style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                      />
                    </>
                  )}
                  {!editMode && (
                    <Button
                      key="1"
                      type="primary"
                      icon={<EditOutlined />}
                      onClick={handleCustomerEdit}
                      style={{
                        borderRadius: '6px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      Edit Customer Detail
                    </Button>
                  )}
                </div>
              }>
              {editMode ? (
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={handleSaveEdit}>
                  <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>
                    {/* Alternate Phone Number is hidden for now - not shown in edit mode.
                    <Col span={24} md={12}>
                      <InputPhone
                        label="Phone Number"
                        name="phone_number"
                        defaultCountry='in'
                        enableSearch
                        disabled
                        rules={[
                          {
                            validator: userPhoneNoValidator(' ', false),
                          },
                        ]}
                      />
                    </Col> */}
                    {/* Alternate WhatsApp Number is hidden for now - not shown in edit mode.
                    <Col span={24} md={12}>
                      <InputPhone
                        label="WhatsApp Number"
                        name="whatsApp_number"
                        defaultCountry='in'
                        enableSearch
                        disabled
                        rules={[
                          {
                            required: true,
                            validator: userPhoneNoValidator('WhatsApp'),
                          },
                        ]}
                      />
                    </Col> */}
                    {/* Alternate Phone is hidden for now - not shown in edit mode.
                    <Col span={24} md={12}>
                      <InputPhone
                        label="Alternate Phone"
                        name="alternate_number"
                        defaultCountry='in'
                        enableSearch
                        disabled
                        rules={[
                          {
                            validator: userPhoneNoValidator(' ', false),
                          },
                        ]}
                      />
                      {/* <Typography.Link onClick={handleLinkClick} style={{ marginTop: '-21px' }}>
                          Click here to add another number
                        </Typography.Link> * /}
                    </Col>
                    */}
                    {/* Additional Number is hidden for now - not shown in edit mode.
                    {leadDetailById?.meta_data?.additional_number ? (
                      <Col span={24} md={12}>
                        <InputPhone
                          label="Additional Number"
                          name="additional_number"
                          defaultCountry='in'
                          enableSearch
                          disabled
                          rules={[
                            {
                              validator: userPhoneNoValidator(
                                ' ',
                                false
                              ),
                            },
                          ]}
                        />
                      </Col>
                    ) : (
                      <>
                        {showAdditionalInput && (
                          <Col span={24} md={12}>
                            <InputPhone
                              label="Additional Number"
                              name="additional_number"
                              defaultCountry='in'
                              enableSearch
                              rules={[
                                {
                                  validator: userPhoneNoValidator(
                                    ' ',
                                    false
                                  ),
                                },
                              ]}
                            />
                          </Col>
                        )}
                      </>
                    )}
                    */}
                  </Row>
                  <div style={{ textAlign: 'right', marginTop: 24 }}>
                    <Button key="back" onClick={handleCancelEdit}>
                      Cancel
                    </Button>
                    <Button
                      loading={submitting}
                      key="submit"
                      type="primary"
                      htmlType="submit"
                      style={{ marginLeft: 8 }}>
                      Save
                    </Button>
                  </div>
                </Form>
              ) : (
                <Descriptions
                  column={{ sm: 1, md: 1, lg: 1, xl: 2, xxl: 2 }}
                  className="custom-descriptions label-width"
                  size="small">
                  <Descriptions.Item label="Name">
                    {leadDetailById?.meta_data?.full_name}
                  </Descriptions.Item>
                  <Descriptions.Item label="Email">
                    {leadDetailById?.meta_data?.email}
                  </Descriptions.Item>
                  {/* Team Lead / Field Sales / Pre Sales call from the Call icon in the header, so no number row for them */}
                  {!canCallNumber && (
                    <Descriptions.Item label="Phone Number">
                      {leadDetailById?.meta_data?.phone_number ? (
                        canShowPlainNumber ? (
                          withCountryCode(leadDetailById?.meta_data?.phone_country_code, decryptedPhoneNumber) ?? '-'
                        ) : (
                          maskPhoneNumber(leadDetailById?.meta_data?.phone_number)
                        )
                      ) : (
                        '-'
                      )}
                    </Descriptions.Item>
                  )}
                  {/* Alternate Number is hidden for now - not shown in view mode.
                  <Descriptions.Item label="Alternate Number">
                    {leadDetailById?.meta_data?.alternate_number ? (
                      canCallNumber ? (
                        <Button
                          type="primary"
                          icon={<PhoneOutlined />}
                          loading={callingNumber === leadDetailById?.meta_data?.alternate_number}
                          onClick={() => handleMakeCall(leadDetailById?.meta_data?.alternate_number, "agent")}
                          style={{ backgroundColor: '#2e7d32', borderColor: '#2e7d32' }}>
                          Call ({leadDetailById?.meta_data?.alternate_number})
                        </Button>
                      ) : canShowPlainNumber ? (
                        leadDetailById?.meta_data?.alternate_number
                      ) : (
                        maskPhoneNumber(leadDetailById?.meta_data?.alternate_number)
                      )
                    ) : (
                      '-'
                    )}
                  </Descriptions.Item>
                  */}
                  {!canCallNumber && (
                    <Descriptions.Item label="Whatsapp Number">
                      {leadDetailById?.meta_data?.whatsApp_number ? (
                        canShowPlainNumber ? (
                          withCountryCode(leadDetailById?.meta_data?.whatsapp_country_code, decryptedWhatsAppNumber) ?? '-'
                        ) : (
                          maskPhoneNumber(leadDetailById?.meta_data?.whatsApp_number)
                        )
                      ) : (
                        '-'
                      )}
                    </Descriptions.Item>
                  )}
                  {/* Additional Number is hidden for now - not shown in view mode.
                  {leadDetailById?.meta_data?.additional_number && (
                    <Descriptions.Item label="Additional Number">
                      {canCallNumber ? (
                        <Button
                          type="primary"
                          icon={<PhoneOutlined />}
                          loading={callingNumber === leadDetailById?.meta_data?.additional_number}
                          onClick={() => handleMakeCall(leadDetailById?.meta_data?.additional_number, "agent")}
                          style={{ backgroundColor: '#2e7d32', borderColor: '#2e7d32' }}>
                          Call ({leadDetailById?.meta_data?.additional_number})
                        </Button>
                      ) : canShowPlainNumber ? (
                        leadDetailById?.meta_data?.additional_number
                      ) : (
                        maskPhoneNumber(leadDetailById?.meta_data?.additional_number)
                      )}
                    </Descriptions.Item>
                  )}
                  */}
                  {leadDetailById?.meta_data?.tag && (
                    <Descriptions.Item label="Tag">
                      {tagLabelsOf(leadDetailById?.meta_data?.tag)}
                    </Descriptions.Item>
                  )}
                </Descriptions>
              )}
            </Panel>
            <Panel header="Inquiry Information" key="InquiryDetail">
              <Descriptions
                column={{ sm: 1, md: 1, lg: 1, xl: 2, xxl: 2 }}
                className="custom-descriptions label-width"
                size="small">
                {leadDetailById?.inquiry_date && (
                  <Descriptions.Item label="Inquiry Date">
                    {displayDate(leadDetailById?.inquiry_date)}
                  </Descriptions.Item>
                )}
                {leadDetailById?.source && (
                  <Descriptions.Item label="Source" className="text-capitalize">
                    {leadDetailById?.source}
                  </Descriptions.Item>
                )}
                {leadDetailById?.project_name && (
                  <Descriptions.Item label="Project">
                    {leadDetailById?.project_name}
                  </Descriptions.Item>
                )}
                {leadDetailById?.launch_name && (
                  <Descriptions.Item label="Launch">
                    <Link
                      href={`/launches/view-edit-launch/${leadDetailById.launch_id}`}
                      color="blue"
                      onClick={handleNameClick}>
                      {leadDetailById?.launch_name}
                    </Link>
                  </Descriptions.Item>
                )}
                {leadDetailById?.builder_name && (
                  <Descriptions.Item label="Builder">
                    {leadDetailById?.builder_name}
                  </Descriptions.Item>
                )}
                {leadDetailById?.meta_data
                  ?.which_configuration_you_are_looking_for_ && (
                    <Descriptions.Item label="Config Type">
                      {
                        leadDetailById?.meta_data
                          ?.which_configuration_you_are_looking_for_
                      }
                    </Descriptions.Item>
                  )}
                {leadDetailById?.meta_data?.min_budget && (
                  <Descriptions.Item label="Budget">
                    <FormattedBudget minAmount={leadDetailById?.meta_data
                      ?.min_budget} maxAmount={leadDetailById?.meta_data
                        ?.max_budget} />
                  </Descriptions.Item>
                )}
                {leadDetailById?.meta_data?.possession && (
                  <Descriptions.Item label="Possession">
                    {leadDetailById?.meta_data?.possession}
                  </Descriptions.Item>
                )}
                {leadDetailById?.meta_data?.tag && (
                  <Descriptions.Item label="Tag">
                    {tagLabelsOf(leadDetailById?.meta_data?.tag)}
                  </Descriptions.Item>
                )}
                {/* Applicants of the primary booking only - not every booking's */}
                {leadDetailById?.primary_booking_applicants?.applicant1 && (
                  <Descriptions.Item label="Booking Applicant 1" span={2}>
                    {renderApplicant(leadDetailById.primary_booking_applicants.applicant1)}
                  </Descriptions.Item>
                )}
                {leadDetailById?.primary_booking_applicants?.applicant2 && (
                  <Descriptions.Item label="Booking Applicant 2" span={2}>
                    {renderApplicant(leadDetailById.primary_booking_applicants.applicant2)}
                  </Descriptions.Item>
                )}
              </Descriptions>
            </Panel>
            <Panel header="Lead Information" key="LeadInformation">
              <Descriptions column={1}>
                <Card title="Lead Information">
                  <Descriptions
                    column={{ sm: 1, md: 1, lg: 1, xl: 2, xxl: 2 }}
                    className="custom-descriptions label-width"
                    size="small">
                    {leadDetailById?.meta_data?.pre_sales && (
                      <Descriptions.Item label="Presales User">
                        {leadDetailById?.meta_data?.pre_sales}
                      </Descriptions.Item>
                    )}
                    {leadDetailById?.meta_data?.field_sales && (
                      <Descriptions.Item label="Field Sales User">
                        {leadDetailById?.meta_data?.field_sales}
                      </Descriptions.Item>
                    )}
                    {leadDetailById?.lead_status_name && (
                      <Descriptions.Item label="Status">
                        {leadDetailById?.lead_status_name}
                      </Descriptions.Item>
                    )}
                    {leadDetailById?.stage && (
                      <Descriptions.Item label="Stage">
                        {session?.user.role?.id === allRoles.pre_sales
                          ? leadDetailById?.team_stage
                          : leadDetailById?.stage}
                      </Descriptions.Item>
                    )}
                    {leadDetailById?.meta_data?.follow_up_at && (
                      <Descriptions.Item label="Follow Up Date & Time">
                        {displayDate(
                          leadDetailById?.meta_data?.follow_up_at
                        )}{' '}
                        {displayTime(
                          leadDetailById?.meta_data?.follow_up_at
                        )}
                      </Descriptions.Item>
                    )}

                    {leadDetailById?.meta_data?.scheduled_at && (
                      <Descriptions.Item label="Schedule Date & Time">
                        {displayDate(
                          leadDetailById?.meta_data?.scheduled_at
                        )}{' '}
                        {displayTime(
                          leadDetailById?.meta_data?.scheduled_at
                        )}
                      </Descriptions.Item>
                    )}
                    {leadDetailById?.meta_data?.site_visited_at && (
                      <Descriptions.Item label="Site Visited Date & Time">
                        {displayDate(
                          leadDetailById?.meta_data?.site_visited_at
                        )}{' '}
                        {displayTime(
                          leadDetailById?.meta_data?.site_visited_at
                        )}
                      </Descriptions.Item>
                    )}
                    {leadDetailById?.meta_data?.visited_project && (
                      <Descriptions.Item label="Project Visited">
                        {leadDetailById?.meta_data?.visited_project}
                      </Descriptions.Item>
                    )}
                    {leadDetailById?.meta_data?.creation_date && (
                      <Descriptions.Item label="Creation Date">
                        {leadDetailById?.meta_data?.creation_date}
                      </Descriptions.Item>
                    )}
                  </Descriptions>
                </Card>
              </Descriptions>
            </Panel>
            {leadDetailById?.meta_data?.token_date && (
              <Panel header="Token Information" key="tokenDetail">
                <Descriptions
                  column={{ sm: 1, md: 1, lg: 1, xl: 2, xxl: 2 }}
                  className="custom-descriptions label-width"
                  size="small">
                  {leadDetailById?.meta_data?.token_amount && (
                    <Descriptions.Item label="Token Amount">
                      <FormattedAmount
                        amount={leadDetailById?.meta_data?.token_amount}
                      />
                    </Descriptions.Item>
                  )}
                  {leadDetailById?.meta_data?.token_date && (
                    <Descriptions.Item label="Token Date">
                      {displayDate(leadDetailById?.meta_data?.token_date)}
                    </Descriptions.Item>
                  )}
                  {leadDetailById?.meta_data
                    ?.which_configuration_you_are_looking_for_ && (
                      <Descriptions.Item label="Config Type">
                        {
                          leadDetailById?.meta_data
                            ?.which_configuration_you_are_looking_for_
                        }
                      </Descriptions.Item>
                    )}
                  {leadDetailById?.meta_data?.carpet_area && (
                    <Descriptions.Item label="Carpet Area">
                      {leadDetailById?.meta_data?.carpet_area}
                    </Descriptions.Item>
                  )}
                  {leadDetailById?.meta_data?.unit && (
                    <Descriptions.Item label="Tower & Flat Number">
                      {leadDetailById?.meta_data?.unit}
                    </Descriptions.Item>
                  )}
                  {leadDetailById?.meta_data?.pricing && (
                    <Descriptions.Item label="Pricing">
                      <FormattedAmount
                        amount={leadDetailById?.meta_data?.pricing}
                      />
                    </Descriptions.Item>
                  )}
                </Descriptions>
              </Panel>
            )}
            {Array.isArray(leadDetailById?.bookings) && leadDetailById.bookings.map((booking: IBooking) => (
                  <Panel
                    header={`Booking${booking.is_cancelled ? ' (Cancelled)' : ''} • ${booking.booked_at ? displayDate(booking.booked_at) : '-'}${booking.unit ? ' • ' + booking.unit : ''}`}
                    key={String(booking.id)}
                    extra={editingBookingId === null && [
                      !booking.is_cancelled && (
                        <Button
                          key="editBooking"
                          type="primary"
                          icon={<EditOutlined />}
                          onClick={(e) => handleBookingEditFor(booking, e)}
                          style={{ marginRight: 8 }}
                        >
                          Edit
                        </Button>
                      ),
                      !booking.is_cancelled && (
                        <Button
                          key="cancelBooking"
                          danger
                          onClick={(e) => {
                            e.stopPropagation();
                            setCancellingBooking(booking);
                          }}
                        >
                          Cancel Booking
                        </Button>
                      ),
                    ]}
                  >
                    {editingBookingId === booking.id ? bookingEditForm : (
                  // Read-only view of this specific booking
                  <Descriptions
                              column={{ sm: 1, md: 1, lg: 1, xl: 2, xxl: 2 }}
                              className="custom-descriptions label-width"
                              size="small">
                              {booking.project_name && (
                                <Descriptions.Item label="Project">
                                  {booking.project_name}
                                </Descriptions.Item>
                              )}
                              {booking.applicants?.applicant1 && (
                                <Descriptions.Item label="Applicant 1" span={2}>
                                  {renderApplicant(booking.applicants.applicant1)}
                                </Descriptions.Item>
                              )}
                              {booking.applicants?.applicant2 && (
                                <Descriptions.Item label="Applicant 2" span={2}>
                                  {renderApplicant(booking.applicants.applicant2)}
                                </Descriptions.Item>
                              )}
                              {booking.booked_at && (
                                <Descriptions.Item label="Booking Date">
                                  {displayDate(booking.booked_at)}
                                </Descriptions.Item>
                              )}
                              {booking.booking_amount && (
                                <Descriptions.Item label="Booked Amount">
                                  <FormattedAmount amount={booking.booking_amount} />
                                </Descriptions.Item>
                              )}
                              {booking.brokerage && (
                                <Descriptions.Item label="Brokerage">
                                  {booking.brokerage}%
                                </Descriptions.Item>
                              )}
                              {booking.passback_amount && (
                                <Descriptions.Item label="Passback Amount">
                                  <FormattedAmount amount={booking.passback_amount} />
                                </Descriptions.Item>
                              )}
                              {booking.closing && (
                                <Descriptions.Item label="Closing">
                                  {booking.closing_user} - ({booking.closing_user_role})
                                </Descriptions.Item>
                              )}
                              {booking.agreement_value && (
                                <Descriptions.Item label="Agreement Value">
                                  <FormattedAmount amount={booking.agreement_value} />
                                </Descriptions.Item>
                              )}
                              {booking.which_configuration_you_are_looking_for_ && (
                                <Descriptions.Item label="Config Type">
                                  {booking.which_configuration_you_are_looking_for_}
                                </Descriptions.Item>
                              )}
                              {booking.carpet_area && (
                                <Descriptions.Item label="Carpet Area">
                                  {booking.carpet_area}
                                </Descriptions.Item>
                              )}
                              {booking.unit && (
                                <Descriptions.Item label="Tower & Flat Number">
                                  {booking.unit}
                                </Descriptions.Item>
                              )}
                              {booking.sourcing && (
                                <Descriptions.Item label="Sourcing">
                                  {booking.sourcing}
                                </Descriptions.Item>
                              )}
                              {booking.is_cancelled && booking.cancel_remark && (
                                <Descriptions.Item label="Cancellation Remark" span={2}>
                                  {booking.cancel_remark}
                                </Descriptions.Item>
                              )}
                              {!!(Array.isArray(booking.booking_images) && booking.booking_images.length) && (
                                <Descriptions.Item label="Booking Images" span={2}>
                                  <Upload
                                    listType="picture-card"
                                    fileList={booking.booking_images.map((img) => ({
                                      uid: img.key, name: img.original_name || img.key, status: 'done' as const, url: img.url,
                                    }))}
                                    showUploadList={{ showRemoveIcon: false }}
                                    onPreview={handleBookingImagePreview}
                                  />
                                </Descriptions.Item>
                              )}
                            </Descriptions>
                )}
              </Panel>
            ))}
            {editingBookingId === 'new' && (
              <Panel header="New Booking" key="new">
                {bookingEditForm}
              </Panel>
            )}
            {editingBookingId === null && leadDetailById?.status_id === LEADS_STATUS.bookingDone.id && (
              <div style={{ margin: '8px 0 16px' }}>
                <Button type="dashed" icon={<PlusOutlined />} onClick={handleAddBooking} block>
                  Add Another Booking
                </Button>
              </div>
            )}

            <Panel header="Remark" key="5">
              <RemarkPanel id={params.id} leadDetailById={leadDetailById} />
            </Panel>
          </Collapse>
          {
            (session?.user.role?.id === getRoleByName('pre_sales')?.id &&
                    leadDetailById?.meta_data?.site_visited_at &&
                    leadDetailById?.stage !== TAB_LABEL_MAP.fresh_lead) ? null
              : leadDetailById &&
                      leadDetailById?.id ? (
                  leadDetailById?.status_id !== LEADS_STATUS.bookingCancelled.id ? (
                    leadDetailById?.status_id === LEADS_STATUS.bookingDone.id ? (
                      // Cancellation now happens per-booking via the "Cancel Booking"
                      // button on each panel in the accordion above - no lead-wide
                      // cancel action here once a lead is Booking Done.
                      null
                    ) : (
                      !DEAD_LEAD_STATUS.includes(leadDetailById?.status_id) && (
                        <Card title="Action" className="mt-5">
                          {leadDetailById?.id && (
                            <DynamicStatusForm
                              key={params.id}
                              getLeads={getLeads}
                              id={params.id}
                              data={leadDetailById}
                              getLeadInfo={handleLeadDetails}
                              role_id={session?.user.role?.id}
                              loginUser={session?.user}
                              onClose={onClose}
                              onSuccess={onSuccess}
                            />
                          )}
                        </Card>
                      )
                    )
                  ) : null
                ) : null}
        </>
      )}
      <Modal
        title="Confirm Booking Details"
        open={bookingConfirmVisible}
        onOk={handleConfirmBookingSubmit}
        onCancel={() => setBookingConfirmVisible(false)}
        okText="Confirm & Save"
        cancelText="Go Back"
        confirmLoading={submittingBooking}
      >
        <Descriptions column={1} bordered size="small">
          <Descriptions.Item label="Booking Date">
            {pendingBookingValues?.booked_at ? pendingBookingValues.booked_at.format('DD MMM, YYYY') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="Agreement Value">
            {pendingBookingValues?.agreement_value != null ? (
              <FormattedAmount amount={pendingBookingValues.agreement_value} />
            ) : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="Config">
            {leadDetailById?.meta_data?.which_configuration_you_are_looking_for_ || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="Tower & Flat No.">
            {pendingBookingValues?.unit || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="Booking Amount">
            {pendingBookingValues?.booking_amount != null ? (
              <FormattedAmount amount={pendingBookingValues.booking_amount} />
            ) : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="Brokerage">
            {pendingBookingValues?.brokerage != null ? `${pendingBookingValues.brokerage}%` : '-'}
          </Descriptions.Item>
        </Descriptions>
      </Modal>
      <Drawer
        open={isChatModalVisible}
        onClose={() => setIsChatModalVisible(false)}
        footer={null}
        closable={true}
        title={leadDetailById?.meta_data?.full_name || 'Chat'}
        // The chat view's own header is hidden inside this drawer, so the Call icon goes in the drawer's
        // header, at the right (the close icon stays at the left)
        extra={
          isRestrictedRole && (
            <Button
              type="text"
              title="Call"
              aria-label="Call"
              icon={<CallIcon />}
              loading={
                callingNumber === (leadDetailById?.meta_data?.phone_number || leadDetailById?.meta_data?.whatsApp_number)
              }
              onClick={() =>
                handleMakeCall(
                  leadDetailById?.meta_data?.phone_number || leadDetailById?.meta_data?.whatsApp_number,
                  'agent'
                )
              }
            />
          )
        }
        width={450}
        push={false}
        bodyStyle={{ padding: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}
        className="wa-chat-drawer"
        rootClassName="wa-chat-root-drawer"
      >
        <div className="drawer-chat-wrapper" style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', height: '100%' }}>
          {isChatModalVisible && (
            <ChatView
              leadId={params.id}
              conversationName={leadDetailById?.meta_data?.full_name}
              onCloseMobile={() => setIsChatModalVisible(false)}
            />
          )}
        </div>
      </Drawer>
      <Modal
        open={bookingImagePreviewOpen}
        title="Booking Image"
        footer={null}
        onCancel={() => setBookingImagePreviewOpen(false)}
      >
        <img alt="Booking" style={{ width: '100%' }} src={bookingImagePreviewUrl} />
      </Modal>
      <Modal
        title="Cancel Booking"
        open={!!cancellingBooking}
        onOk={handleCancelBookingConfirm}
        onCancel={() => {
          setCancellingBooking(null);
          setCancelBookingRemark('');
        }}
        okText="Cancel Booking"
        cancelText="Go Back"
        confirmLoading={cancellingBookingSubmitting}
        okButtonProps={{ danger: true, disabled: !cancelBookingRemark.trim() }}
      >
        <p>
          {cancellingBooking?.unit ? `Unit ${cancellingBooking.unit}` : 'This booking'} will be marked cancelled.
        </p>
        <Input.TextArea
          rows={3}
          maxLength={2500}
          placeholder="Cancellation remark (required)"
          value={cancelBookingRemark}
          onChange={(e) => setCancelBookingRemark(e.target.value)}
        />
      </Modal>
      <Modal
        title="Call Failed"
        open={agentNotRegisteredModal.visible}
        onCancel={() => setAgentNotRegisteredModal({ visible: false, message: '', phoneNumber: null })}
        footer={[
          <Button key="cancel" onClick={() => setAgentNotRegisteredModal({ visible: false, message: '', phoneNumber: null })}>
            Cancel
          </Button>,
          // <Button
          //   key="call"
          //   type="primary"
          //   icon={<PhoneOutlined />}
          //   style={{ backgroundColor: '#2e7d32', borderColor: '#2e7d32' }}
          //   onClick={() => handleMakeCall(leadDetailById?.meta_data?.phone_number, "agent")}
          // >
          //   Call on App
          // </Button>,
          <Button
            key="call"
            type="primary"
            icon={<PhoneOutlined />}
            style={{ backgroundColor: '#2e7d32', borderColor: '#2e7d32' }}
            onClick={() => handleMakeCall(leadDetailById?.meta_data?.phone_number, "mobile")}
          >
            Call to Office Assigned Number
          </Button>,
        ]}
      >
        <p>{agentNotRegisteredModal.message}</p>
        <p>Open the App and call again (or) call to office assigned number</p>
      </Modal>
    </div>
  );
};

export default LeadDetailsPage;
