import React, { useState } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useQuery } from '@tanstack/react-query'
import { YongrenTabBarLayout } from '@d8d/yongren-shared-ui/components/YongrenTabBarLayout'
import { Navbar } from '@d8d/mini-shared-ui-components/components/navbar'
import { enterpriseOrderClient } from '../../api/enterpriseOrderClient'

// 视频类型枚举
type VideoAssetType = 'salary_video' | 'tax_video' | 'checkin_video' | 'work_video'

// 视频状态枚举
type VideoStatus = 'pending' | 'verified' | 'rejected'

// 视频分类标签
interface VideoCategoryTab {
  key: 'all' | VideoAssetType
  label: string
  count: number
}

// 视频卡片数据
interface VideoCardData {
  id: string
  title: string
  description: string
  assetType: VideoAssetType
  status: VideoStatus
  fileSize: number
  duration: number
  uploadedAt: string
  thumbnailUrl?: string
  fileUrl: string
  talentName?: string
  orderId?: string
}

// 视频统计数据
interface VideoStatisticsData {
  totalCount: number
  salaryVideoCount: number
  taxVideoCount: number
  checkinVideoCount: number
  workVideoCount: number
}

// 视频分类标签配置
const VIDEO_CATEGORIES: VideoCategoryTab[] = [
  { key: 'all', label: '全部视频', count: 0 },
  { key: 'salary_video', label: '工资视频', count: 0 },
  { key: 'tax_video', label: '个税视频', count: 0 },
  { key: 'checkin_video', label: '打卡视频', count: 0 }
]

// 视频状态标签配置
const VIDEO_STATUS_LABELS = {
  pending: { text: '待审核', className: 'bg-yellow-100 text-yellow-800' },
  verified: { text: '已验证', className: 'bg-green-100 text-green-800' },
  rejected: { text: '已拒绝', className: 'bg-red-100 text-red-800' }
} as const

