'use client';
import React, { useState } from 'react';
import { Button, Modal, notification } from 'antd';
import { PhoneOutlined } from '@ant-design/icons';
import { useSession } from 'next-auth/react';
import { originateCall } from '@/app/manage-sip/service';

export type LeadCallType = 'agent' | 'mobile';

interface CallFailedState {
  visible: boolean;
  message: string;
  phoneNumber: string | null;
}

const CLOSED: CallFailedState = { visible: false, message: '', phoneNumber: null };

const formatNumber = (number: string): 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;
};

/**
 * Starts a call to a lead through the PBX, the same way as the Call buttons on the lead details page.
 * `phoneNumber` is passed exactly as the API returns it (encrypted for sales roles); the backend resolves it.
 * Render `callFailedModal` once in the component that uses the hook: it offers a fallback call to the
 * user's office number when the web agent isn't registered.
 */
export function useLeadCall() {
  const { data: session } = useSession();
  const [callingNumber, setCallingNumber] = useState<string | null>(null);
  const [callFailed, setCallFailed] = useState<CallFailedState>(CLOSED);

  const callLead = (phoneNumber: string | undefined | null, callType: LeadCallType = 'agent'): void => {
    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 userOfficeNumber = session?.user?.webrtc_office_assigned_number || '';
    const userDidNumber = session?.user?.webrtc_did_number || '';
    const userWebrtcUsername = session?.user?.webrtc_username || '';
    const payload =
      callType === 'agent'
        ? {
            call_initiate: 'webcall',
            call_type: 'agent',
            internal_callerid: formatNumber(userOfficeNumber),
            internal_agent: userWebrtcUsername,
            outbound_callerid: formatNumber(userDidNumber),
            outbound_customer_number: phoneNumber,
          }
        : {
            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.',
        });
        setCallFailed(CLOSED);
      })
      .catch((error) => {
        const { message, details } = error?.response?.data || {};
        const detailMsg = details?.message || message || 'Failed to originate call.';
        const text = Array.isArray(detailMsg) ? detailMsg.join(', ') : detailMsg;

        if (details?.error?.code === 'agent_not_registered') {
          setCallFailed({ visible: true, message: text, phoneNumber });
          return;
        }
        notification.error({ message: 'Call Failed', description: text });
      })
      .finally(() => {
        setCallingNumber(null);
      });
  };

  const callFailedModal = (
    <Modal
      title="Call Failed"
      open={callFailed.visible}
      onCancel={() => setCallFailed(CLOSED)}
      footer={[
        <Button key="cancel" onClick={() => setCallFailed(CLOSED)}>
          Cancel
        </Button>,
        <Button
          key="call"
          type="primary"
          icon={<PhoneOutlined />}
          style={{ backgroundColor: '#2e7d32', borderColor: '#2e7d32' }}
          onClick={() => callLead(callFailed.phoneNumber, 'mobile')}>
          Call to Office Assigned Number
        </Button>,
      ]}>
      <p>{callFailed.message}</p>
      <p>Open the App and call again (or) call to office assigned number</p>
    </Modal>
  );

  return { callLead, callingNumber, callFailedModal };
}
