/**
 * 卡券使用页面
 */
import { View, Text, Input } from '@tarojs/components'
import Taro, { useLoad, useRouter } from '@tarojs/taro'
import { useState } from 'react'
import { Popup, Button } from '@taroify/core'
import { Arrow, Search as SearchIcon } from '@taroify/icons'
import './index.scss'

// 门店数据接口
interface Store {
  id: number
  name: string
  address: string
  distance: string
}

// 城市选项
const cityOptions = [
  { title: '选城市', value: 'all' },
  { title: '北京', value: 'beijing' },
  { title: '上海', value: 'shanghai' },
  { title: '广州', value: 'guangzhou' },
  { title: '深圳', value: 'shenzhen' },
]

const CouponUse = () => {
  const router = useRouter()
  const { couponId } = router.params
  
  // 卡券信息（从路由参数或上一页面传递，实际应根据couponId获取）
  const [couponInfo] = useState({
    title: '豪华自助台球厅20分钟通用券（体验券）',
    duration: '20',
    validPeriod: '2025.10.01 - 2025.10.07（有效7天）',
    useMethod: '自动抵扣，单次使用',
    partialUsable: true, // 部分门店不可用
  })

  // 城市选择
  const [selectedCity, setSelectedCity] = useState('all')
  const [showCityPicker, setShowCityPicker] = useState(false)
  
  // 搜索关键词
  const [searchValue, setSearchValue] = useState('')
  
  // 已选门店
  const [selectedStoreId, setSelectedStoreId] = useState<number | null>(1)
  
  // 门店列表（模拟数据）
  const [storeList] = useState<Store[]>([
    {
      id: 1,
      name: '北京黑八大师联盟球厅店',
      address: '北京市XXX区XXX街道XXXXXXXXXXXXXXXXXXXXXXX路19号606',
      distance: '0.05km'
    },
    {
      id: 2,
      name: '北京晶彩桌球世界店',
      address: '北京市XXX区XXX街道XXX路19号606',
      distance: '0.1km'
    },
    {
      id: 3,
      name: '北京球坛风云店',
      address: '北京市XXX区XXXXXXXXXXX街道XXX路19号606',
      distance: '0.2km'
    },
  ])

  useLoad(() => {
    console.log('卡券使用页面加载')
    Taro.setNavigationBarTitle({ title: '' })
  })

  // 获取已选门店名称
  const getSelectedStoreName = () => {
    const store = storeList.find(s => s.id === selectedStoreId)
    return store ? store.name : ''
  }

  // 选择门店
  const handleSelectStore = (storeId: number) => {
    setSelectedStoreId(storeId)
  }

  // 搜索
  const handleSearch = () => {
    console.log('搜索', searchValue)
    Taro.showToast({
      title: `搜索: ${searchValue}`,
      icon: 'none'
    })
  }

  // 获取当前城市名称
  const getCityName = () => {
    const city = cityOptions.find(c => c.value === selectedCity)
    return city ? city.title : '选城市'
  }

  // 选择城市
  const handleSelectCity = (value: string) => {
    setSelectedCity(value)
    setShowCityPicker(false)
  }

  // 去使用
  const handleUse = () => {
    if (!selectedStoreId) {
      Taro.showToast({
        title: '请选择门店',
        icon: 'none'
      })
      return
    }
    console.log('使用卡券', selectedStoreId)
    Taro.showToast({
      title: '卡券使用成功',
      icon: 'success'
    })
  }

  return (
    <View className="coupon_use_page">
      {/* 卡券信息区域 */}
      <View className="coupon_info_section">
        <View className="coupon_header">
          <View className="coupon_title_area">
            <Text className="coupon_title">{couponInfo.title}</Text>
            <Text className="coupon_valid">有效期限：{couponInfo.validPeriod}</Text>
            <Text className="coupon_method">使用方法：{couponInfo.useMethod}</Text>
          </View>
          <View className="coupon_duration_area">
            <Text className="duration_value">{couponInfo.duration}</Text>
            <Text className="duration_unit">分钟</Text>
          </View>
        </View>
      </View>

    <div style={{height: '1rpx', width:'100%', backgroundColor: '#45454C', margin: '0 24rpx'}}></div>

      {/* 选择门店区域 */}
      <View className="store_select_section">
        <View className="section_title_row">
          <Text className="section_title">选择门店</Text>
          {couponInfo.partialUsable && (
            <Text className="partial_tip">（部分门店不可用）</Text>
          )}
        </View>
        <Text className="selected_store">已选门店：{getSelectedStoreName()}</Text>
        
        {/* 搜索栏 */}
        <View className="search_row">
          <View className="city_dropdown" onClick={() => setShowCityPicker(true)}>
            <Text className="city_text">{getCityName()}</Text>
            <Arrow className="city_arrow" />
          </View>
          <View className="search_input">
            <Input
              className="search_field"
              value={searchValue}
              placeholder="搜索门店名称/地址"
              placeholderClass="search_placeholder"
              onInput={(e) => setSearchValue(e.detail.value)}
              onConfirm={handleSearch}
            />
            <SearchIcon className="search_icon" onClick={handleSearch} />
          </View>
        </View>

        {/* 城市选择弹窗 */}
        <Popup
          open={showCityPicker}
          placement="bottom"
          rounded
          onClose={() => setShowCityPicker(false)}
        >
          <View className="city_picker">
            <View className="picker_header">
              <Text className="picker_title">选择城市</Text>
            </View>
            <View className="picker_options">
              {cityOptions.map((city) => (
                <View 
                  key={city.value}
                  className={`picker_option ${selectedCity === city.value ? 'selected' : ''}`}
                  onClick={() => handleSelectCity(city.value)}
                >
                  <Text className="option_text">{city.title}</Text>
                  {selectedCity === city.value && <Text className="check_icon">✓</Text>}
                </View>
              ))}
            </View>
          </View>
        </Popup>
      </View>

      {/* 门店列表 */}
      <View className="store_list">
        {storeList.map((store) => (
          <View 
            key={store.id}
            className={`store_card ${selectedStoreId === store.id ? 'selected' : ''}`}
            onClick={() => handleSelectStore(store.id)}
          >
            <View className="store_info">
              <Text className="store_name">{store.name}</Text>
              <Text className="store_address">{store.address}</Text>
            </View>
            <View className="store_distance">
              <Text className="distance_text">距离{store.distance}</Text>
            </View>
          </View>
        ))}
      </View>

      {/* 到底提示 */}
      <Text className="end_tip">到底了~</Text>

      {/* 页脚按钮 */}
      <View className="footer">
        <Button 
          className="use_btn"
          onClick={handleUse}
        >
          去使用
        </Button>
      </View>
    </View>
  )
}

export default CouponUse
