import React, { useState, useEffect } from 'react'
import { View, Text, Input, Button, Textarea } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useReachBottom } from '@tarojs/taro'
import { pageMyApply, createApply } from '@/api/developer/developer'
import type { Apply, ApplyParam, ApplyStatus } from '@/types/developer'
import './apply.scss'

// 状态配置
const STATUS_CONFIG: Record<ApplyStatus, { label: string; color: string; bgColor: string }> = {
  pending: { label: '待审核', color: '#faad14', bgColor: '#fffbe6' },
  approved: { label: '已通过', color: '#52c41a', bgColor: '#f6ffed' },
  rejected: { label: '已拒绝', color: '#ff4d4f', bgColor: '#fff1f0' },
}

const DeveloperApplyPage: React.FC = () => {
  const [tab, setTab] = useState<'apply' | 'record'>('apply')
  const [loading, setLoading] = useState(false)
  const [refreshing, setRefreshing] = useState(false)
  const [list, setList] = useState<Apply[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)

  // 申请表单
  const [form, setForm] = useState({
    realName: '',
    phone: '',
    email: '',
    company: '',
    position: '',
    experience: '',
  })
  const [submitting, setSubmitting] = useState(false)
  const [agreementChecked, setAgreementChecked] = useState(false)

  // 加载申请记录
  const loadData = async (pageNum: number = 1, isRefresh = false) => {
    if (loading) return
    setLoading(true)
    if (isRefresh) setRefreshing(true)

    try {
      const params: ApplyParam = { page: pageNum, limit: 20 }
      const data = await pageMyApply(params)

      if (pageNum === 1) {
        setList(data?.records || [])
      } else {
        setList(prev => [...prev, ...(data?.records || [])])
      }

      const total = data?.total || 0
      const records = data?.records || []
      setHasMore(records.length > 0 && (pageNum * 20) < total)
      setPage(pageNum)
    } catch (err) {
      console.error('加载失败', err)
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

  useEffect(() => {
    if (tab === 'record') {
      loadData()
    }
  }, [tab])

  // 提交申请
  const handleSubmit = async () => {
    if (!form.realName.trim()) {
      Taro.showToast({ title: '请输入真实姓名', icon: 'none' })
      return
    }
    if (!form.phone.trim()) {
      Taro.showToast({ title: '请输入手机号码', icon: 'none' })
      return
    }

    // 检查隐私协议是否同意
    if (!agreementChecked) {
      Taro.showToast({
        title: '请先同意服务协议和隐私政策',
        icon: 'none'
      });
      return false;
    }

    setSubmitting(true)
    try {
      await createApply({
        type: 'developer',
        reason: JSON.stringify(form),
      } as Partial<Apply>)
      Taro.showToast({ title: '申请已提交', icon: 'success' })
      setForm({
        realName: '',
        phone: '',
        email: '',
        company: '',
        position: '',
        experience: '',
      })
      setTab('record')
      loadData(1)
    } catch (err) {
      console.error('提交失败', err)
      Taro.showToast({ title: '提交失败', icon: 'none' })
    } finally {
      setSubmitting(false)
    }
  }

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

  return (
    <View className="apply-page">
      {/* Tab */}
      <View className="apply-page__tabs">
        <View
          className={`apply-page__tab ${tab === 'apply' ? 'active' : ''}`}
          onClick={() => setTab('apply')}
        >
          申请成为开发者
        </View>
        <View
          className={`apply-page__tab ${tab === 'record' ? 'active' : ''}`}
          onClick={() => setTab('record')}
        >
          申请记录
        </View>
      </View>

      {/* 申请表单 */}
      {tab === 'apply' && (
        <View className="apply-page__form">
          <View className="apply-page__section">
            <Text className="apply-page__section-title">基本信息</Text>

            <View className="apply-page__field">
              <Text className="apply-page__label">真实姓名 *</Text>
              <Input
                className="apply-page__input"
                placeholder="请输入真实姓名"
                value={form.realName}
                onInput={(e) => setForm(prev => ({ ...prev, realName: e.detail.value }))}
              />
            </View>

            <View className="apply-page__field">
              <Text className="apply-page__label">手机号码 *</Text>
              <Input
                className="apply-page__input"
                type="number"
                placeholder="请输入手机号码"
                maxlength={11}
                value={form.phone}
                onInput={(e) => setForm(prev => ({ ...prev, phone: e.detail.value }))}
              />
            </View>

            <View className="apply-page__field">
              <Text className="apply-page__label">电子邮箱</Text>
              <Input
                className="apply-page__input"
                type="text"
                placeholder="请输入电子邮箱（选填）"
                value={form.email}
                onInput={(e) => setForm(prev => ({ ...prev, email: e.detail.value }))}
              />
            </View>
          </View>

          <View className="apply-page__section">
            <Text className="apply-page__section-title">职业信息</Text>

            <View className="apply-page__field">
              <Text className="apply-page__label">公司/组织</Text>
              <Input
                className="apply-page__input"
                placeholder="请输入公司或组织名称（选填）"
                value={form.company}
                onInput={(e) => setForm(prev => ({ ...prev, company: e.detail.value }))}
              />
            </View>

            <View className="apply-page__field">
              <Text className="apply-page__label">职位</Text>
              <Input
                className="apply-page__input"
                placeholder="请输入您的职位（选填）"
                value={form.position}
                onInput={(e) => setForm(prev => ({ ...prev, position: e.detail.value }))}
              />
            </View>

            <View className="apply-page__field">
              <Text className="apply-page__label">开发经验</Text>
              <Textarea
                className="apply-page__textarea"
                placeholder="请简要描述您的开发经验和擅长的技术领域..."
                value={form.experience}
                onInput={(e: any) => setForm(prev => ({ ...prev, experience: e.detail.value }))}
                rows={4}
              />
            </View>
          </View>

          <View className="apply-page__agreement">
            <View style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <View
                style={{
                  width: '18px', height: '18px', borderRadius: '4px',
                  border: agreementChecked ? 'none' : '1px solid #ccc',
                  background: agreementChecked ? '#3b82f6' : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  marginRight: '8px'
                }}
                onClick={() => setAgreementChecked(!agreementChecked)}
              >
                {agreementChecked && <Text style={{ color: '#fff', fontSize: '12px' }}>✓</Text>}
              </View>
              <Text className="apply-page__agreement-text" style={{ fontSize: '12px' }}>
                我已阅读并同意
                <Text style={{ color: '#3b82f6' }} onClick={() => Taro.navigateTo({ url: '/passport/webview/index?url=' + encodeURIComponent('https://websopy.websoft.top/agreement') })}>《开发者协议》</Text>
                和
                <Text style={{ color: '#3b82f6' }} onClick={() => Taro.navigateTo({ url: '/passport/webview/index?url=' + encodeURIComponent('https://websopy.websoft.top/privacy') })}>《隐私政策》</Text>
              </Text>
            </View>
          </View>

          <Button
            className="apply-page__submit"
            loading={submitting}
            onClick={handleSubmit}
          >
            提交申请
          </Button>
        </View>
      )}

      {/* 申请记录 */}
      {tab === 'record' && (
        <View className="apply-page__list">
          {list.length === 0 && !loading ? (
            <View className="apply-page__empty">
              <Text className="apply-page__empty-icon">📋</Text>
              <Text className="apply-page__empty-text">暂无申请记录</Text>
            </View>
          ) : (
            list.map((item) => (
              <View key={item.id} className="apply-card">
                <View className="apply-card__header">
                  <View className="apply-card__type">
                    <Text>开发者申请</Text>
                  </View>
                  <View
                    className="apply-card__status"
                    style={{
                      color: STATUS_CONFIG[item.status as ApplyStatus]?.color,
                      background: STATUS_CONFIG[item.status as ApplyStatus]?.bgColor,
                    }}
                  >
                    {STATUS_CONFIG[item.status as ApplyStatus]?.label}
                  </View>
                </View>

                {item.reason && (
                  <View className="apply-card__reason">
                    <Text className="apply-card__reason-label">申请信息:</Text>
                    <Text className="apply-card__reason-content" numberOfLines={3}>
                      {(() => {
                        try {
                          const info = JSON.parse(item.reason)
                          return `姓名: ${info.realName} | 手机: ${info.phone}`
                        } catch {
                          return item.reason
                        }
                      })()}
                    </Text>
                  </View>
                )}

                <View className="apply-card__footer">
                  <Text className="apply-card__time">
                    申请时间: {formatDate(item.createTime)}
                  </Text>
                  {item.reviewTime && (
                    <Text className="apply-card__review">
                      审核时间: {formatDate(item.reviewTime)}
                    </Text>
                  )}
                </View>

                {item.reviewRemark && (
                  <View className="apply-card__remark">
                    <Text className="apply-card__remark-label">审核备注:</Text>
                    <Text className="apply-card__remark-content">{item.reviewRemark}</Text>
                  </View>
                )}
              </View>
            ))
          )}

          {loading && list.length === 0 && (
            <View className="apply-page__loading">
              <Text>加载中...</Text>
            </View>
          )}

          {!hasMore && list.length > 0 && (
            <View className="apply-page__no-more">
              <Text>没有更多了</Text>
            </View>
          )}
        </View>
      )}
    </View>
  )
}

export default DeveloperApplyPage
