import React, { useEffect, useRef, useState } from 'react';
import { Form, Input } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import type { RuleObject } from 'rc-field-form/lib/interface';
import PhoneInput from 'antd-phone-input';

import countries from 'i18n-iso-countries';
import enLocale from 'i18n-iso-countries/langs/en.json';
countries.registerLocale(enLocale);

interface InputPhoneProps {
  name: string;
  label: string;
  disabled?: boolean;
  rules?: RuleObject[];
  defaultCountry?: string;
  enableSearch?: boolean;
  // Keep the country code ("+91") at the start of the input from being edited by hand.
  // The country (and with it the code) is still changed with the flag dropdown.
  lockCountryCode?: boolean;
  [key: string]: unknown;
}

// Country search for the flag dropdown. antd-phone-input builds its own search box with an antd option that only
// exists from antd 5.25 (this project has 5.9), so the box never shows here. The library lets us wrap the country
// select instead, so we add the search to it ourselves. Matches the country name, ISO code or dial code.
const matchesCountry = (input: string, option?: any): boolean => {
  const query = input.trim().toLowerCase().replace(/^\+/, '');
  if (!query) return true;
  const key = String(option?.value ?? ''); // library option values are the ISO code + dial code, e.g. "in91"
  const iso = key.slice(0, 2);
  const dial = key.slice(2);
  const name = (countries.getName(iso.toUpperCase(), 'en') || '').toLowerCase();
  return name.includes(query) || iso.startsWith(query) || dial.startsWith(query);
};

// The phone widget shows the number as "+91 9876 543 210": the code is "+" and digits, then a space once
// number digits exist. Returns how many leading characters belong to the code (and the space after it).
const countryCodeLength = (text: string): number => text.match(/^\+\d+\s?/)?.[0].length ?? 0;

// Stops edits from touching the country code at the start of the phone input
const protectCountryCode = (input: HTMLInputElement): (() => void) => {
  const onBeforeInput = (event: InputEvent) => {
    const protectedLength = countryCodeLength(input.value);
    const start = input.selectionStart ?? 0;
    const end = input.selectionEnd ?? 0;

    // Dropping text into the input could land inside the code
    if (event.inputType === 'insertFromDrop') {
      event.preventDefault();
      return;
    }
    // Backspace with the caret at the end of the code would delete part of it
    if (event.inputType === 'deleteContentBackward' && start === end && start <= protectedLength) {
      event.preventDefault();
      // The phone widget remembers "Backspace was pressed" until its next input event; send one so the next
      // keystroke isn't treated as a Backspace (which would move the caret back a position)
      setTimeout(() => input.dispatchEvent(new Event('input', { bubbles: true })), 0);
      return;
    }
    // Any other edit that starts inside the code: keep the code out of the selection so only the number changes
    if (start < protectedLength) {
      input.setSelectionRange(Math.max(start, protectedLength), Math.max(end, protectedLength));
    }
  };

  // A pasted "+91 98765 43210" would otherwise add the code a second time: paste only the number part
  const onPaste = (event: ClipboardEvent) => {
    const text = (event.clipboardData?.getData('text') ?? '').trim();
    const dial = input.value.match(/^\+(\d+)/)?.[1] ?? '';
    if (!dial || !(text.startsWith('+') || text.startsWith('00'))) return;
    const digits = text.replace(/\D/g, '').replace(/^00/, '');
    if (!digits.startsWith(dial)) return;
    event.preventDefault();
    const protectedLength = countryCodeLength(input.value);
    input.setSelectionRange(
      Math.max(input.selectionStart ?? 0, protectedLength),
      Math.max(input.selectionEnd ?? 0, protectedLength)
    );
    document.execCommand('insertText', false, digits.slice(dial.length));
  };

  input.addEventListener('beforeinput', onBeforeInput);
  input.addEventListener('paste', onPaste);
  return () => {
    input.removeEventListener('beforeinput', onBeforeInput);
    input.removeEventListener('paste', onPaste);
  };
};

const InputPhone: React.FC<InputPhoneProps> = ({
  name,
  label,
  disabled = false,
  rules = [],
  defaultCountry = 'in',
  enableSearch = false,
  lockCountryCode = false,
  ...restProps
}) => {
  const phoneRef = useRef<any>(null);
  const countrySearchRef = useRef<any>(null);
  const [countryQuery, setCountryQuery] = useState('');

  // Wraps the library's country select: adds a search box at the top of its dropdown and filters the options
  const withCountrySearch = (node: React.ReactNode): React.ReactNode => {
    if (!enableSearch || !React.isValidElement(node)) return node;
    return React.cloneElement(node as React.ReactElement<any>, {
      className: 'phone-country-select',
      showSearch: true,
      searchValue: countryQuery,
      onSearch: setCountryQuery,
      filterOption: matchesCountry,
      onDropdownVisibleChange: (open: boolean) => {
        if (open) setTimeout(() => countrySearchRef.current?.focus(), 100);
        else setCountryQuery('');
      },
      dropdownRender: (menu: React.ReactNode) => (
        <div>
          <div style={{ padding: 8 }}>
            <Input
              ref={countrySearchRef}
              prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
              placeholder="Search country or code"
              allowClear
              value={countryQuery}
              onChange={(e) => setCountryQuery(e.target.value)}
              // keep the select from treating typed keys (space, arrows) as option shortcuts
              onKeyDown={(e) => e.stopPropagation()}
            />
          </div>
          {menu}
        </div>
      ),
    });
  };

  useEffect(() => {
    if (!lockCountryCode) return;
    const input: HTMLInputElement | null | undefined = phoneRef.current?.input;
    if (!input) return;
    return protectCountryCode(input);
  }, [lockCountryCode]);

  // returns the full international number, the country name, the country calling code (e.g. "+91") and the
  // national number: area code + number as digits only, with no country code and no "+"
  const formatPhoneValue = (
    value: any
  ): { number: string; country: string; callingCode: string; nationalNumber: string } => {
    if (!value) return { number: '', country: '', callingCode: '', nationalNumber: '' };
    const { countryCode, areaCode, phoneNumber, isoCode } = value;
    // build full number string
    const fullNumber = areaCode ? `+${countryCode}${areaCode}${phoneNumber}` : `+${countryCode}${phoneNumber}`;
    // lookup country name via i18n-iso-countries
    const countryName = isoCode ? countries.getName(isoCode.toUpperCase(), 'en') || '' : '';
    const nationalNumber = `${areaCode ?? ''}${phoneNumber ?? ''}`.replace(/\D/g, '');
    // Not named "countryCode": the phone widget reads that key from the stored value itself
    return {
      number: fullNumber,
      country: countryName,
      callingCode: countryCode ? `+${countryCode}` : '',
      nationalNumber,
    };
  };

  return (
    <Form.Item
      label={label}
      name={name}
      rules={rules}
      getValueFromEvent={(value) => formatPhoneValue(value)}
    >
      <PhoneInput
        ref={phoneRef}
        disabled={disabled}
        country={defaultCountry}
        // the library's own search box doesn't render on this antd version; see withCountrySearch
        enableSearch={false}
        dropdownRender={withCountrySearch}
        enableArrow
        disableParentheses
        {...restProps}
      />
    </Form.Item>
  );
};

export default InputPhone;
