import { useEffect, useState } from "react"
import { Sprout, Lock, Droplets, Bug, Skull, Shovel, Flower, Ban, Hand } from "lucide-react"
import { cn } from "@/lib/utils"

export interface LandData {
  id: number
  type: 'locked' | 'empty' | 'planted'
  status?: 'growing' | 'mature' | 'dead'
  plantName?: string
  plantId?: number
  phase?: number
  phaseName?: string
  fertilized?: boolean
  needs?: {
    water: boolean
    weed: boolean
    bug: boolean
  }
  canSteal?: boolean
  couldUnlock?: boolean
  unlockCondition?: {
    needLevel: number
    needGold: number
  }
}

interface FarmGridProps {
  lands: LandData[]
  isLoading?: boolean
  onLandClick?: (land: LandData) => void
  onLandUnlock?: (land: LandData) => void
  selectionEnabled?: boolean
  selectedLandIds?: number[]
  userLevel?: number
  userGold?: number
  unlockingLandIds?: number[]
}

export function FarmGrid({ lands, isLoading = false, onLandClick, onLandUnlock, selectionEnabled = false, selectedLandIds = [], userLevel = 0, userGold = 0, unlockingLandIds = [] }: FarmGridProps) {
  const [plantImageMap, setPlantImageMap] = useState<Record<number, string>>({})
  
  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) {
          setPlantImageMap({})
          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 plantId = Number(parts[2])
          const fileName = parts[4]
          if (!Number.isNaN(plantId) && fileName) {
            map[plantId] = fileName
          }
        }
        setPlantImageMap(map)
      })
      .catch(() => {
        if (!cancelled) setPlantImageMap({})
      })
    return () => {
      cancelled = true
    }
  }, [])

  // Generate default 18 slots if lands is empty (initial state)
  const displayLands = lands.length > 0 ? lands : Array.from({ length: 18 }, (_, i) => ({
    id: i + 1,
    type: 'locked' as const
  }))

  if (isLoading && lands.length === 0) {
    return (
      <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 gap-4">
        {Array.from({ length: 18 }).map((_, i) => (
          <div key={i} className="aspect-square rounded-3xl bg-white/20 animate-pulse border-2 border-dashed border-white/30" />
        ))}
      </div>
    )
  }

  return (
    <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 gap-4 p-4 bg-stone-100/50 rounded-[2rem] border border-stone-200/50 shadow-inner">
      {displayLands.map((land) => (
        <LandCard
          key={land.id}
          land={land}
          plantImageMap={plantImageMap}
          onClick={() => onLandClick?.(land)}
          onUnlock={() => onLandUnlock?.(land)}
          userLevel={userLevel}
          userGold={userGold}
          isUnlocking={unlockingLandIds.includes(land.id)}
          selected={selectionEnabled && selectedLandIds.includes(land.id)}
          selectionEnabled={selectionEnabled}
        />
      ))}
    </div>
  )
}

