import { useEffect, useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import { api } from '@/lib/api'
import { Modal } from '@/components/Modal'
import { Button } from '@/components/Button'
import { Field, TextInput, Select, AsyncSelect } from '@/components/Field'
import { useUnits } from '@/lib/useLookups'
import { useOrgSettings } from '@/lib/useOrgSettings'
import { BarcodeType, type Product } from '@/lib/types'
import { generateEan13InternalPrefix2 } from '@/lib/barcode'

type Prefill =
  | { kind: 'barcode'; value: string; barcodeType: BarcodeType }
  | { kind: 'article'; value: string }
  | { kind: 'name'; value: string }

interface Props {
  open: boolean
  onClose: () => void
  prefill: Prefill | null
  onCreated: (p: Product) => void
}

/** Минималка для создания товара «на лету» из формы документа.
 * Поля: Название, Группа, Единица измерения. Штрихкод и артикул
 * pre-fill'ятся из набранного запроса в зависимости от типа. */
export function ProductQuickCreateModal({ open, onClose, prefill, onCreated }: Props) {
  const units = useUnits()
  const org = useOrgSettings()

  const [name, setName] = useState('')
  const [article, setArticle] = useState('')
  const [barcode, setBarcode] = useState('')
  const [barcodeType, setBarcodeType] = useState<BarcodeType>(BarcodeType.Ean13)
  const [unitId, setUnitId] = useState('')
  const [groupId, setGroupId] = useState('')
  const [error, setError] = useState<string | null>(null)

  // На каждый open подставляем prefill и дефолты для пустых полей
  useEffect(() => {
    if (!open) return
    setError(null)
    if (prefill?.kind === 'barcode') {
      setBarcode(prefill.value)
      setBarcodeType(prefill.barcodeType)
      setName('')
      setArticle('')
    } else if (prefill?.kind === 'article') {
      setArticle(prefill.value)
      setBarcode(generateEan13InternalPrefix2())
      setBarcodeType(BarcodeType.Ean13)
      setName('')
    } else if (prefill?.kind === 'name') {
      setName(prefill.value)
      setArticle('')
      setBarcode(generateEan13InternalPrefix2())
      setBarcodeType(BarcodeType.Ean13)
    } else {
      setName(''); setArticle(''); setBarcode(generateEan13InternalPrefix2()); setBarcodeType(BarcodeType.Ean13)
    }
  }, [open, prefill])

  useEffect(() => {
    if (!open) return
    if (!unitId && units.data?.length) {
      const sht = units.data.find((u) => u.code === '796') ?? units.data[0]
      setUnitId(sht.id)
    }
  }, [open, units.data, unitId])

  const create = useMutation({
    mutationFn: async () => {
      const payload = {
        name: name.trim(),
        article: article.trim() || null,
        description: null,
        unitOfMeasureId: unitId,
        vat: org.data?.showVatEnabledOnProduct ? (org.data?.vatRate ?? 0) : null,
        vatEnabled: true,
        productGroupId: groupId,
        defaultSupplierId: null,
        countryOfOriginId: null,
        isService: false,
        packaging: 0,
        isMarked: false,
        minStock: null,
        maxStock: null,
        referencePrice: null,
        purchaseCurrencyId: null,
        imageUrl: null,
        prices: [],
        barcodes: [{ code: barcode, type: barcodeType, isPrimary: true }],
      }
      const res = await api.post<Product>('/api/catalog/products', payload)
      return res.data
    },
    onSuccess: (p) => { onCreated(p); onClose() },
    onError: (e: Error) => {
      const msg = (e as { response?: { data?: { error?: string } } }).response?.data?.error ?? e.message
      setError(msg)
    },
  })

  const canSave = name.trim().length > 0 && unitId && groupId && barcode.trim().length > 0
  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Быстрое создание товара"
      footer={<>
        <Button type="button" variant="secondary" onClick={onClose}>Отмена</Button>
        <Button type="button" disabled={!canSave || create.isPending} onClick={() => create.mutate()}>
          {create.isPending ? 'Создаю…' : 'Создать и добавить'}
        </Button>
      </>}
    >
      <div className="space-y-3">
        {error && <div className="p-2 rounded bg-red-50 text-red-700 text-sm border border-red-200">{error}</div>}
        <Field label="Название *">
          <TextInput value={name} onChange={(e) => setName(e.target.value)} autoFocus={prefill?.kind !== 'name'} />
        </Field>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Артикул">
            <TextInput value={article} onChange={(e) => setArticle(e.target.value)} placeholder="авто" />
          </Field>
          <Field label="Штрихкод *">
            <TextInput value={barcode} onChange={(e) => setBarcode(e.target.value)} />
          </Field>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Группа *">
            <AsyncSelect
              url="/api/catalog/product-groups"
              value={groupId}
              onChange={setGroupId}
              placeholder="Выберите группу…"
              getLabel={(item) => String(item['path'] ?? item['name'] ?? '')}
            />
          </Field>
          <Field label="Единица измерения *">
            <Select value={unitId} onChange={(e) => setUnitId(e.target.value)}>
              {units.data?.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
            </Select>
          </Field>
        </div>
        <p className="text-xs text-slate-500">
          Остальные поля (цены, описание, поставщик) можно дозаполнить позже в карточке товара.
        </p>
      </div>
    </Modal>
  )
}
