import { useEffect, useMemo, useState } from "react"
import { Link, useNavigate, useParams } from "react-router-dom"
import DOMPurify from "dompurify"
import { ArrowLeft, CheckCircle2, ShoppingCart } from "lucide-react"
import {
  fetchGroups,
  fetchProducts,
  type StoreGroup,
  type StoreProduct,
  type StoreProvisionProductPageTab,
  type StoreProvisionPurchaseField,
} from "../api/store"
import { addCartItem } from "../api/cart"
import { useAuth } from "../contexts/AuthContext"
import { toast } from "../utils/toast"

const CYCLE_LABEL: Record<string, string> = {
  hourly: "小时",
  daily: "天",
  monthly: "月",
  quarterly: "季度",
  semi_annually: "半年",
  annually: "年",
  biennially: "两年",
  triennially: "三年",
  one_time: "一次性",
}

function minQuantity(product: StoreProduct) {
  return Math.max(1, product.min_quantity ?? 1)
}

function maxQuantity(product: StoreProduct) {
  const stockMax = product.stock_policy === "tracked" ? Math.max(0, product.stock ?? 0) : 0
  const productMax = product.max_quantity ?? 0
  if (product.stock_policy === "tracked") return productMax > 0 ? Math.min(productMax, stockMax) : stockMax
  return productMax
}

function enabledPricings(product: StoreProduct) {
  return [...product.pricings].filter((item) => item.is_enabled).sort((a, b) => a.sort_order - b.sort_order)
}

function SafeHtml({ html }: { html: string }) {
  return (
    <div
      className="prose prose-sm max-w-none text-gray-700 [&_table]:w-full [&_td]:border [&_td]:border-gray-200 [&_td]:p-2 [&_th]:border [&_th]:border-gray-200 [&_th]:bg-gray-50 [&_th]:p-2"
      dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }}
    />
  )
}

function fieldDefaultValue(field: StoreProvisionPurchaseField) {
  if (field.default !== undefined) return field.default
  if (field.type === "checkbox") return false
  return ""
}

function defaultsFromFields(fields: StoreProvisionPurchaseField[]) {
  const values: Record<string, unknown> = {}
  for (const field of fields) values[field.key] = fieldDefaultValue(field)
  return values
}

function isFieldEmpty(value: unknown) {
  return value === null || value === undefined || value === ""
}

