<template>
  <div class="phone-input-wrapper" :class="{ 'phone-input-wrapper--mobile': mobileDetection.isMobile }">
    <v-text-field
      v-model="localNumber"
      :label="label"
      :placeholder="placeholder"
      :error="error"
      :error-messages="errorMessage"
      :hint="helpText"
      :persistent-hint="!!helpText"
      :required="required"
      :disabled="disabled"
      variant="outlined"
      :density="mobileDetection.isMobile ? 'default' : 'comfortable'"
      class="phone-text-field"
      @input="handleInput"
      @blur="handleBlur"
    >
      <template #prepend-inner>
        <!-- Country Selector -->
        <v-menu
          v-model="dropdownOpen"
          :close-on-content-click="false"
          location="bottom start"
          :offset="4"
          :min-width="mobileDetection.isMobile ? '90vw' : '280'"
          :transition="mobileDetection.isMobile ? 'none' : 'fade-transition'"
          :no-click-animation="true"
          :persistent="mobileDetection.isMobile"
          :attach="false"
        >
          <template #activator="{ props: menuProps }">
            <div
              v-bind="menuProps"
              class="country-selector"
              :class="{ 
                'country-selector--open': dropdownOpen,
                'country-selector--mobile': mobileDetection.isMobile
              }"
            >
              <img
                :src="flagUrl"
                :alt="`${selectedCountry.name} flag`"
                class="country-flag"
                @error="handleFlagError"
              />
              <span class="country-code">{{ selectedCountry.dialCode }}</span>
              <v-icon
                :size="mobileDetection.isMobile ? 18 : 16"
                class="dropdown-icon"
                :class="{ 'dropdown-icon--rotated': dropdownOpen }"
              >
                mdi-chevron-down
              </v-icon>
            </div>
          </template>

          <!-- Dropdown Content -->
          <v-card 
            class="country-dropdown" 
            :class="{ 'country-dropdown--mobile': mobileDetection.isMobile }"
            :elevation="mobileDetection.isMobile ? 24 : 8"
          >
            <!-- Mobile Header -->
            <div v-if="mobileDetection.isMobile" class="mobile-header">
              <h3 class="mobile-title">Select Country</h3>
              <v-btn
                icon="mdi-close"
                variant="text"
                size="small"
                @click="closeDropdown"
                class="close-btn"
              />
            </div>

            <!-- Search Bar -->
            <div class="search-container">
              <v-text-field
                v-model="searchQuery"
                placeholder="Search countries..."
                variant="outlined"
                :density="mobileDetection.isMobile ? 'default' : 'compact'"
                prepend-inner-icon="mdi-magnify"
                hide-details
                class="search-input"
                :autofocus="!mobileDetection.isMobile"
                clearable
              />
            </div>

            <!-- Country List -->
            <v-list 
              class="country-list" 
              :class="{ 'country-list--mobile': mobileDetection.isMobile }"
              :density="mobileDetection.isMobile ? 'default' : 'compact'"
            >
              <v-list-item
                v-for="country in filteredCountries"
                :key="country.iso2"
                :class="{
                  'country-item': true,
                  'country-item--selected': country.iso2 === selectedCountry.iso2,
                  'country-item--preferred': isPreferredCountry(country.iso2),
                  'country-item--mobile': mobileDetection.isMobile
                }"
                @click="selectCountry(country)"
                :ripple="mobileDetection.isMobile"
              >
                <template #prepend>
                  <img
                    :src="getCountryFlagUrl(country.iso2)"
                    :alt="`${country.name} flag`"
                    class="list-flag"
                    :class="{ 'list-flag--mobile': mobileDetection.isMobile }"
                    @error="handleFlagError"
                  />
                </template>

                <v-list-item-title 
                  class="country-name"
                  :class="{ 'country-name--mobile': mobileDetection.isMobile }"
                >
                  {{ country.name }}
                </v-list-item-title>

                <template #append>
                  <span 
                    class="dial-code"
                    :class="{ 'dial-code--mobile': mobileDetection.isMobile }"
                  >
                    {{ country.dialCode }}
                  </span>
                </template>
              </v-list-item>
            </v-list>

            <!-- Mobile Footer -->
            <div v-if="mobileDetection.isMobile" class="mobile-footer">
              <v-btn
                block
                variant="text"
                @click="closeDropdown"
                class="cancel-btn"
              >
                Cancel
              </v-btn>
            </div>
          </v-card>
        </v-menu>
      </template>
    </v-text-field>
  </div>
</template>

<script setup lang="ts">
import { parsePhoneNumber, AsYouType } from 'libphonenumber-js';
import { getPhoneCountriesWithPreferred, searchPhoneCountries, getPhoneCountryByCode, type PhoneCountry } from '~/utils/phone-countries';
import { useMobileDetection } from '~/composables/useMobileDetection';

interface Props {
  modelValue?: string;
  label?: string;
  placeholder?: string;
  error?: boolean;
  errorMessage?: string;
  helpText?: string;
  required?: boolean;
  disabled?: boolean;
  defaultCountry?: string;
  preferredCountries?: string[];
}

