import React, { useState } from 'react';
import { Modal, Button, Alert, Typography, Space, notification } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { deregisterPhoneNumber } from './service';
import type { WhatsAppPhoneNumber } from './interface';

const { Text } = Typography;

interface DeregisterPhoneNumberModalProps {
  open: boolean;
  record: WhatsAppPhoneNumber | null;
  onCancel: () => void;
  onSuccess: () => void;
}

// What WhatsApp Cloud API "deregister" means. These match the backend's own notes for the endpoint.
const LIMITATIONS = [
  'The number stops working on the WhatsApp Cloud API. No messages can be sent or received with it until it is registered again, which needs a 6-digit PIN.',
  'It is not deleted. The number stays in the WhatsApp business account and its message history is kept. Meta has no API to delete a number, so to remove it completely use WhatsApp Manager.',
  'It cannot be deregistered while it is assigned to a user. Remove it from the employee first, otherwise the request is refused.',
  'The saved PIN is cleared, and the number is marked as not allocated in the CRM.',
  'Meta allows only 10 deregister requests per number every 72 hours.',
];

export default function DeregisterPhoneNumberModal({
  open,
  record,
  onCancel,
  onSuccess,
}: DeregisterPhoneNumberModalProps) {
  const [loading, setLoading] = useState(false);

  const handleConfirm = async () => {
    if (!record?.id || loading) return;
    setLoading(true);
    try {
      const res = await deregisterPhoneNumber(record.id);
      notification.success({
        message: 'Phone number deregistered',
        description:
          res?.data?.message ||
          `${record.display_phone_number} can no longer be used on the WhatsApp Cloud API until it is registered again.`,
      });
      onSuccess();
    } catch (error: any) {
      notification.error({
        message: 'Failed to deregister',
        description:
          error?.response?.data?.message || 'Something went wrong. Please try again.',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      open={open}
      title={
        <Space>
          <ExclamationCircleFilled style={{ color: '#faad14' }} />
          Deregister phone number
        </Space>
      }
      onCancel={loading ? undefined : onCancel}
      maskClosable={!loading}
      closable={!loading}
      destroyOnClose
      width={540}
      footer={[
        <Button key="cancel" onClick={onCancel} disabled={loading}>
          Cancel
        </Button>,
        <Button key="confirm" type="primary" danger loading={loading} onClick={handleConfirm}>
          Yes, deregister
        </Button>,
      ]}>
      <Text style={{ display: 'block', marginBottom: 12 }}>
        You are about to deregister <Text strong>{record?.display_phone_number}</Text>
        {record?.verified_name ? ` (${record.verified_name})` : ''} from the WhatsApp Cloud API.
      </Text>

      <Alert
        type="warning"
        showIcon
        message="Please read before you continue"
        description={
          <ul style={{ margin: 0, paddingLeft: 18 }}>
            {LIMITATIONS.map((item) => (
              <li key={item} style={{ marginBottom: 4 }}>
                {item}
              </li>
            ))}
          </ul>
        }
      />
    </Modal>
  );
}
