import React, { useEffect, useState } from 'react';
import { Modal, Button, Typography, Space, notification } from 'antd';
import { registerPhoneNumber } from './service';
import type { WhatsAppPhoneNumber } from './interface';
import PinBoxes from './PinBoxes';

const { Text } = Typography;

const PIN_LENGTH = 6;

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

export default function GeneratePinModal({
  open,
  record,
  onCancel,
  onSuccess,
}: GeneratePinModalProps) {
  const [pin, setPin] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (open) setPin('');
  }, [open]);

  const handleSubmit = async () => {
    if (!record?.id) return;
    if (pin.length !== PIN_LENGTH) {
      notification.warning({ message: 'Please enter all 6 digits of the PIN.' });
      return;
    }
    setLoading(true);
    try {
      await registerPhoneNumber({ phone_number_id: record.id, pin });
      Modal.success({
        title: 'Phone number registered',
        content: (
          <div>
            <p>
              Two-step verification PIN for {record.display_phone_number} is{' '}
              <Text strong copyable>
                {pin}
              </Text>
              .
            </p>
            <Text type="secondary">
              The PIN is not stored. Save it now, Meta needs it to re-register this number later.
            </Text>
          </div>
        ),
      });
      onSuccess();
    } catch (error: any) {
      notification.error({
        message: 'Failed to generate PIN',
        description: error?.response?.data?.message || 'Something went wrong. Please try again.',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      open={open}
      title="Generate PIN"
      onCancel={onCancel}
      footer={null}
      destroyOnClose
      maskClosable={!loading}
      width={460}
    >
      <Text type="secondary" style={{ display: 'block', marginBottom: 20 }}>
        Set a 6-digit two-step verification PIN to register{' '}
        <Text strong>{record?.display_phone_number}</Text> with WhatsApp.
      </Text>

      <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
        <PinBoxes
          value={pin}
          onChange={setPin}
          onEnter={handleSubmit}
          length={PIN_LENGTH}
          disabled={loading}
        />
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Space>
          <Button onClick={onCancel} disabled={loading}>
            Cancel
          </Button>
          <Button
            type="primary"
            onClick={handleSubmit}
            loading={loading}
            disabled={pin.length !== PIN_LENGTH}
          >
            Register
          </Button>
        </Space>
      </div>
    </Modal>
  );
}
