"use client"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { EmptyState } from "@/components/ui/empty-state"
import { Progress } from "@/components/ui/progress"
import { StatusBadge, type StatusBadgeProps } from "@/components/ui/status-badge"
import { getMyPlayer, getMyShop, getShopIncomeStats, listOrders } from "@/lib/api"
import { statusLabels } from "@/lib/constants"
import type { Player, Shop } from "@/lib/types"
import { useAuthStore } from "@/store/auth"
import { CheckCircle, Clock, DollarSign, ListOrdered, Star, TrendingUp, Users } from "lucide-react"
import Link from "next/link"
import { useEffect, useState } from "react"

const orderStatusVariants: Record<string, StatusBadgeProps["status"]> = {
  pending_payment: "warning",
  pending_accept: "info",
  in_progress: "success",
  pending_close: "info",
  pending_review: "info",
  disputed: "destructive",
  completed: "success",
  cancelled: "neutral",
}

function getOrderRole(role: "consumer" | "player" | "owner" | "admin") {
  if (role === "consumer" || role === "player" || role === "owner") {
    return role
  }
  return undefined
}

export default function DashboardPage() {
  const { currentRole, user } = useAuthStore()
  const isOwner = currentRole === "owner"
  const orderRole = getOrderRole(currentRole)

  const [player, setPlayer] = useState<Player | null>(null)
  const [shop, setShop] = useState<Shop | null>(null)
  const [orders, setOrders] = useState<Awaited<ReturnType<typeof listOrders>>>([])
  const [monthlyIncome, setMonthlyIncome] = useState<string>("0")
  const recentOrders = orders.slice(0, 3)

  useEffect(() => {
    if (!user?.id) {
      setPlayer(null)
      setShop(null)
      return
    }

    let cancelled = false

    Promise.all([getMyPlayer(), getMyShop()])
      .then(([player, shop]) => {
        if (cancelled) return
        setPlayer(player ?? null)
        setShop(shop ?? null)
      })
      .catch(() => {
        if (cancelled) return
        setPlayer(null)
        setShop(null)
      })

    return () => {
      cancelled = true
    }
  }, [user?.id])

  useEffect(() => {
    let cancelled = false

    void (async () => {
      try {
        if (!orderRole) {
          setOrders([])
          return
        }

        const orders = await Promise.resolve(listOrders({ role: orderRole }))
        if (cancelled) return
        setOrders(orders)
      } catch {
        if (cancelled) return
        setOrders([])
      }
    })()

    return () => {
      cancelled = true
    }
  }, [orderRole])

  useEffect(() => {
    if (!shop) {
      setMonthlyIncome("0")
      return
    }

    let cancelled = false

    getShopIncomeStats(shop.id)
      .then((stats) => {
        if (cancelled) return
        setMonthlyIncome(stats.monthlyIncome)
      })
      .catch(() => {
        if (cancelled) return
        setMonthlyIncome("0")
      })

    return () => {
      cancelled = true
    }
  }, [shop])

  const totalOrders = isOwner ? (shop?.totalOrders ?? 0) : (player?.totalOrders ?? 0)
  const rating = isOwner ? (shop?.rating ?? 0) : (player?.rating ?? 0)
  const playerCount = shop?.playerCount ?? 0
  const completionRate = player?.completionRate ?? 0
  const serviceCount = player?.services.length ?? 0

  return (
    <div className="container mx-auto max-w-6xl px-4 py-8 space-y-8">
      <h1 className="text-2xl font-bold">概览</h1>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Card className="border-border/80 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">总订单</CardTitle>
            <ListOrdered className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalOrders}</div>
          </CardContent>
        </Card>
        <Card className="border-border/80 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">评分</CardTitle>
            <Star className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{rating}</div>
          </CardContent>
        </Card>
        <Card className="border-border/80 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">{isOwner ? "签约打手" : "完成率"}</CardTitle>
            {isOwner ? (
              <Users className="h-4 w-4 text-muted-foreground" />
            ) : (
              <CheckCircle className="h-4 w-4 text-muted-foreground" />
            )}
          </CardHeader>
          <CardContent>
            {isOwner ? (
              <div className="text-2xl font-bold">{playerCount}</div>
            ) : (
              <div className="space-y-2">
                <div className="text-2xl font-bold">{(completionRate * 100).toFixed(0)}%</div>
                <Progress value={completionRate * 100} className="h-1.5" />
              </div>
            )}
          </CardContent>
        </Card>
        <Card className="border-border/80 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">{isOwner ? "本月收入" : "服务数"}</CardTitle>
            {isOwner ? (
              <DollarSign className="h-4 w-4 text-muted-foreground" />
            ) : (
              <TrendingUp className="h-4 w-4 text-muted-foreground" />
            )}
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{isOwner ? `¥${monthlyIncome}` : serviceCount}</div>
          </CardContent>
        </Card>
      </div>

      <Card className="border-border/80 shadow-sm">
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="text-base">最近订单</CardTitle>
          <Button variant="ghost" size="sm" asChild>
            <Link href="/orders">查看全部</Link>
          </Button>
        </CardHeader>
        <CardContent>
          {recentOrders.length > 0 ? (
            <div className="space-y-3">
              {recentOrders.map((order) => (
                <Link key={order.id} href={`/order/${order.id}`}>
                  <div className="flex items-center justify-between rounded-md border border-border/60 p-3 transition-colors hover:bg-muted/50">
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-sm font-medium">{order.service.title}</p>
                      <p className="text-xs text-muted-foreground">{order.service.title}</p>
                    </div>
                    <div className="flex shrink-0 items-center gap-3">
                      <span className="text-sm font-medium tabular-nums">¥{order.totalPrice}</span>
                      <StatusBadge status={orderStatusVariants[order.status] ?? "neutral"}>
                        {statusLabels[order.status]}
                      </StatusBadge>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          ) : (
            <EmptyState title="暂无最近订单" icon={ListOrdered} className="min-h-[180px]" />
          )}
        </CardContent>
      </Card>

      {!isOwner && (
        <Card className="border-border/80 shadow-sm">
          <CardHeader>
            <CardTitle className="text-base">快捷操作</CardTitle>
          </CardHeader>
          <CardContent className="flex gap-2 flex-wrap">
            <Button asChild>
              <Link href="/dashboard/services/new">发布新服务</Link>
            </Button>
            <Button variant="outline" asChild>
              <Link href="/orders">
                <Clock className="mr-1 h-4 w-4" />
                待处理订单
              </Link>
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
