import { useCallback, useEffect, useState } from "react"
import { RefreshCw, Coins, Search } from "lucide-react"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { cn } from "@/lib/utils"

interface GoodsItem {
  goodsId: number
  itemId: number
  name: string
  price: number
  limitCount: number
  boughtNum: number
  unlocked: boolean
  itemCount: number
}

export function ShopPanel({ email, refreshKey }: { email: string, refreshKey?: number }) {
  const [goods, setGoods] = useState<GoodsItem[]>([])
  const [filteredGoods, setFilteredGoods] = useState<GoodsItem[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [isBuying, setIsBuying] = useState(false)
  const [searchQuery, setSearchQuery] = useState("")
  const [buyDialogOpen, setBuyDialogOpen] = useState(false)
  const [selectedGoods, setSelectedGoods] = useState<GoodsItem | null>(null)
  const [buyAmount, setBuyAmount] = useState(1)
  const [message, setMessage] = useState("")
  const [imageMap, setImageMap] = useState<Record<number, string>>({})

  const fetchShop = useCallback(async () => {
    if (!email) return
    setIsLoading(true)
    try {
      const res = await fetch(`/api/shop?email=${email}`)
      const json = await res.json()
      if (json.goods) {
        setGoods(json.goods)
        setFilteredGoods(json.goods)
      }
    } catch (e) {
      console.error(e)
    } finally {
      setIsLoading(false)
    }
  }, [email])

  useEffect(() => {
    fetchShop()
  }, [fetchShop, refreshKey])

  useEffect(() => {
    if (!searchQuery) {
      setFilteredGoods(goods)
    } else {
      const query = searchQuery.toLowerCase()
      setFilteredGoods(goods.filter(g => g.name.toLowerCase().includes(query)))
    }
  }, [searchQuery, goods])

  useEffect(() => {
    let cancelled = false
    fetch('/shop_plants_organized/mapping.csv')
      .then(res => res.text())
      .then(text => {
        if (cancelled) return
        const lines = text.split(/\r?\n/).filter(Boolean)
        if (lines.length <= 1) {
          setImageMap({})
          return
        }
        const map: Record<number, string> = {}
        for (let i = 1; i < lines.length; i += 1) {
          const line = lines[i].trim()
          if (!line) continue
          const parts = line.split(',')
          if (parts.length < 5) continue
          const seedId = Number(parts[0])
          const fileName = parts[4]
          if (!Number.isNaN(seedId) && fileName) {
            map[seedId] = fileName
          }
        }
        setImageMap(map)
      })
      .catch(() => {
        if (!cancelled) setImageMap({})
      })
    return () => {
      cancelled = true
    }
  }, [])

  const openBuyDialog = (item: GoodsItem) => {
    setSelectedGoods(item)
    setBuyAmount(1)
    setMessage("")
    setBuyDialogOpen(true)
  }

  const handleBuy = async () => {
    if (!selectedGoods) return

    setIsBuying(true)
    setMessage("")
    
    try {
      const res = await fetch('/api/shop/buy', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email,
          goodsId: selectedGoods.goodsId,
          count: buyAmount,
          price: selectedGoods.price
        })
      })
      const json = await res.json()
      
      if (json.success) {
        setMessage(`购买成功！获得 ${selectedGoods.name} x${buyAmount * selectedGoods.itemCount}`)
        setTimeout(() => {
          setBuyDialogOpen(false)
          fetchShop() // Refresh limits/stock if any
        }, 1500)
      } else {
        setMessage(`购买失败: ${json.error}`)
      }
    } catch (error) {
      console.error(error)
      setMessage("网络错误")
    } finally {
      setIsBuying(false)
    }
  }

  return (
    <div className="h-full flex flex-col gap-4">
      <div className="flex justify-between items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="搜索种子..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-8"
          />
        </div>
        <Button
          variant="outline"
          size="icon"
          onClick={fetchShop}
          disabled={isLoading}
          className={cn("transition-all", isLoading && "animate-spin")}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </div>

      <ScrollArea className="flex-1 rounded-md border p-4 bg-muted/20">
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
          {filteredGoods.map((item) => (
            <div
              key={item.goodsId}
              className={cn(
                "relative flex flex-col items-center justify-between p-3 rounded-lg border bg-card transition-all hover:shadow-md group",
                !item.unlocked && "opacity-60 grayscale"
              )}
            >
              {imageMap[item.itemId] && (
                <div className="w-full aspect-square rounded-md overflow-hidden bg-muted/30 mb-2">
                  <img
                    src={`/shop_plants_organized/${imageMap[item.itemId]}`}
                    alt={item.name}
                    className="w-full h-full object-contain"
                  />
                </div>
              )}
              <div className="text-center mb-2">
                <div className="font-medium text-sm truncate w-full" title={item.name}>{item.name}</div>
                <div className="text-xs text-muted-foreground">ID: {item.itemId}</div>
              </div>

              <div className="flex items-center gap-1 text-amber-500 font-bold text-sm mb-3">
                <Coins className="h-3 w-3" />
                {item.price}
              </div>

              <Button 
                size="sm" 
                variant={item.unlocked ? "default" : "secondary"}
                className="w-full h-7 text-xs"
                disabled={!item.unlocked}
                onClick={() => openBuyDialog(item)}
              >
                {item.unlocked ? "购买" : "未解锁"}
              </Button>
              
              {item.limitCount > 0 && (
                <div className="absolute top-1 right-1 text-[10px] bg-red-100 text-red-600 px-1 rounded">
                  限购 {item.boughtNum}/{item.limitCount}
                </div>
              )}
            </div>
          ))}
          {filteredGoods.length === 0 && !isLoading && (
            <div className="col-span-full text-center text-muted-foreground py-10">
              未找到商品
            </div>
          )}
        </div>
      </ScrollArea>

      <Dialog open={buyDialogOpen} onOpenChange={setBuyDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>购买 {selectedGoods?.name}</DialogTitle>
            <DialogDescription>
              单价: {selectedGoods?.price} 金币
            </DialogDescription>
          </DialogHeader>
          
          <div className="py-4 flex flex-col gap-4">
            <div className="flex items-center justify-center gap-4">
              <Button 
                variant="outline" 
                size="icon"
                onClick={() => setBuyAmount(Math.max(1, buyAmount - 1))}
              >
                -
              </Button>
              <div className="text-xl font-bold w-12 text-center">{buyAmount}</div>
              <Button 
                variant="outline" 
                size="icon"
                onClick={() => setBuyAmount(buyAmount + 1)}
              >
                +
              </Button>
            </div>
            
            <div className="text-center text-sm">
              总价: <span className="text-amber-600 font-bold text-lg">{(selectedGoods?.price || 0) * buyAmount}</span> 金币
            </div>
            
            {message && (
              <div className={cn(
                "p-2 rounded text-sm text-center",
                message.includes("成功") ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"
              )}>
                {message}
              </div>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setBuyDialogOpen(false)}>取消</Button>
            <Button onClick={handleBuy} disabled={isBuying}>
              {isBuying ? "购买中..." : "确认购买"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
