"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
import { ChevronLeft, Copy, Share2, Users, Wallet, MessageCircle, ImageIcon, TrendingUp, Gift, Check, ArrowRight } from "lucide-react"
import { useStore, type Purchase } from "@/lib/store"
import { PosterModal } from "@/components/modules/referral/poster-modal"
import { WithdrawalModal } from "@/components/modules/referral/withdrawal-modal"

export default function ReferralPage() {
  const { user, isLoggedIn, settings, getAllPurchases, getAllUsers } = useStore()
  const [copied, setCopied] = useState(false)
  const [showPoster, setShowPoster] = useState(false)
  const [showWithdrawal, setShowWithdrawal] = useState(false)
  const [referralPurchases, setReferralPurchases] = useState<Purchase[]>([])
  const [referralUsers, setReferralUsers] = useState<number>(0)

  useEffect(() => {
    if (user?.referralCode) {
      const allPurchases = getAllPurchases()
      const allUsers = getAllUsers()
      const usersWithMyCode = allUsers.filter((u) => u.referredBy === user.referralCode)
      const userIds = usersWithMyCode.map((u) => u.id)
      const myReferralPurchases = allPurchases.filter((p) => userIds.includes(p.userId))
      setReferralPurchases(myReferralPurchases)
      setReferralUsers(usersWithMyCode.length)
    }
  }, [user, getAllPurchases, getAllUsers])

  if (!isLoggedIn || !user) {
    return (
      <div className="min-h-screen bg-black text-white flex items-center justify-center pb-20">
        <div className="text-center glass-card p-8">
          <p className="text-[var(--app-text-secondary)] mb-4">请先登录</p>
          <Link href="/" className="btn-ios inline-block">
            返回首页
          </Link>
        </div>
      </div>
    )
  }

  const referralLink = `${typeof window !== "undefined" ? window.location.origin : ""}?ref=${user.referralCode}`
  const distributorShare = settings?.distributorShare || 90
  const totalEarnings = user.earnings || 0
  const pendingEarnings = user.pendingEarnings || 0

  const handleCopy = () => {
    navigator.clipboard.writeText(referralLink)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const handleShare = async () => {
    const shareText = `我正在读《一场SOUL的创业实验场》，每天6-9点的真实商业故事，推荐给你！${referralLink}`
    try {
      if (typeof navigator.share === 'function' && typeof navigator.canShare === 'function') {
        await navigator.share({
          title: "一场SOUL的创业实验场",
          text: "来自Soul派对房的真实商业故事",
          url: referralLink,
        })
      } else {
        await navigator.clipboard.writeText(shareText)
        alert("分享文案已复制，快去朋友圈或Soul派对分享吧！")
      }
    } catch {
      await navigator.clipboard.writeText(shareText)
      alert("分享文案已复制！")
    }
  }

  const handleShareToWechat = async () => {
    const shareText = `📖 推荐一本好书《一场SOUL的创业实验场》

这是卡若每天早上6-9点在Soul派对房分享的真实商业故事，55个真实案例，讲透创业的底层逻辑。

👉 点击阅读: ${referralLink}

#创业 #商业思维 #Soul派对`
    await navigator.clipboard.writeText(shareText)
    alert("朋友圈文案已复制！\n\n打开微信 → 发朋友圈 → 粘贴即可")
  }

  return (
    <div className="min-h-screen bg-black text-white pb-24 page-transition">
      {/* 背景光效 */}
      <div className="fixed inset-0 -z-10">
        <div className="absolute top-0 left-1/2 -translate-x-1/2 w-[500px] h-[500px] bg-[var(--app-brand)] opacity-[0.05] blur-[150px] rounded-full" />
      </div>

      {/* Header - iOS风格 */}
      <header className="sticky top-0 z-50 glass-nav safe-top">
        <div className="max-w-md mx-auto px-4 py-3 flex items-center">
          <Link href="/my" className="w-8 h-8 rounded-full bg-[var(--app-bg-secondary)] flex items-center justify-center touch-feedback">
            <ChevronLeft className="w-5 h-5 text-[var(--app-text-secondary)]" />
          </Link>
          <h1 className="flex-1 text-center font-semibold">分销中心</h1>
          <div className="w-8" />
        </div>
      </header>

      <main className="max-w-md mx-auto px-4 py-6">
        {/* 收益卡片 - 毛玻璃渐变 */}
        <div className="relative glass-card-heavy p-6 mb-6 overflow-hidden">
          {/* 背景装饰 */}
          <div className="absolute top-0 right-0 w-32 h-32 bg-[var(--app-brand)] opacity-[0.15] blur-[50px] rounded-full" />
          
          <div className="relative">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <div className="w-10 h-10 rounded-xl bg-[var(--app-brand-light)] flex items-center justify-center">
                  <Wallet className="w-5 h-5 text-[var(--app-brand)]" />
                </div>
                <div>
                  <p className="text-[var(--app-text-tertiary)] text-xs">累计收益</p>
                  <p className="text-[var(--app-brand)] text-xs font-medium">{distributorShare}% 返利</p>
                </div>
              </div>
              <div className="text-right">
                <p className="text-3xl font-bold text-white glow-text">¥{totalEarnings.toFixed(2)}</p>
                <p className="text-[var(--app-text-tertiary)] text-xs">待结算: ¥{pendingEarnings.toFixed(2)}</p>
              </div>
            </div>

            <button
              disabled={totalEarnings < 10}
              onClick={() => setShowWithdrawal(true)}
              className="btn-ios w-full glow disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {totalEarnings < 10 ? `满10元可提现` : "申请提现"}
            </button>
          </div>
        </div>

        {/* 数据统计 */}
        <div className="grid grid-cols-2 gap-4 mb-6">
          <div className="glass-card p-4 text-center">
            <div className="w-10 h-10 rounded-xl bg-[var(--ios-blue)]/20 flex items-center justify-center mx-auto mb-2">
              <Users className="w-5 h-5 text-[var(--ios-blue)]" />
            </div>
            <p className="text-2xl font-bold text-white mb-0.5">{referralUsers}</p>
            <p className="text-[var(--app-text-tertiary)] text-xs">邀请人数</p>
          </div>
          <div className="glass-card p-4 text-center">
            <div className="w-10 h-10 rounded-xl bg-[var(--ios-purple)]/20 flex items-center justify-center mx-auto mb-2">
              <TrendingUp className="w-5 h-5 text-[var(--ios-purple)]" />
            </div>
            <p className="text-2xl font-bold text-white mb-0.5">{referralPurchases.length}</p>
            <p className="text-[var(--app-text-tertiary)] text-xs">成交订单</p>
          </div>
        </div>

        {/* 专属链接 */}
        <div className="glass-card p-5 mb-6">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-white font-semibold">我的专属链接</h3>
            <span className="text-[var(--app-brand)] text-xs bg-[var(--app-brand-light)] px-2 py-1 rounded-full">
              {user.referralCode}
            </span>
          </div>
          
          <div className="flex gap-2 mb-4">
            <div className="flex-1 bg-[var(--app-bg-secondary)] rounded-xl px-4 py-3 text-[var(--app-text-secondary)] text-sm truncate font-mono">
              {referralLink}
            </div>
            <button
              onClick={handleCopy}
              className="w-12 h-12 rounded-xl bg-[var(--app-brand-light)] flex items-center justify-center text-[var(--app-brand)] touch-feedback"
            >
              {copied ? <Check className="w-5 h-5" /> : <Copy className="w-5 h-5" />}
            </button>
          </div>
          
          <p className="text-[var(--app-text-tertiary)] text-xs">
            好友通过此链接购买，你将获得 {distributorShare}% 返利
          </p>
        </div>

        {/* 分享按钮 */}
        <div className="space-y-3 mb-6">
          <button
            onClick={() => setShowPoster(true)}
            className="w-full glass-card p-4 flex items-center gap-4 touch-feedback"
          >
            <div className="w-12 h-12 rounded-xl bg-[var(--ios-indigo)]/20 flex items-center justify-center">
              <ImageIcon className="w-6 h-6 text-[var(--ios-indigo)]" />
            </div>
            <div className="flex-1 text-left">
              <p className="text-white font-medium">生成推广海报</p>
              <p className="text-[var(--app-text-tertiary)] text-xs">一键生成精美海报分享</p>
            </div>
            <ArrowRight className="w-5 h-5 text-[var(--app-text-tertiary)]" />
          </button>
          
          <button
            onClick={handleShareToWechat}
            className="w-full glass-card p-4 flex items-center gap-4 touch-feedback"
          >
            <div className="w-12 h-12 rounded-xl bg-[#07C160]/20 flex items-center justify-center">
              <MessageCircle className="w-6 h-6 text-[#07C160]" />
            </div>
            <div className="flex-1 text-left">
              <p className="text-white font-medium">分享到朋友圈</p>
              <p className="text-[var(--app-text-tertiary)] text-xs">复制文案发朋友圈</p>
            </div>
            <ArrowRight className="w-5 h-5 text-[var(--app-text-tertiary)]" />
          </button>
          
          <button
            onClick={handleShare}
            className="w-full glass-card p-4 flex items-center gap-4 touch-feedback"
          >
            <div className="w-12 h-12 rounded-xl bg-[var(--app-bg-secondary)] flex items-center justify-center">
              <Share2 className="w-6 h-6 text-[var(--app-text-secondary)]" />
            </div>
            <div className="flex-1 text-left">
              <p className="text-white font-medium">更多分享方式</p>
              <p className="text-[var(--app-text-tertiary)] text-xs">使用系统分享功能</p>
            </div>
            <ArrowRight className="w-5 h-5 text-[var(--app-text-tertiary)]" />
          </button>
        </div>

        {/* 收益明细 */}
        {referralPurchases.length > 0 && (
          <div className="glass-card overflow-hidden">
            <div className="px-5 py-4 border-b border-[var(--app-separator)]">
              <h3 className="text-white font-semibold">收益明细</h3>
            </div>
            <div className="max-h-60 overflow-auto scrollbar-hide">
              {referralPurchases.slice(0, 10).map((purchase, idx) => (
                <div 
                  key={purchase.id} 
                  className={`px-5 py-4 flex items-center justify-between ${idx !== referralPurchases.length - 1 ? 'border-b border-[var(--app-separator)]' : ''}`}
                >
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-xl bg-[var(--app-brand-light)] flex items-center justify-center">
                      <Gift className="w-5 h-5 text-[var(--app-brand)]" />
                    </div>
                    <div>
                      <p className="text-white text-sm font-medium">
                        {purchase.type === "fullbook" ? "整本书购买" : "单节购买"}
                      </p>
                      <p className="text-[var(--app-text-tertiary)] text-xs">
                        {new Date(purchase.createdAt).toLocaleDateString("zh-CN")}
                      </p>
                    </div>
                  </div>
                  <p className="text-[var(--app-brand)] font-semibold">
                    +¥{(purchase.referrerEarnings || 0).toFixed(2)}
                  </p>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 空状态 */}
        {referralPurchases.length === 0 && (
          <div className="glass-card p-8 text-center">
            <div className="w-16 h-16 rounded-full bg-[var(--app-bg-secondary)] flex items-center justify-center mx-auto mb-4">
              <Gift className="w-8 h-8 text-[var(--app-text-tertiary)]" />
            </div>
            <p className="text-white font-medium mb-2">暂无收益记录</p>
            <p className="text-[var(--app-text-tertiary)] text-sm">
              分享专属链接，好友购买即可获得 {distributorShare}% 返利
            </p>
          </div>
        )}
      </main>

      <PosterModal 
        isOpen={showPoster} 
        onClose={() => setShowPoster(false)} 
        referralLink={referralLink}
        referralCode={user.referralCode}
        nickname={user.nickname}
      />

      <WithdrawalModal
        isOpen={showWithdrawal}
        onClose={() => setShowWithdrawal(false)}
        availableAmount={totalEarnings}
      />
    </div>
  )
}
