import { useEffect, useState } from 'react'
import { Plus } from 'lucide-react'
import { useToast } from '@meshkee/dashboard-ui'
import { ApiError } from '../../lib/api'
import { createAddress } from '../../services/addressService'
import {
  listCitiesByProvinceSlug,
  listIranProvinces,
  type CityOption,
} from '../../services/citiesService'
import styles from './CheckoutAddAddressPanel.module.css'

function FieldLabel({
  htmlFor,
  optional,
  children,
}: {
  htmlFor: string
  optional?: boolean
  children: React.ReactNode
}) {
  return (
    <label htmlFor={htmlFor}>
      {children}
      {optional ? <span className={styles.optionalMark}> (اختیاری)</span> : null}
    </label>
  )
}

interface CheckoutAddAddressPanelProps {
  onSaved: () => void
  onCancel: () => void
  inModal?: boolean
}

export function CheckoutAddAddressPanel({
  onSaved,
  onCancel,
  inModal = false,
}: CheckoutAddAddressPanelProps) {
  const { showToast } = useToast()
  const [provinces, setProvinces] = useState<CityOption[]>([])
  const [cities, setCities] = useState<CityOption[]>([])
  const [loadingLocations, setLoadingLocations] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [label, setLabel] = useState('')
  const [provinceSlug, setProvinceSlug] = useState('')
  const [city, setCity] = useState('')
  const [address, setAddress] = useState('')
  const [postalCode, setPostalCode] = useState('')
  const [landline, setLandline] = useState('')

  useEffect(() => {
    const controller = new AbortController()

    async function loadProvinces() {
      setLoadingLocations(true)
      try {
        const items = await listIranProvinces(controller.signal)
        if (!controller.signal.aborted) setProvinces(items)
      } catch {
        if (!controller.signal.aborted) setError('بارگذاری استان‌ها ممکن نشد.')
      } finally {
        if (!controller.signal.aborted) setLoadingLocations(false)
      }
    }

    void loadProvinces()
    return () => controller.abort()
  }, [])

  async function handleProvinceChange(slug: string) {
    setProvinceSlug(slug)
    setCity('')
    setCities([])

    if (!slug) return

    try {
      const items = await listCitiesByProvinceSlug(slug)
      setCities(items)
    } catch {
      setError('بارگذاری شهرها ممکن نشد.')
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError('')

    const province = provinces.find((item) => item.slug === provinceSlug)
    if (!label.trim() || !province || !city.trim() || !address.trim()) {
      setError('لطفاً همه فیلدهای الزامی را تکمیل کنید.')
      return
    }

    setSaving(true)
    try {
      await createAddress({
        label: label.trim(),
        province: province.nameFa || province.nameEn,
        city: city.trim(),
        address: address.trim(),
        postalCode: postalCode.trim() || undefined,
        landline: landline.trim() || undefined,
      })
      showToast('آدرس ذخیره شد.', 'success')
      onSaved()
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'ذخیره آدرس ممکن نشد.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <form
      className={[styles.form, inModal ? styles.formInModal : ''].filter(Boolean).join(' ')}
      onSubmit={(e) => void handleSubmit(e)}
    >
      {error && (
        <div className={styles.error} role="alert">
          {error}
        </div>
      )}

      <div className={styles.fieldRowTriple}>
        <div className={styles.field}>
          <FieldLabel htmlFor="checkout-label">عنوان آدرس</FieldLabel>
          <input
            id="checkout-label"
            type="text"
            value={label}
            disabled={saving}
            onChange={(e) => setLabel(e.target.value)}
            placeholder="مثلاً خانه، محل کار"
          />
        </div>

        <div className={styles.field}>
          <FieldLabel htmlFor="checkout-province">استان</FieldLabel>
          <select
            id="checkout-province"
            value={provinceSlug}
            disabled={loadingLocations || saving}
            onChange={(e) => void handleProvinceChange(e.target.value)}
          >
            <option value="">انتخاب استان</option>
            {provinces.map((province) => (
              <option key={province.id} value={province.slug}>
                {province.nameFa}
              </option>
            ))}
          </select>
        </div>

        <div className={styles.field}>
          <FieldLabel htmlFor="checkout-city">شهر</FieldLabel>
          <select
            id="checkout-city"
            value={city}
            disabled={!provinceSlug || saving}
            onChange={(e) => setCity(e.target.value)}
          >
            <option value="">انتخاب شهر</option>
            {cities.map((item) => (
              <option key={item.id} value={item.nameFa}>
                {item.nameFa}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className={styles.field}>
        <FieldLabel htmlFor="checkout-address">آدرس</FieldLabel>
        <input
          id="checkout-address"
          type="text"
          value={address}
          disabled={saving}
          onChange={(e) => setAddress(e.target.value)}
          placeholder="خیابان، پلاک، واحد"
        />
      </div>

      <div className={styles.fieldRow}>
        <div className={styles.field}>
          <FieldLabel htmlFor="checkout-postal" optional>
            کد پستی
          </FieldLabel>
          <input
            id="checkout-postal"
            type="text"
            inputMode="numeric"
            value={postalCode}
            disabled={saving}
            onChange={(e) => setPostalCode(e.target.value)}
            placeholder="کد پستی"
            dir="ltr"
          />
        </div>

        <div className={styles.field}>
          <FieldLabel htmlFor="checkout-landline" optional>
            تلفن ثابت
          </FieldLabel>
          <input
            id="checkout-landline"
            type="tel"
            value={landline}
            disabled={saving}
            onChange={(e) => setLandline(e.target.value)}
            placeholder="021..."
            dir="ltr"
          />
        </div>
      </div>

      <div className={styles.formActions}>
        <button type="button" className={styles.cancelBtn} onClick={onCancel} disabled={saving}>
          انصراف
        </button>
        <button type="submit" className={styles.saveBtn} disabled={saving}>
          {saving ? 'در حال ذخیره...' : 'ذخیره آدرس'}
        </button>
      </div>
    </form>
  )
}

interface CheckoutAddAddressRowProps {
  onClick: () => void
}

export function CheckoutAddAddressRow({ onClick }: CheckoutAddAddressRowProps) {
  return (
    <button type="button" className={styles.addRow} onClick={onClick}>
      <Plus size={18} />
      <span>افزودن آدرس جدید</span>
    </button>
  )
}