function LandCard({ land, plantImageMap, onClick, onUnlock, userLevel, userGold, isUnlocking, selected, selectionEnabled }: { land: LandData, plantImageMap: Record<number, string>, onClick?: () => void, onUnlock?: () => void, userLevel: number, userGold: number, isUnlocking: boolean, selected?: boolean, selectionEnabled?: boolean }) {
  const isLocked = land.type === 'locked'
  const isEmpty = land.type === 'empty'
  const isPlanted = land.type === 'planted'
  
  const isDead = land.status === 'dead'
  const isMature = land.status === 'mature'
  const isGrowing = land.status === 'growing'
  const isFertilized = land.fertilized === true
  const plantImage = land.plantId ? plantImageMap[land.plantId] : undefined
  const needLevel = land.unlockCondition?.needLevel ?? 0
  const needGold = land.unlockCondition?.needGold ?? 0
  const canUnlock = isLocked && !!land.couldUnlock && userLevel >= needLevel && userGold >= needGold

  return (
    <div 
      onClick={!isLocked ? onClick : undefined}
      className={cn(
      "aspect-square rounded-2xl relative transition-all duration-300 group select-none",
      "flex flex-col items-center justify-center p-2",
      "border-2",
      selected && "ring-2 ring-rose-400 border-rose-200",
      isLocked && "bg-slate-100 border-slate-200 text-slate-300",
      isEmpty && "bg-[#F3E5D0] border-[#E6D5BC] text-[#C4B29B] hover:border-[#D4C3AA]",
      isPlanted && isGrowing && "bg-green-50 border-green-100 text-green-600",
      isPlanted && isMature && "bg-amber-50 border-amber-100 text-amber-600 shadow-[0_4px_12px_-4px_rgba(251,191,36,0.4)]",
      isPlanted && isDead && "bg-purple-50 border-purple-100 text-purple-400",
      !isLocked && "hover:scale-[1.02] hover:shadow-sm cursor-pointer active:scale-[0.98]",
      selectionEnabled && !isLocked && "hover:ring-2 hover:ring-rose-200"
    )}>
      
      {/* Status Badge (ID) */}
      <span className={cn(
        "absolute top-2 left-2 text-[10px] font-bold px-1.5 py-0.5 rounded-full",
        isLocked ? "bg-slate-200 text-slate-400" : "bg-white/60 backdrop-blur-sm text-slate-500"
      )}>
        #{land.id}
      </span>
      {canUnlock && (
        <div className="absolute inset-x-0 bottom-2 flex items-center justify-center px-2">
          <button
            className={cn(
              "px-3 py-1 rounded-full text-[11px] font-bold bg-emerald-500 text-white shadow-sm",
              isUnlocking ? "opacity-70 cursor-not-allowed" : "hover:bg-emerald-600"
            )}
            onClick={(e) => {
              e.stopPropagation()
              if (!isUnlocking) onUnlock?.()
            }}
            disabled={isUnlocking}
          >
            {isUnlocking ? "解锁中" : `解锁(${needGold})`}
          </button>
        </div>
      )}

      {/* Main Icon */}
      <div className="flex flex-col items-center gap-1 z-10">
        {isLocked && <Lock className="h-6 w-6 opacity-50" />}
        {isEmpty && <Shovel className="h-6 w-6 opacity-50" />}
        
        {isPlanted && (
          <>
            {plantImage ? (
              <img
                src={`/shop_plants_organized/${plantImage}`}
                alt={land.plantName || '作物'}
                className={cn(
                  "h-12 w-12 object-contain",
                  isDead && "grayscale opacity-60",
                  isMature && "animate-bounce"
                )}
                style={isMature ? { animationDuration: '3s' } : undefined}
              />
            ) : (
              <>
                {isDead && <Skull className="h-8 w-8 animate-pulse" />}
                {isGrowing && <Sprout className="h-8 w-8" />}
                {isMature && <Flower className="h-8 w-8 animate-bounce" style={{ animationDuration: '3s' }} />}
              </>
            )}
            <span className={cn(
              "text-[11px] font-semibold text-center line-clamp-1 max-w-full px-1",
              isDead && "text-purple-500",
              isMature && "text-amber-600",
              isGrowing && "text-green-600"
            )}>
              {land.plantName || '等待中...'}
            </span>
            <span className={cn(
              "text-[10px] font-medium",
              isFertilized ? "text-emerald-600" : "text-slate-500"
            )}>
              {`${land.phaseName || '未知'}/${isFertilized ? '已施肥' : '未施肥'}`}
            </span>
          </>
        )}
      </div>

      {/* Action Indicators */}
      {isPlanted && !isDead && land.needs && (
        <div className="absolute -top-1 -right-1 flex flex-col gap-1">
          {land.needs.water && (
            <div className="h-6 w-6 rounded-full bg-blue-400 text-white flex items-center justify-center shadow-sm border-2 border-white animate-bounce">
              <Droplets className="h-3 w-3" />
            </div>
          )}
          {land.needs.bug && (
            <div className="h-6 w-6 rounded-full bg-rose-400 text-white flex items-center justify-center shadow-sm border-2 border-white animate-pulse">
              <Bug className="h-3 w-3" />
            </div>
          )}
          {land.needs.weed && (
            <div className="h-6 w-6 rounded-full bg-purple-400 text-white flex items-center justify-center shadow-sm border-2 border-white">
              <Ban className="h-3 w-3" />
            </div>
          )}
        </div>
      )}

      {/* Steal Indicator */}
      {land.canSteal && (
        <div className="absolute top-1 right-1 h-6 w-6 rounded-full bg-orange-400 text-white flex items-center justify-center shadow-sm border-2 border-white animate-bounce z-20">
            <Hand className="h-3 w-3" />
        </div>
      )}

      {/* Background decoration for mature */}
      {isMature && (
        <div className="absolute inset-0 bg-gradient-to-br from-amber-100/0 via-amber-100/0 to-amber-200/30 rounded-2xl" />
      )}
    </div>
  )
}
