import { useState } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { TabBarLayout } from '@/layouts/tab-bar-layout'
import { useAuth } from '@/utils/auth'
import { cn } from '@/utils/cn'
import { Button } from '@/components/ui/button'
import { Navbar } from '@/components/ui/navbar'
import { AvatarUpload } from '@/components/ui/avatar-upload'
import { type UploadResult } from '@/utils/minio'
import TDesignUserCenterCard from '@/components/tdesign/user-center-card'
import TDesignOrderGroup from '@/components/tdesign/order-group'
import TDesignCellGroup from '@/components/tdesign/cell-group'
import TDesignCell from '@/components/tdesign/cell'
import TDesignPopup from '@/components/tdesign/popup'
import TDesignIcon from '@/components/tdesign/icon'
import './index.css'

const ProfilePage: React.FC = () => {
  const { user: userProfile, logout, isLoading: loading, updateUser } = useAuth()
  const [updatingAvatar, setUpdatingAvatar] = useState(false)
  const [showCustomerService, setShowCustomerService] = useState(false)

  const handleLogout = async () => {
    try {
      Taro.showModal({
        title: '退出登录',
        content: '确定要退出登录吗？',
        success: async (res) => {
          if (res.confirm) {
            Taro.showLoading({ title: '退出中...' })
            await logout()
            Taro.hideLoading()
            Taro.showToast({
              title: '已退出登录',
              icon: 'success',
              duration: 1500
            })
            setTimeout(() => {
              Taro.reLaunch({ url: '/pages/index/index' })
            }, 1500)
          }
        }
      })
    } catch (error) {
      Taro.hideLoading()
      Taro.showToast({
        title: '退出失败，请重试',
        icon: 'none'
      })
    }
  }

  const handleAvatarUpload = async (result: UploadResult) => {
    try {
      setUpdatingAvatar(true)
      Taro.showLoading({ title: '更新头像...' })
      
      // 这里应该调用更新用户头像的API
      // 假设有一个更新用户信息的API
      console.log('头像上传成功:', result)
      
      // 更新本地用户数据
      if (userProfile) {
        const updatedUser = {
          ...userProfile,
          avatarFileId: result.fileId
        }
        updateUser(updatedUser)
      }
        
        Taro.hideLoading()
        Taro.showToast({
          title: '头像更新成功',
          icon: 'success'
        })
    } catch (error) {
      console.error('更新头像失败:', error)
      Taro.hideLoading()
      Taro.showToast({
        title: '更新头像失败',
        icon: 'none'
      })
    } finally {
      setUpdatingAvatar(false)
    }
  }

  const handleAvatarUploadError = (error: Error) => {
    console.error('头像上传失败:', error)
    Taro.showToast({
      title: '上传失败，请重试',
      icon: 'none'
    })
  }

  const handleEditProfile = () => {
    Taro.showToast({
      title: '功能开发中...',
      icon: 'none'
    })
  }

  const handleSettings = () => {
    Taro.showToast({
      title: '功能开发中...',
      icon: 'none'
    })
  }

  const handleCustomerService = () => {
    setShowCustomerService(true)
  }

  const handleCloseCustomerService = () => {
    setShowCustomerService(false)
  }

  // 跳转到订单列表页面
  const handleNavigateToOrderList = (tabKey?: string) => {
    console.debug('跳转到订单列表页面，tabKey:', tabKey)
    const url = tabKey ? `/pages/order-list/index?tab=${tabKey}` : '/pages/order-list/index'
    console.debug('跳转URL:', url)
    Taro.navigateTo({ url })
  }

  const handleCallCustomerService = () => {
    Taro.makePhoneCall({
      phoneNumber: '057985101558'
    })
  }

  // 订单状态数据
  const orderTagInfos = [
    { title: '待付款', iconName: 'clock', orderNum: 0, tabKey: 'unpaid' },
    { title: '待发货', iconName: 'package', orderNum: 0, tabKey: 'unshipped' },
    { title: '待收货', iconName: 'truck', orderNum: 0, tabKey: 'shipped' },
    { title: '待评价', iconName: 'star', orderNum: 0, tabKey: 'completed' }
  ]

  // 菜单数据 - 按照 tcb-shop-demo 的结构
  const menuData = [
    [
      { title: '收货地址', icon: 'location', type: 'address' },
      { title: '联系客服', icon: 'service', type: 'service' }
    ],
    // [
    //   { title: '关于我们', icon: 'info-circle', type: 'about' },
    //   { title: '隐私政策', icon: 'shield-check', type: 'privacy' }
    // ]
  ]

  const handleCellClick = (type: string) => {
    switch (type) {
      case 'address':
        Taro.navigateTo({ url: '/pages/address-manage/index' })
        break
      case 'service':
        handleCustomerService()
        break
      // case 'about':
      //   Taro.showToast({ title: '关于我们功能开发中...', icon: 'none' })
      //   break
      // case 'privacy':
      //   Taro.showToast({ title: '隐私政策功能开发中...', icon: 'none' })
      //   break
      default:
        Taro.showToast({ title: '功能开发中...', icon: 'none' })
    }
  }

  if (loading) {
    return (
      <TabBarLayout activeKey="profile">
        <View className="flex-1 flex items-center justify-center">
          <View className="i-heroicons-arrow-path-20-solid animate-spin w-8 h-8 text-blue-500" />
        </View>
      </TabBarLayout>
    )
  }

  if (!userProfile) {
    return (
      <TabBarLayout activeKey="profile">
        <Navbar
          title="个人中心"
          leftIcon=""
        />
        <View className="flex-1 flex flex-col items-center justify-center">
          <View className="flex flex-col items-center">
            <View className="i-heroicons-exclamation-circle-20-solid w-12 h-12 text-gray-400 mx-auto mb-4" />
            <Text className="text-gray-600 mb-4">请先登录</Text>
            <Button
              variant="default"
              size="lg"
              onClick={() => Taro.navigateTo({ url: '/pages/login/index' })}
            >
              去登录
            </Button>
          </View>
        </View>
      </TabBarLayout>
    )
  }

  return (
    <TabBarLayout activeKey="profile">
      <Navbar
        title="个人中心"
        leftIcon=""
        onClickLeft={() => Taro.navigateBack()}
        rightIcon=""
        onClickRight={() => {}}
      />
      {/* 用户中心卡片 - 使用固定定位 */}
      <TDesignUserCenterCard
        avatar={userProfile.avatarFile?.fullUrl}
        nickname={userProfile.username}
        isLoggedIn={!!userProfile}
        onUserEdit={handleEditProfile}
        className="tdesign-user-center-card-profile"
      />

      {/* 内容区域 - 使用 margin-top 定位 */}
      <ScrollView className="flex-1 bg-gray-50 tdesign-user-center-content z-10">
        {/* 订单状态卡片 */}
        <View className="px-4 pt-4">
          <TDesignOrderGroup
            orderTagInfos={orderTagInfos}
            title="我的订单"
            desc="全部订单"
            onTopClick={() => handleNavigateToOrderList()}
            onItemClick={(item) => handleNavigateToOrderList(item.tabKey)}
          />
        </View>

        {/* 功能菜单 */}
        <View className="px-4 pt-4">
          {menuData.map((group, groupIndex) => (
            <View key={groupIndex} className="mb-4">
              <TDesignCellGroup>
                {group.map((item, itemIndex) => (
                  <TDesignCell
                    key={itemIndex}
                    title={item.title}
                    arrow
                    bordered={itemIndex < group.length - 1}
                    onClick={() => handleCellClick(item.type)}
                    noteSlot={
                      <TDesignIcon
                        name={item.icon}
                        size="48rpx"
                        color="#6a6a6a"
                      />
                    }
                  />
                ))}
              </TDesignCellGroup>
            </View>
          ))}
        </View>

        {/* 退出登录按钮 */}
        <View className="px-4 pt-6 pb-8">
          <Button
            variant="destructive"
            size="lg"
            className="w-full"
            onClick={handleLogout}
          >
            <View className="flex items-center justify-center">
              <View className="i-heroicons-arrow-left-on-rectangle-20-solid w-5 h-5 mr-2" />
              退出登录
            </View>
          </Button>
        </View>

        {/* 版本信息 */}
        <View className="pb-8">
          <Text className="text-center text-xs text-gray-400">
            v0.0.5 - 小程序版
          </Text>
        </View>
      </ScrollView>
      {/* 客服弹窗 */}
      <TDesignPopup
        visible={showCustomerService}
        placement="bottom"
        onVisibleChange={(visible) => setShowCustomerService(visible)}
        onClose={handleCloseCustomerService}
      >
        <View className="popup-content">
          <View className="popup-title border-bottom-1px">
            服务时间: 9:00-18:00
          </View>
          <View
            className="popup-phone border-bottom-1px"
            onClick={handleCallCustomerService}
          >
            电话客服
          </View>
          <button
            className="popup-phone border-bottom-1px online"
            open-type="contact"
          >
            在线客服
          </button>
          <View
            className="popup-close"
            onClick={handleCloseCustomerService}
          >
            取消
          </View>
        </View>
      </TDesignPopup>
    </TabBarLayout>
  )
}

export default ProfilePage