<template>
  <custom-dialog :visible.sync="dialogVisible" title="我的农场" @close="onClose">
    <view class="farm-container">
      <view class="farm-grid">
        <view v-for="(plot, index) in plots" :key="index" class="farm-plot" @click="onPlotClick(index)">
          <view class="plot-content" :class="getPlotClass(plot)">
            <view v-if="plot.crop" class="crop-stage">
              <image :src="getCropImage(plot)" mode="aspectFit" class="crop-image"></image>
            </view>
            <view v-if="plot.weeds" class="weeds"></view>
            <view v-if="plot.needsWater" class="water-indicator"></view>
          </view>
        </view>
      </view>
      
      <view class="action-panel">
        <view class="action-buttons">
          <button @click="selectAction('plant')" :disabled="!canPlant">播种</button>
          <button @click="selectAction('water')" :disabled="!canWater">浇水</button>
          <button @click="selectAction('fertilize')" :disabled="!canFertilize">施肥</button>
          <button @click="selectAction('weed')" :disabled="!canWeed">除草</button>
          <button @click="selectAction('harvest')" :disabled="!canHarvest">收获</button>
        </view>
        <view class="selected-plot-info" v-if="selectedPlot !== null">
          <text>状态: {{ getPlotStatus(plots[selectedPlot]) }}</text>
          <text v-if="plots[selectedPlot].crop">作物: {{ plots[selectedPlot].crop.name }}</text>
          <text v-if="plots[selectedPlot].crop">生长进度: {{ getGrowthProgress(plots[selectedPlot]) }}%</text>
        </view>
      </view>
    </view>
  </custom-dialog>
</template>

<script>
import CustomDialog from '@/components/CustomDialog/CustomDialog.vue'

const CROPS = {
  carrot: {
    name: '胡萝卜',
    growthTime: 30, // minutes
    stages: ['/static/crops/carrot_stage1.png', '/static/crops/carrot_stage2.png', '/static/crops/carrot_stage3.png'],
    value: 100
  },
  tomato: {
    name: '番茄',
    growthTime: 60,
    stages: ['/static/crops/tomato_stage1.png', '/static/crops/tomato_stage2.png', '/static/crops/tomato_stage3.png'],
    value: 200
  }
}

export default {
  name: 'FarmDialog',
  components: {
    CustomDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      plots: Array(12).fill().map(() => ({
        crop: null,
        plantedAt: null,
        watered: false,
        fertilized: false,
        weeds: false,
        needsWater: false
      })),
      selectedPlot: null,
      selectedAction: null,
      growthTimer: null
    }
  },
  computed: {
    canPlant() {
      return this.selectedPlot !== null && !this.plots[this.selectedPlot].crop
    },
    canWater() {
      return this.selectedPlot !== null && 
             this.plots[this.selectedPlot].crop && 
             !this.plots[this.selectedPlot].watered
    },
    canFertilize() {
      return this.selectedPlot !== null && 
             this.plots[this.selectedPlot].crop && 
             !this.plots[this.selectedPlot].fertilized
    },
    canWeed() {
      return this.selectedPlot !== null && 
             this.plots[this.selectedPlot].weeds
    },
    canHarvest() {
      return this.selectedPlot !== null && 
             this.plots[this.selectedPlot].crop && 
             this.isCropReady(this.plots[this.selectedPlot])
    }
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal
      if (newVal) {
        this.startGrowthTimer()
      } else {
        this.stopGrowthTimer()
      }
    }
  },
  methods: {
    onClose() {
      this.$emit('update:visible', false)
    },
    onPlotClick(index) {
      this.selectedPlot = index
      if (this.selectedAction) {
        this.performAction(index)
      }
    },
    selectAction(action) {
      this.selectedAction = action
    },
    performAction(plotIndex) {
      const plot = this.plots[plotIndex]
      
      switch (this.selectedAction) {
        case 'plant':
          if (this.canPlant) {
            plot.crop = { ...CROPS.carrot }
            plot.plantedAt = Date.now()
            plot.watered = false
            plot.fertilized = false
            plot.weeds = false
            plot.needsWater = true
          }
          break
        case 'water':
          if (this.canWater) {
            plot.watered = true
            plot.needsWater = false
          }
          break
        case 'fertilize':
          if (this.canFertilize) {
            plot.fertilized = true
          }
          break
        case 'weed':
          if (this.canWeed) {
            plot.weeds = false
          }
          break
        case 'harvest':
          if (this.canHarvest) {
            // TODO: Add harvested items to inventory
            plot.crop = null
            plot.plantedAt = null
            plot.watered = false
            plot.fertilized = false
            plot.weeds = false
            plot.needsWater = false
          }
          break
      }
      
      this.selectedAction = null
    },
    getPlotClass(plot) {
      return {
        'has-crop': plot.crop,
        'needs-water': plot.needsWater,
        'has-weeds': plot.weeds
      }
    },
    getCropImage(plot) {
      if (!plot.crop) return ''
      const growthStage = this.getGrowthStage(plot)
      return plot.crop.stages[growthStage]
    },
    getGrowthStage(plot) {
      if (!plot.crop || !plot.plantedAt) return 0
      const growthProgress = this.getGrowthProgress(plot)
      if (growthProgress >= 100) return 2
      if (growthProgress >= 50) return 1
      return 0
    },
    getGrowthProgress(plot) {
      if (!plot.crop || !plot.plantedAt) return 0
      const elapsed = (Date.now() - plot.plantedAt) / 1000 / 60 // minutes
      const progress = (elapsed / plot.crop.growthTime) * 100
      return Math.min(100, Math.floor(progress))
    },
    isCropReady(plot) {
      return this.getGrowthProgress(plot) >= 100
    },
    getPlotStatus(plot) {
      if (!plot.crop) return '空地'
      if (plot.weeds) return '需要除草'
      if (plot.needsWater) return '需要浇水'
      if (this.isCropReady(plot)) return '可以收获'
      return '生长中'
    },
    startGrowthTimer() {
      this.growthTimer = setInterval(() => {
        this.plots.forEach(plot => {
          if (plot.crop && !plot.watered) {
            plot.needsWater = true
          }
          if (plot.crop && Math.random() < 0.1) { // 10% chance to spawn weeds
            plot.weeds = true
          }
        })
      }, 60000) // Check every minute
    },
    stopGrowthTimer() {
      if (this.growthTimer) {
        clearInterval(this.growthTimer)
        this.growthTimer = null
      }
    }
  },
  beforeDestroy() {
    this.stopGrowthTimer()
  }
}
</script>

<style lang="scss">
@import './FarmDialog.scss';
</style> 