// 视频类型标签配置
const VIDEO_TYPE_LABELS: Record<VideoAssetType, string> = {
  salary_video: '工资视频',
  tax_video: '个税视频',
  checkin_video: '打卡视频',
  work_video: '工作视频'
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)}KB`
  }
  return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
}

// 格式化时长
const formatDuration = (seconds: number): string => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 格式化日期
const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

const VideoManagement: React.FC = () => {
  const [activeCategory, setActiveCategory] = useState<'all' | VideoAssetType>('all')
  const [selectedVideos, setSelectedVideos] = useState<Set<string>>(new Set())

  // 获取视频统计数据
  const { data: statisticsData, isLoading: statisticsLoading } = useQuery({
    queryKey: ['video-statistics'],
    queryFn: async () => {
      const res = await enterpriseOrderClient['video-statistics'].$get({} as any)
      if (!res.ok) {
        throw new Error('获取视频统计数据失败')
      }
      return await res.json()
    }
  })

  // 获取视频列表
  const { data: videosData, isLoading: videosLoading } = useQuery({
    queryKey: ['company-videos', activeCategory],
    queryFn: async () => {
      const query = activeCategory !== 'all' ? { assetType: activeCategory as any } : {}
      const res = await enterpriseOrderClient['company-videos'].$get({ query } as any)
      if (!res.ok) {
        throw new Error('获取视频列表失败')
      }
      return await res.json()
    }
  })

  // 计算统计数据 - 从API响应中提取
  const statistics: VideoStatisticsData = statisticsData?.total !== undefined ? {
    totalCount: statisticsData.total || 0,
    salaryVideoCount: statisticsData.stats?.find((s: any) => s.assetType === 'salary_video')?.count || 0,
    taxVideoCount: statisticsData.stats?.find((s: any) => s.assetType === 'tax_video')?.count || 0,
    checkinVideoCount: statisticsData.stats?.find((s: any) => s.assetType === 'checkin_video')?.count || 0,
    workVideoCount: statisticsData.stats?.find((s: any) => s.assetType === 'work_video')?.count || 0
  } : {
    totalCount: 0,
    salaryVideoCount: 0,
    taxVideoCount: 0,
    checkinVideoCount: 0,
    workVideoCount: 0
  }

  // 更新分类标签的计数
  const categoryTabs: VideoCategoryTab[] = VIDEO_CATEGORIES.map(tab => {
    if (tab.key === 'all') {
      return { ...tab, count: statistics.totalCount }
    }
    const countMap: Record<string, number> = {
      salary_video: statistics.salaryVideoCount,
      tax_video: statistics.taxVideoCount,
      checkin_video: statistics.checkinVideoCount,
      work_video: statistics.workVideoCount
    }
    return { ...tab, count: countMap[tab.key] || 0 }
  })

  // 视频列表数据
  const videos: VideoCardData[] = videosData?.data?.map((video: any) => {
    const assetType: VideoAssetType = video.assetType || 'work_video'
    const title = video.talentName
      ? `${video.talentName} - ${VIDEO_TYPE_LABELS[assetType]}`
      : VIDEO_TYPE_LABELS[assetType]

    return {
      id: video.id,
      title,
      description: video.description || '视频文件',
      assetType,
      status: video.status || 'pending',
      fileSize: video.fileSize || 0,
      duration: video.duration || 0,
      uploadedAt: video.createdAt,
      thumbnailUrl: video.thumbnailUrl,
      fileUrl: video.fileUrl,
      talentName: video.talentName,
      orderId: video.orderId
    }
  }) || []

  // 选择/取消选择视频
  const toggleVideoSelection = (videoId: string) => {
    const newSelection = new Set(selectedVideos)
    if (newSelection.has(videoId)) {
      newSelection.delete(videoId)
    } else {
      newSelection.add(videoId)
    }
    setSelectedVideos(newSelection)
  }

  // 批量下载视频
  const handleBatchDownload = async () => {
    if (selectedVideos.size === 0) {
      Taro.showToast({
        title: '请先选择要下载的视频',
        icon: 'none'
      })
      return
    }

    try {
      Taro.showLoading({ title: '准备下载...' })

      const res = await enterpriseOrderClient['batch-download'].$post({
        json: {
          downloadScope: 'company' as any,
          fileIds: Array.from(selectedVideos)
        }
      } as any)

      if (!res.ok) {
        throw new Error('批量下载失败')
      }

      const result = await res.json()

      Taro.hideLoading()
      Taro.showToast({
        title: '下载任务已创建',
        icon: 'success'
      })

      // 清空选择
      setSelectedVideos(new Set())
    } catch (error) {
      Taro.hideLoading()
      Taro.showToast({
        title: '下载失败，请重试',
        icon: 'none'
      })
    }
  }

  // 播放视频
  const handlePlayVideo = (video: VideoCardData) => {
    Taro.showModal({
      title: '播放视频',
      content: `即将播放：${video.title}`,
      confirmText: '播放',
      success: (res) => {
        if (res.confirm && video.fileUrl) {
          // 在小程序中打开视频播放器
          Taro.openDocument({
            filePath: video.fileUrl,
            fileType: 'mp4' as any,
            success: () => {
              console.log('视频播放成功')
            },
            fail: (err) => {
              console.error('视频播放失败：', err)
              Taro.showToast({
                title: '播放失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  }

  // 下载视频
  const handleDownloadVideo = async (video: VideoCardData) => {
    try {
      Taro.showLoading({ title: '下载中...' })

      const res = await enterpriseOrderClient['batch-download'].$post({
        json: {
          downloadScope: 'company' as any,
          fileIds: [video.id]
        }
      } as any)

      if (!res.ok) {
        throw new Error('下载失败')
      }

      Taro.hideLoading()
      Taro.showToast({
        title: '下载成功',
        icon: 'success'
      })
    } catch (error) {
      Taro.hideLoading()
      Taro.showToast({
        title: '下载失败',
        icon: 'none'
      })
    }
  }

  // 分享视频
  const handleShareVideo = (video: VideoCardData) => {
    Taro.showShareMenu({
      withShareTicket: true
    })
  }

  // 加载状态
  if (videosLoading || statisticsLoading) {
    return (
      <YongrenTabBarLayout activeKey="settings">
        <ScrollView
          className="h-[calc(100%-60px)] overflow-y-auto px-4 pb-4 pt-0"
          scrollY
        >
          <Navbar
            title="视频管理"
            leftIcon=""
            leftText=""
            onClickLeft={() => {}}
            backgroundColor="bg-white"
            border={true}
            fixed={true}
            placeholder={true}
          />
          <View className="p-4">
            <Text>加载中...</Text>
          </View>
        </ScrollView>
      </YongrenTabBarLayout>
    )
  }

  return (
    <YongrenTabBarLayout activeKey="settings">
      <ScrollView
        className="h-[calc(100%-60px)] overflow-y-auto px-4 pb-4 pt-0"
        scrollY
      >
        {/* 导航栏 */}
        <Navbar
          title="视频管理"
          leftIcon=""
          leftText=""
          onClickLeft={() => {}}
          backgroundColor="bg-white"
          border={true}
          fixed={true}
          placeholder={true}
        />

        {/* 顶部信息区域 */}
        <View className="p-4 border-b border-gray-200">
          <View className="flex flex-col">
            <Text className="font-semibold text-gray-800">企业视频管理</Text>
            <Text className="text-sm text-gray-500">企业维度 - 视频资料查看</Text>
          </View>
          <View
            className="text-blue-500 text-sm mt-2"
            onClick={handleBatchDownload}
          >
            <Text>批量下载 ({selectedVideos.size})</Text>
          </View>
        </View>

        {/* 视频分类筛选区域 */}
        <View className="p-4 border-b border-gray-200">
          <View className="flex space-x-2 overflow-x-auto pb-2">
            {categoryTabs.map(tab => (
              <View
                key={tab.key}
                className={`text-xs px-3 py-1 rounded-full whitespace-nowrap ${
                  activeCategory === tab.key
                    ? 'bg-blue-100 text-blue-800'
                    : 'bg-gray-100 text-gray-800'
                }`}
                onClick={() => setActiveCategory(tab.key)}
              >
                <Text>{tab.label} ({tab.count})</Text>
              </View>
            ))}
          </View>
        </View>

        {/* 视频列表标题区域 */}
        <View className="p-4">
          <View className="flex justify-between items-center mb-4">
            <Text className="font-semibold text-gray-700">
              视频列表 ({videos.length})
            </Text>
            <View className="flex space-x-2">
              <Text className="text-gray-500">排序</Text>
              <Text className="text-gray-500">筛选</Text>
            </View>
          </View>

          {/* 视频列表 */}
          {videos.length === 0 ? (
            <View className="p-8 text-center">
              <Text className="text-gray-500">暂无视频数据</Text>
            </View>
          ) : (
            <View className="space-y-4">
              {videos.map(video => {
                const statusLabel = VIDEO_STATUS_LABELS[video.status]
                const isSelected = selectedVideos.has(video.id)

                return (
                  <View
                    key={video.id}
                    className="bg-white p-4 rounded-lg border border-gray-200"
                  >
                    {/* 视频卡片头部 */}
                    <View className="flex justify-between items-start mb-3">
                      <View className="flex flex-col">
                        <Text className="font-semibold text-gray-800">
                          {video.title}
                        </Text>
                        <Text className="text-xs text-gray-500">
                          {formatDate(video.uploadedAt)} 上传
                        </Text>
                      </View>
                      <View className={`text-xs px-2 py-1 rounded-full ${statusLabel.className}`}>
                        <Text>{statusLabel.text}</Text>
                      </View>
                    </View>

                    {/* 视频内容区域 */}
                    <View className="flex items-center mb-3">
                      <View className="w-16 h-16 bg-gray-200 rounded-lg flex items-center justify-center mr-3">
                        <Text className="text-gray-500">▶</Text>
                      </View>
                      <View className="flex-1 flex flex-col">
                        <Text className="text-sm text-gray-700">
                          {video.description}
                        </Text>
                        <Text className="text-xs text-gray-500">
                          时长: {formatDuration(video.duration)} · 大小: {formatFileSize(video.fileSize)}
                        </Text>
                      </View>
                    </View>

                    {/* 操作按钮区域 */}
                    <View className="flex justify-between text-sm">
                      <View
                        className="text-blue-500"
                        onClick={() => handlePlayVideo(video)}
                      >
                        <Text>播放</Text>
                      </View>
                      <View
                        className="text-green-500"
                        onClick={() => handleDownloadVideo(video)}
                      >
                        <Text>下载</Text>
                      </View>
                      <View
                        className="text-gray-500"
                        onClick={() => handleShareVideo(video)}
                      >
                        <Text>分享</Text>
                      </View>
                      <View
                        className={`${isSelected ? 'text-blue-500' : 'text-gray-400'}`}
                        onClick={() => toggleVideoSelection(video.id)}
                      >
                        <Text>{isSelected ? '已选择' : '选择'}</Text>
                      </View>
                    </View>
                  </View>
                )
              })}
            </View>
          )}
        </View>
      </ScrollView>
    </YongrenTabBarLayout>
  )
}

export default VideoManagement