interface Emits {
  (e: 'update:modelValue', value: string): void;
  (e: 'country-changed', country: PhoneCountry): void;
  (e: 'phone-data', data: { number: string; isValid: boolean; country: PhoneCountry }): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: 'Phone number',
  error: false,
  required: false,
  disabled: false,
  defaultCountry: 'MC',
  preferredCountries: () => ['MC', 'FR', 'US', 'IT', 'CH']
});

const emit = defineEmits<Emits>();

// Use unified mobile detection
const mobileDetection = useMobileDetection();

// Get comprehensive countries list
const countries = getPhoneCountriesWithPreferred(props.preferredCountries);

// Reactive state
const dropdownOpen = ref(false);
const searchQuery = ref('');
const localNumber = ref('');
const selectedCountry = ref<PhoneCountry>(
  getPhoneCountryByCode(props.defaultCountry) || countries[0]
);

// Computed
const flagUrl = computed(() => getCountryFlagUrl(selectedCountry.value.iso2));

const filteredCountries = computed(() => {
  return searchPhoneCountries(searchQuery.value, props.preferredCountries);
});

// Methods
const getCountryFlagUrl = (iso2: string) => {
  return `https://flagcdn.com/24x18/${iso2.toLowerCase()}.png`;
};

const isPreferredCountry = (iso2: string) => {
  return props.preferredCountries.includes(iso2);
};

const selectCountry = (country: PhoneCountry) => {
  selectedCountry.value = country;
  dropdownOpen.value = false;
  searchQuery.value = ''; // Clear search on selection
  emit('country-changed', country);
  
  // Reformat existing number with new country
  if (localNumber.value) {
    handleInput();
  }
};

const handleInput = () => {
  const rawInput = localNumber.value;
  
  // Create full international number
  const fullNumber = selectedCountry.value.dialCode + rawInput.replace(/\D/g, '');
  
  try {
    // Parse and validate
    const phoneNumber = parsePhoneNumber(fullNumber);
    const isValid = phoneNumber?.isValid() || false;
    
    // Format for display (national format)
    if (phoneNumber && isValid) {
      const formatter = new AsYouType(selectedCountry.value.iso2 as any);
      const formatted = formatter.input(rawInput);
      localNumber.value = formatted;
    }
    
    // Emit data
    emit('update:modelValue', fullNumber);
    emit('phone-data', {
      number: fullNumber,
      isValid,
      country: selectedCountry.value
    });
    
  } catch (error) {
    // Handle invalid numbers gracefully
    emit('update:modelValue', fullNumber);
    emit('phone-data', {
      number: fullNumber,
      isValid: false,
      country: selectedCountry.value
    });
  }
};

const handleBlur = () => {
  // Additional formatting on blur if needed
};

const handleFlagError = (event: Event) => {
  // Fallback to a default flag or hide image
  const img = event.target as HTMLImageElement;
  img.style.display = 'none';
};

// Mobile-specific handlers
const closeDropdown = () => {
  dropdownOpen.value = false;
  searchQuery.value = '';
};

// Initialize from modelValue
watch(() => props.modelValue, (newValue) => {
  if (newValue && newValue !== selectedCountry.value.dialCode + localNumber.value.replace(/\D/g, '')) {
    try {
      const phoneNumber = parsePhoneNumber(newValue);
      if (phoneNumber) {
        // Find matching country
        const matchingCountry = countries.find(c => 
          c.dialCode === '+' + phoneNumber.countryCallingCode
        );
        
        if (matchingCountry) {
          selectedCountry.value = matchingCountry;
        }
        
        // Set local number (national format)
        localNumber.value = phoneNumber.formatNational().replace(phoneNumber.countryCallingCode, '').trim();
      }
    } catch (error) {
      // Handle invalid initial value
      localNumber.value = newValue;
    }
  }
}, { immediate: true });

// Clean up search query when dropdown closes
watch(dropdownOpen, (isOpen) => {
  if (!isOpen) {
    // Clear search after a small delay to allow selection to complete
    setTimeout(() => {
      searchQuery.value = '';
    }, 100);
  }
});
</script>

<style scoped>
.phone-input-wrapper {
  width: 100%;
}

.country-selector {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: rgba(var(--v-theme-surface), 1);
  border: 1px solid transparent;
  margin-right: 8px;
  user-select: none;
  -webkit-tap-highlight-color: transparent;
}

.country-selector:hover {
  background: rgba(var(--v-theme-primary), 0.08);
  border-color: rgba(var(--v-theme-primary), 0.24);
}

.country-selector--open {
  background: rgba(var(--v-theme-primary), 0.12);
  border-color: rgba(var(--v-theme-primary), 0.48);
}

.country-flag {
  width: 24px;
  height: 18px;
  border-radius: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
  object-fit: cover;
}

.country-code {
  font-size: 0.875rem;
  font-weight: 600;
  color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
  min-width: 32px;
}

.dropdown-icon {
  transition: transform 0.2s ease;
  color: rgba(var(--v-theme-on-surface), var(--v-medium-emphasis-opacity));
}

.dropdown-icon--rotated {
  transform: rotate(180deg);
}

