import { useCallback, useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { ProductItemForm } from '../components/ProductItemForm'
import { hasProductContext, parseProductContext, serializeProductContext } from '../lib/productContext'
import type { BrandData, BrandProductData } from '../types/brand'
import { AcLink, Button, Card, ErrorText, Field, Input, PageTitle } from '../components/ui'

const emptyDraft = () => ({
  label: '',
  productContext: '',
  matchTags: [] as string[],
})

function buildProductPayload(label: string, productContext: string, brandName: string) {
  const fields = parseProductContext(productContext)
  return serializeProductContext({
    ...fields,
    brand: brandName,
    product: label.trim(),
  })
}

export function BrandProductEditPage() {
  const navigate = useNavigate()
  const { id: brandId = '', productId = '' } = useParams()
  const isCreate = productId === 'new'

  const [brand, setBrand] = useState<BrandData | null>(null)
  const [draft, setDraft] = useState(emptyDraft)
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')
  const brandName = brand?.display_name?.trim() || '未命名品牌'
  const backTo = `/brands/${encodeURIComponent(brandId)}`

  const load = useCallback(async () => {
    if (!brandId) return
    setLoading(true)
    setError('')
    try {
      const brandData = await api.get<BrandData>(`/api/v1/brands/${encodeURIComponent(brandId)}`, {
        auth: true,
      })
      setBrand(brandData)

      if (isCreate) {
        setDraft(emptyDraft())
        return
      }

      const products = await api.get<{ list: BrandProductData[] }>(
        `/api/v1/brands/${encodeURIComponent(brandId)}/products`,
        { auth: true },
      )
      const item = (products.list ?? []).find((p) => p.id === productId)
      if (!item) {
        setError('找不到此產品')
        return
      }
      setDraft({
        label: item.label,
        productContext: item.product_context,
        matchTags: item.match_tags ?? [],
      })
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '載入失敗')
    } finally {
      setLoading(false)
    }
  }, [brandId, isCreate, productId])

  useEffect(() => {
    void load()
  }, [load])

  const submit = async () => {
    if (!brandId) return
    if (!draft.label.trim()) {
      setError('請填寫產品名稱')
      return
    }
    const payload = buildProductPayload(draft.label, draft.productContext, brandName)
    if (!hasProductContext(payload)) {
      setError('請填寫產品特色')
      return
    }
    setSubmitting(true)
    setError('')
    try {
      if (isCreate) {
        await api.post<BrandProductData>(
          `/api/v1/brands/${encodeURIComponent(brandId)}/products`,
          {
            label: draft.label.trim(),
            product_context: payload,
            match_tags: draft.matchTags,
          },
          { auth: true },
        )
      } else {
        await api.patch<BrandProductData>(
          `/api/v1/brands/${encodeURIComponent(brandId)}/products/${encodeURIComponent(productId)}`,
          {
            label: draft.label.trim(),
            product_context: payload,
            match_tags: draft.matchTags,
          },
          { auth: true },
        )
      }
      navigate(backTo)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '儲存產品失敗')
    } finally {
      setSubmitting(false)
    }
  }

  if (!brandId) {
    return (
      <Card className="py-8 text-center">
        <p className="text-sm text-muted">未指定品牌。</p>
      </Card>
    )
  }

  if (!productId) {
    return (
      <Card className="py-8 text-center">
        <p className="text-sm text-muted">未指定產品。</p>
      </Card>
    )
  }

  return (
    <div className="mx-auto w-full max-w-4xl space-y-8">
      <AcLink to={backTo} className="inline-flex items-center gap-1.5 text-sm">
        ← 返回品牌
      </AcLink>

      <PageTitle
        title={isCreate ? '新增產品' : '編輯產品'}
        subtitle={isCreate ? `為「${brandName}」建立新的產品線。` : `調整「${brandName}」旗下的產品資訊。`}
      />

      <Card className="grid gap-6 p-6 md:p-8">
        <Field label="所屬品牌">
          <Input value={brandName} disabled className="min-h-12 px-5 py-3.5" />
        </Field>

        {loading ? (
          <p className="text-sm text-muted">載入中…</p>
        ) : (
          <ProductItemForm
            label={draft.label}
            productContext={draft.productContext}
            matchTags={draft.matchTags}
            onLabelChange={(value) => setDraft((prev) => ({ ...prev, label: value }))}
            onProductContextChange={(value) => setDraft((prev) => ({ ...prev, productContext: value }))}
            onMatchTagsChange={(tags) => setDraft((prev) => ({ ...prev, matchTags: tags }))}
            spacious
          />
        )}

        <div className="flex flex-wrap gap-2 border-t border-line/60 pt-4">
          <Button variant="ghost" onClick={() => navigate(backTo)} disabled={submitting}>
            取消
          </Button>
          <Button onClick={() => void submit()} disabled={submitting || loading}>
            {submitting ? '儲存中…' : '儲存產品'}
          </Button>
        </div>
      </Card>

      <ErrorText message={error} />
    </div>
  )
}