export default function GenericProductPage() {
  const { categorySlug, groupSlug, productSku } = useParams<{ categorySlug: string; groupSlug: string; productSku: string }>()
  const navigate = useNavigate()
  const { user } = useAuth()
  const [loading, setLoading] = useState(true)
  const [buying, setBuying] = useState(false)
  const [groups, setGroups] = useState<StoreGroup[]>([])
  const [products, setProducts] = useState<StoreProduct[]>([])
  const [cycle, setCycle] = useState("")
  const [quantity, setQuantity] = useState(1)
  const [alias, setAlias] = useState("")
  const [activeTab, setActiveTab] = useState("")
  const [pluginFieldValues, setPluginFieldValues] = useState<Record<string, unknown>>({})

  useEffect(() => {
    if (!categorySlug || !groupSlug) return
    setLoading(true)
    Promise.all([fetchGroups(categorySlug), fetchProducts(categorySlug, groupSlug)])
      .then(([groupRes, productRes]) => {
        setGroups(groupRes.data ?? [])
        const nextProducts = productRes.data ?? []
        setProducts(nextProducts)
        const product = nextProducts.find((item) => item.sku === productSku) ?? nextProducts[0]
        const firstPricing = product ? enabledPricings(product)[0] : null
        setCycle(firstPricing?.cycle ?? "")
        setQuantity(product ? minQuantity(product) : 1)
        const firstTab = product?.product_page?.tabs?.[0] ?? product?.provision_plugin?.product_page?.tabs?.[0]
        setActiveTab(firstTab?.key ?? "")
        const page = product?.product_page ?? product?.provision_plugin?.product_page
        setPluginFieldValues(defaultsFromFields(page?.purchase_fields ?? []))
      })
      .finally(() => setLoading(false))
  }, [categorySlug, groupSlug, productSku])

  const product = useMemo(
    () => products.find((item) => item.sku === productSku) ?? null,
    [products, productSku],
  )
  const group = useMemo(() => groups.find((item) => item.slug === groupSlug) ?? null, [groups, groupSlug])
  const pricings = product ? enabledPricings(product) : []
  const currentPricing = pricings.find((item) => item.cycle === cycle) ?? pricings[0] ?? null
  const page = product?.product_page ?? product?.provision_plugin?.product_page ?? null
  const tabs = (page?.tabs ?? []).filter((tab): tab is StoreProvisionProductPageTab => Boolean(tab.key && tab.label))
  const purchaseFields = page?.purchase_fields ?? []
  const selectedTab = tabs.find((tab) => tab.key === activeTab) ?? tabs[0] ?? null
  const soldOut = product?.stock_policy === "tracked" && (product.stock ?? 0) <= 0
  const max = product ? maxQuantity(product) : 0
  const total = ((currentPricing?.price ?? 0) * quantity) + (currentPricing?.setup_fee ?? 0)

  const buy = async () => {
    if (!product || !currentPricing) return
    if (!user) {
      navigate("/login")
      return
    }
    if (soldOut) {
      toast.error("该产品已售罄")
      return
    }
    if (max > 0 && quantity > max) {
      toast.error(`购买数量超出限制，最多可购买 ${max} 件`)
      return
    }
    const missingField = purchaseFields.find((field) => field.required && isFieldEmpty(pluginFieldValues[field.key]))
    if (missingField) {
      toast.error(`请填写${missingField.label}`)
      return
    }
    setBuying(true)
    try {
      const res = await addCartItem({
        product_id: product.id,
        cycle: currentPricing.cycle,
        quantity,
        alias: alias || null,
        os_image: null,
        unit_price: currentPricing.price,
        setup_fee: currentPricing.setup_fee,
        addon_price: 0,
        slider_values: purchaseFields.length > 0 ? { __plugin_fields: pluginFieldValues } : null,
      })
      toast.success("已加入购物车")
      navigate(res.data?.id ? `/cart?from=store&highlight=${res.data.id}` : "/cart")
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加入购物车失败")
    } finally {
      setBuying(false)
    }
  }

  if (loading) {
    return <div className="mx-auto max-w-6xl px-6 py-10 text-sm text-gray-500">正在加载产品...</div>
  }
  if (!product) {
    return <div className="mx-auto max-w-6xl px-6 py-10 text-sm text-gray-500">产品不存在或已下架。</div>
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="mx-auto max-w-6xl px-6 py-6">
        <Link to={`/store/${categorySlug}/${groupSlug}`} className="inline-flex items-center gap-2 text-sm text-gray-500 hover:text-sky-600">
          <ArrowLeft className="h-4 w-4" />
          返回产品组
        </Link>
        <div className="mt-5 grid gap-6 lg:grid-cols-[1fr_340px]">
          <main className="min-w-0 rounded-lg border border-gray-200 bg-white">
            <div className="border-b border-gray-100 px-6 py-5">
              <div className="text-sm text-gray-500">{group?.name ?? "通用产品"}</div>
              <h1 className="mt-1 text-2xl font-semibold text-gray-900">{product.name}</h1>
              {page?.summary_html && <div className="mt-4"><SafeHtml html={page.summary_html} /></div>}
            </div>
            <div className="border-b border-gray-100 px-6">
              <div className="flex gap-1 overflow-x-auto">
                {(tabs.length ? tabs : [{ key: "blank", label: "产品内容", html: page?.empty_state_html ?? "" }]).map((tab) => (
                  <button
                    key={tab.key}
                    type="button"
                    onClick={() => setActiveTab(tab.key)}
                    className={`h-11 border-b-2 px-4 text-sm font-medium ${((activeTab || "blank") === tab.key) ? "border-sky-500 text-sky-600" : "border-transparent text-gray-500 hover:text-gray-800"}`}
                  >
                    {tab.label}
                  </button>
                ))}
              </div>
            </div>
            <div className="min-h-64 px-6 py-6">
              {selectedTab?.html ? <SafeHtml html={selectedTab.html} /> : <SafeHtml html={page?.empty_state_html ?? ""} />}
            </div>
          </main>
          <aside className="h-fit rounded-lg border border-gray-200 bg-white p-5">
            <div className="text-sm font-medium text-gray-900">购买配置</div>
            <div className="mt-4 space-y-4">
              <div>
                <label className="mb-2 block text-xs font-medium text-gray-500">周期</label>
                <div className="grid grid-cols-2 gap-2">
                  {pricings.map((item) => (
                    <button
                      key={item.id}
                      type="button"
                      onClick={() => setCycle(item.cycle)}
                      className={`rounded-md border px-3 py-2 text-left text-sm ${cycle === item.cycle ? "border-sky-500 bg-sky-50 text-sky-700" : "border-gray-200 text-gray-700 hover:border-gray-300"}`}
                    >
                      <div>{CYCLE_LABEL[item.cycle] ?? item.cycle}</div>
                      <div className="mt-1 font-semibold">¥{item.price.toFixed(2)}</div>
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="mb-2 block text-xs font-medium text-gray-500">数量</label>
                <input
                  type="number"
                  min={minQuantity(product)}
                  max={max || undefined}
                  value={quantity}
                  onChange={(event) => setQuantity(Math.max(minQuantity(product), Number(event.target.value) || minQuantity(product)))}
                  className="h-10 w-full rounded-md border border-gray-200 px-3 text-sm outline-none focus:border-sky-400"
                />
              </div>
              <div>
                <label className="mb-2 block text-xs font-medium text-gray-500">备注</label>
                <input
                  value={alias}
                  onChange={(event) => setAlias(event.target.value)}
                  className="h-10 w-full rounded-md border border-gray-200 px-3 text-sm outline-none focus:border-sky-400"
                  placeholder="可选"
                />
              </div>
              {purchaseFields.map((field) => (
                <div key={field.key}>
                  <label className="mb-2 block text-xs font-medium text-gray-500">
                    {field.label}{field.required ? " *" : ""}
                  </label>
                  {field.type === "textarea" ? (
                    <textarea
                      value={String(pluginFieldValues[field.key] ?? "")}
                      onChange={(event) => setPluginFieldValues((values) => ({ ...values, [field.key]: event.target.value }))}
                      className="min-h-20 w-full rounded-md border border-gray-200 px-3 py-2 text-sm outline-none focus:border-sky-400"
                      placeholder={field.placeholder}
                    />
                  ) : field.type === "select" ? (
                    <select
                      value={String(pluginFieldValues[field.key] ?? "")}
                      onChange={(event) => setPluginFieldValues((values) => ({ ...values, [field.key]: event.target.value }))}
                      className="h-10 w-full rounded-md border border-gray-200 px-3 text-sm outline-none focus:border-sky-400"
                    >
                      <option value="">请选择</option>
                      {(field.options ?? []).map((option) => (
                        <option key={option.value} value={option.value}>{option.label}</option>
                      ))}
                    </select>
                  ) : field.type === "checkbox" ? (
                    <label className="inline-flex items-center gap-2 text-sm text-gray-700">
                      <input
                        type="checkbox"
                        checked={Boolean(pluginFieldValues[field.key])}
                        onChange={(event) => setPluginFieldValues((values) => ({ ...values, [field.key]: event.target.checked }))}
                      />
                      {field.placeholder || "启用"}
                    </label>
                  ) : (
                    <input
                      type={field.type === "number" ? "number" : "text"}
                      value={String(pluginFieldValues[field.key] ?? "")}
                      onChange={(event) => setPluginFieldValues((values) => ({
                        ...values,
                        [field.key]: field.type === "number" && event.target.value !== "" ? Number(event.target.value) : event.target.value,
                      }))}
                      className="h-10 w-full rounded-md border border-gray-200 px-3 text-sm outline-none focus:border-sky-400"
                      placeholder={field.placeholder}
                    />
                  )}
                  {field.help && <p className="mt-1 text-xs text-gray-400">{field.help}</p>}
                </div>
              ))}
              <div className="rounded-md bg-gray-50 p-3">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-gray-500">合计</span>
                  <span className="text-xl font-semibold text-gray-900">¥{total.toFixed(2)}</span>
                </div>
                {currentPricing?.setup_fee ? <div className="mt-1 text-xs text-gray-500">含安装费 ¥{currentPricing.setup_fee.toFixed(2)}</div> : null}
              </div>
              <button
                type="button"
                disabled={!currentPricing || soldOut || buying}
                onClick={() => void buy()}
                className="inline-flex h-11 w-full items-center justify-center gap-2 rounded-md bg-sky-600 px-4 text-sm font-medium text-white hover:bg-sky-700 disabled:cursor-not-allowed disabled:bg-gray-300"
              >
                {soldOut ? <CheckCircle2 className="h-4 w-4" /> : <ShoppingCart className="h-4 w-4" />}
                {soldOut ? "已售罄" : "加入购物车"}
              </button>
            </div>
          </aside>
        </div>
      </div>
    </div>
  )
}