/* Dropdown Styling */
.country-dropdown {
  min-width: 280px;
  max-width: 320px;
  max-height: 400px;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.search-container {
  padding: 12px;
  border-bottom: 1px solid rgba(var(--v-theme-outline), 0.12);
  background: rgba(var(--v-theme-surface), 1);
}

.search-input :deep(.v-field) {
  background: rgba(var(--v-theme-surface), 1);
}

/* Country List */
.country-list {
  flex: 1;
  max-height: 300px;
  overflow-y: auto;
  background: rgba(var(--v-theme-surface), 1);
  -webkit-overflow-scrolling: touch;
}

.country-list::-webkit-scrollbar {
  width: 6px;
}

.country-list::-webkit-scrollbar-track {
  background: transparent;
}

.country-list::-webkit-scrollbar-thumb {
  background: rgba(var(--v-theme-primary), 0.3);
  border-radius: 3px;
}

.country-item {
  cursor: pointer;
  transition: all 0.15s ease;
  border-left: 3px solid transparent;
}

.country-item:hover {
  background: rgba(var(--v-theme-primary), 0.08) !important;
}

.country-item--selected {
  background: rgba(var(--v-theme-primary), 0.12) !important;
  border-left-color: rgb(var(--v-theme-primary));
  font-weight: 600;
}

.country-item--preferred {
  background: rgba(var(--v-theme-primary), 0.04);
  font-weight: 500;
}

.list-flag {
  width: 20px;
  height: 15px;
  border-radius: 2px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  object-fit: cover;
}

.country-name {
  font-size: 0.875rem;
  font-weight: 500;
}

.dial-code {
  font-size: 0.8125rem;
  font-weight: 600;
  color: rgba(var(--v-theme-on-surface), var(--v-medium-emphasis-opacity));
  font-family: 'Roboto Mono', monospace;
}

/* Mobile Header */
.mobile-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(var(--v-theme-outline), 0.12);
  background: rgba(var(--v-theme-primary), 0.04);
}

.mobile-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
  margin: 0;
}

.close-btn {
  color: rgba(var(--v-theme-on-surface), var(--v-medium-emphasis-opacity)) !important;
}

/* Mobile Footer */
.mobile-footer {
  padding: 16px 20px;
  border-top: 1px solid rgba(var(--v-theme-outline), 0.12);
  background: rgba(var(--v-theme-surface), 1);
}

.cancel-btn {
  color: rgba(var(--v-theme-on-surface), var(--v-medium-emphasis-opacity)) !important;
}

/* Mobile-specific styling */
.phone-input-wrapper--mobile {
  position: relative;
}

.country-selector--mobile {
  padding: 6px 10px;
  margin-right: 6px;
  border-radius: 8px;
  min-height: 44px; /* Touch-friendly size */
  align-items: center;
  -webkit-tap-highlight-color: transparent;
}

.country-selector--mobile:active {
  background: rgba(var(--v-theme-primary), 0.16);
}

.country-dropdown--mobile {
  width: 90vw !important;
  max-width: 400px !important;
  max-height: 70vh !important;
}

.country-list--mobile {
  max-height: calc(50vh - 120px) !important;
  -webkit-overflow-scrolling: touch;
}

.country-item--mobile {
  min-height: 56px !important;
  padding: 12px 20px !important;
  border-left-width: 4px !important;
  -webkit-tap-highlight-color: transparent;
}

.country-item--mobile:active {
  background: rgba(var(--v-theme-primary), 0.16) !important;
}

.list-flag--mobile {
  width: 24px !important;
  height: 18px !important;
}

.country-name--mobile {
  font-size: 1rem !important;
  font-weight: 500 !important;
}

.dial-code--mobile {
  font-size: 0.9375rem !important;
  font-weight: 600 !important;
}

/* Touch-friendly input field */
.phone-input-wrapper--mobile .phone-text-field :deep(.v-field) {
  min-height: 56px !important;
}

.phone-input-wrapper--mobile .phone-text-field :deep(.v-field__input) {
  font-size: 16px !important; /* Prevent zoom on iOS */
  padding: 16px !important;
}

/* Responsive Breakpoints */
@media (max-width: 768px) {
  .country-dropdown {
    min-width: 260px;
    max-width: 300px;
  }
  
  .country-list {
    max-height: 250px;
  }
  
  .country-selector {
    min-height: 48px;
    padding: 6px 10px;
  }
  
  .search-input :deep(.v-field__input) {
    font-size: 16px !important; /* Prevent zoom */
  }
}

/* iOS specific fixes */
@supports (-webkit-touch-callout: none) {
  .phone-input-wrapper--mobile .phone-text-field :deep(.v-field__input) {
    font-size: 16px !important; /* Prevent zoom on focus */
    -webkit-appearance: none;
  }
  
  .search-input :deep(.v-field__input) {
    font-size: 16px !important;
    -webkit-appearance: none;
  }
  
  .country-list {
    -webkit-overflow-scrolling: touch;
  }
}

/* Accessibility improvements */
@media (prefers-reduced-motion: reduce) {
  .country-item,
  .country-selector,
  .dropdown-icon {
    transition: none !important;
  }
}
</style>
