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

const { Text } = Typography;

const PIN_LENGTH = 6;

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

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

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

  const handleSubmit = async () => {
    if (!record?.id || loading) return;
    if (pin.length !== PIN_LENGTH) {
      notification.warning({ message: 'Please enter all 6 digits of the PIN.' });
      return;
    }
    setLoading(true);
    try {
      const res = await changePhoneNumberPin({ phone_number_id: record.id, pin });
      notification.success({
        message: 'PIN changed',
        description: res?.data?.message || `PIN for ${record.display_phone_number} has been changed.`,
      });
      onSuccess();
    } catch (error: any) {
      notification.error({
        message: 'Failed to change PIN',
        description: error?.response?.data?.message || 'Something went wrong. Please try again.',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      open={open}
      title="Enter new PIN"
      onCancel={onCancel}
      footer={null}
      destroyOnClose
      maskClosable={!loading}
      width={460}
    >
      <Text type="secondary" style={{ display: 'block', marginBottom: 20 }}>
        Enter a new 6-digit PIN which you'll be asked for when registering your phone number <Text strong>({record?.display_phone_number})</Text> with WhatsApp again.{' '}
      </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}
          >
            Change PIN
          </Button>
        </Space>
      </div>
    </Modal>
  );
}
