import { Plus, Trash2 } from 'lucide-react'
import styles from './AddressListEditor.module.css'

export type CityOption = {
  id: string
  parentId: string | null
  level: 'country' | 'province' | 'city'
  nameFa: string
  nameEn: string
  landlineCode: string | null
  slug: string
  sortOrder: number
}

export type AddressListItem = {
  id?: string
  provinceSlug: string
  province: string
  city: string
  address: string
  postalCode: string
  landline: string
}

export function createEmptyAddressItem(): AddressListItem {
  return {
    provinceSlug: '',
    province: '',
    city: '',
    address: '',
    postalCode: '',
    landline: '',
  }
}

export type AddressLocale = 'en' | 'fa'

export type AddressListEditorLabels = {
  title?: string
  addLabel?: string
  loading?: string
  province?: string
  city?: string
  address?: string
  postalCode?: string
  landline?: string
  selectProvince?: string
  selectCity?: string
  streetPlaceholder?: string
  postalPlaceholder?: string
  landlinePlaceholder?: string
  removeAriaLabel?: string
}

export function getLocationOptionLabel(option: CityOption, locale: AddressLocale = 'en') {
  return locale === 'fa' ? option.nameFa : option.nameEn
}

export function matchProvinceByName(provinceName: string, provinces: CityOption[]) {
  const normalized = provinceName.trim().toLowerCase()
  return provinces.find(
    (item) =>
      item.nameFa === provinceName ||
      item.nameEn.toLowerCase() === normalized ||
      item.slug === normalized,
  )
}

export function matchCityByName(cityName: string, cities: CityOption[]) {
  const normalized = cityName.trim().toLowerCase()
  return cities.find(
    (item) =>
      item.nameFa === cityName ||
      item.nameEn.toLowerCase() === normalized ||
      item.slug === normalized,
  )
}

type AddressListEditorProps = {
  addresses: AddressListItem[]
  provinces: CityOption[]
  citiesByProvince: Record<string, CityOption[]>
  onAddressChange: (index: number, patch: Partial<AddressListItem>) => void
  onProvinceChange: (index: number, provinceSlug: string) => void | Promise<void>
  onAdd: () => void
  onRemove: (index: number) => void
  disabled?: boolean
  loading?: boolean
  locale?: AddressLocale
  title?: string
  addLabel?: string
  labels?: AddressListEditorLabels
}

export function AddressListEditor({
  addresses,
  provinces,
  citiesByProvince,
  onAddressChange,
  onProvinceChange,
  onAdd,
  onRemove,
  disabled = false,
  loading = false,
  locale = 'en',
  title,
  addLabel,
  labels = {},
}: AddressListEditorProps) {
  const selectClassName =
    locale === 'fa' ? `${styles.selectField} ${styles.selectFieldFa}` : styles.selectField

  const resolved = {
    title: labels.title ?? title ?? 'Saved addresses',
    addLabel: labels.addLabel ?? addLabel ?? 'Add address',
    loading: labels.loading ?? 'Loading addresses...',
    province: labels.province ?? 'Province',
    city: labels.city ?? 'City',
    address: labels.address ?? 'Address',
    postalCode: labels.postalCode ?? 'Postal code',
    landline: labels.landline ?? 'Landline',
    selectProvince: labels.selectProvince ?? 'Select province',
    selectCity: labels.selectCity ?? 'Select city',
    streetPlaceholder: labels.streetPlaceholder ?? 'Street address',
    postalPlaceholder: labels.postalPlaceholder ?? 'Postal code',
    landlinePlaceholder: labels.landlinePlaceholder ?? 'Landline',
    removeAriaLabel: labels.removeAriaLabel ?? 'Remove address',
  }

  return (
    <>
      <div className={styles.sectionHeader}>
        <h3 className={styles.sectionTitle}>{resolved.title}</h3>
        <button type="button" className={styles.addBtn} onClick={onAdd} disabled={disabled}>
          <Plus size={16} />
          {resolved.addLabel}
        </button>
      </div>

      {loading ? (
        <p className={styles.helperText}>{resolved.loading}</p>
      ) : (
        <div className={styles.duplicatorGrid}>
          <div className={styles.gridHeader}>
            <span>{resolved.province}</span>
            <span>{resolved.city}</span>
            <span>{resolved.address}</span>
            <span>{resolved.postalCode}</span>
            <span>{resolved.landline}</span>
            <span />
          </div>

          {addresses.map((item, index) => {
            const cities = item.provinceSlug
              ? (citiesByProvince[item.provinceSlug] ?? [])
              : []

            return (
              <div key={item.id ?? `address-${index}`} className={styles.gridRow}>
                <select
                  className={selectClassName}
                  value={item.provinceSlug}
                  disabled={disabled}
                  onChange={(e) => void onProvinceChange(index, e.target.value)}
                >
                  <option value="">{resolved.selectProvince}</option>
                  {provinces.map((province) => (
                    <option key={province.id} value={province.slug}>
                      {getLocationOptionLabel(province, locale)}
                    </option>
                  ))}
                </select>

                <select
                  className={selectClassName}
                  value={item.city}
                  disabled={disabled || !item.provinceSlug}
                  onChange={(e) => onAddressChange(index, { city: e.target.value })}
                >
                  <option value="">{resolved.selectCity}</option>
                  {cities.map((city) => (
                    <option key={city.id} value={getLocationOptionLabel(city, locale)}>
                      {getLocationOptionLabel(city, locale)}
                    </option>
                  ))}
                </select>

                <input
                  className={styles.textField}
                  value={item.address}
                  disabled={disabled}
                  onChange={(e) => onAddressChange(index, { address: e.target.value })}
                  placeholder={resolved.streetPlaceholder}
                />

                <input
                  className={styles.textField}
                  value={item.postalCode}
                  disabled={disabled}
                  onChange={(e) => onAddressChange(index, { postalCode: e.target.value })}
                  placeholder={resolved.postalPlaceholder}
                />

                <input
                  className={styles.textField}
                  value={item.landline}
                  disabled={disabled}
                  onChange={(e) => onAddressChange(index, { landline: e.target.value })}
                  placeholder={resolved.landlinePlaceholder}
                />

                <button
                  type="button"
                  className={styles.removeBtn}
                  onClick={() => onRemove(index)}
                  aria-label={resolved.removeAriaLabel}
                  disabled={disabled}
                >
                  <Trash2 size={15} />
                </button>
              </div>
            )
          })}
        </div>
      )}
    </>
  )
}
