import { useMemo } from 'react'
import { Link } from 'react-router-dom'
import type { BrandData } from '../types/brand'
import {
  formatCatalogProductSummary,
  summarizeCatalogProduct,
  toCatalogBrand,
} from '../lib/productCatalog'
import { Field, Select } from './ui'

const AUTO_VALUE = '__auto__'
const NONE_VALUE = '__none__'

type BrandProductPickerProps = {
  brands: BrandData[]
  brandId: string
  productId: string | null
  onBrandChange: (brandId: string) => void
  onProductChange: (productId: string | null) => void
  label?: string
  /** 主題已綁定品牌時，只選產品、不換品牌 */
  brandLocked?: boolean
}

export function BrandProductPicker({
  brands,
  brandId,
  productId,
  onBrandChange,
  onProductChange,
  label = '置入品牌與產品',
  brandLocked = false,
}: BrandProductPickerProps) {
  const catalogBrands = useMemo(() => brands.map(toCatalogBrand), [brands])
  const selectedBrand = useMemo(
    () => catalogBrands.find((item) => item.id === brandId) ?? null,
    [catalogBrands, brandId],
  )
  const selectedProduct = useMemo(() => {
    if (!selectedBrand || !productId) return null
    return selectedBrand.products.find((item) => item.id === productId) ?? null
  }, [selectedBrand, productId])

  const preview = useMemo(() => {
    if (!selectedBrand) return null
    if (selectedProduct) {
      return formatCatalogProductSummary(
        selectedBrand.name,
        selectedProduct.context,
        selectedProduct.label,
      )
    }
    if (selectedBrand.products.length > 0) {
      return `${selectedBrand.name} · ${selectedBrand.products.length} 個產品（海巡時依標籤自動推薦）`
    }
    const legacy = brands.find((item) => item.id === brandId)
    if (legacy?.product_context) {
      return summarizeCatalogProduct(
        {
          id: 'legacy',
          label: legacy.display_name || '產品',
          product_context: legacy.product_context,
          create_at: 0,
          update_at: 0,
        },
        selectedBrand.name,
      )
    }
    return null
  }, [selectedBrand, selectedProduct, brands, brandId])

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between gap-2">
        <p className="text-sm font-bold text-ink">{label}</p>
        <Link to="/brands" className="text-xs font-semibold text-brand hover:underline">
          管理品牌與產品
        </Link>
      </div>

      {brandLocked && selectedBrand ? (
        <Field label="品牌">
          <p className="rounded-[var(--radius-md)] border-2 border-line bg-surface px-4 py-3 text-[15px] text-ink">
            {selectedBrand.name}
          </p>
        </Field>
      ) : (
        <Field label="品牌">
          <Select
            value={brandId || NONE_VALUE}
            onChange={(e) => {
              const next = e.target.value
              if (next === NONE_VALUE) {
                onBrandChange('')
                onProductChange(null)
                return
              }
              onBrandChange(next)
              onProductChange(null)
            }}
            data-islander-label="置入品牌"
          >
            <option value={NONE_VALUE}>請選擇品牌</option>
            {catalogBrands.map((item) => (
              <option key={item.id} value={item.id}>
                {item.name}（{item.products.length} 個產品）
              </option>
            ))}
          </Select>
        </Field>
      )}

      {selectedBrand && selectedBrand.products.length > 0 ? (
        <Field label="產品">
          <Select
            value={productId ?? AUTO_VALUE}
            onChange={(e) => {
              const next = e.target.value
              onProductChange(next === AUTO_VALUE ? null : next)
            }}
            data-islander-label="置入產品"
          >
            <option value={AUTO_VALUE}>自動依海巡標籤推薦</option>
            {selectedBrand.products.map((product) => (
              <option key={product.id} value={product.id}>
                {product.label}
                {product.matchTags.length > 0 ? ` · ${product.matchTags.slice(0, 3).join('、')}` : ''}
              </option>
            ))}
          </Select>
        </Field>
      ) : null}

      {selectedBrand && selectedBrand.products.length === 0 ? (
        <p className="text-sm text-ink-secondary">
          此品牌尚無產品。
          <Link to={`/brands/${selectedBrand.id}`} className="ml-1 font-semibold text-brand hover:underline">
            到品牌庫新增
          </Link>
        </p>
      ) : null}

      {preview ? (
        <div className="rounded-[var(--radius-md)] border border-line/70 bg-surface-muted px-3 py-2.5">
          <p className="text-xs font-semibold text-ink">產品定位預覽</p>
          <p className="mt-1 line-clamp-3 text-sm text-ink-secondary">{preview}</p>
        </div>
      ) : null}
    </div>
  )
}