"use client"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress"
import { listOrders, listPlayers, listServices, listShops } from "@/lib/api"
import { statusLabels } from "@/lib/constants"
import type { Player, PlayerService, 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"

export default function DashboardPage() {
  const { currentRole } = useAuthStore()
  const isOwner = currentRole === "owner"

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

  useEffect(() => {
    let cancelled = false

    Promise.all([listPlayers(), listShops(), listServices()])
      .then(([players, shops, services]) => {
        if (cancelled) return
        setPlayer(players[0] ?? null)
        setShop(shops[0] ?? null)
        setServices(services)
      })
      .catch(() => {
        if (cancelled) return
        setPlayer(null)
        setShop(null)
        setServices([])
      })

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

  useEffect(() => {
    let cancelled = false

    void (async () => {
      try {
        const orders = await Promise.resolve(listOrders())
        if (cancelled) return
        setOrders(orders)
      } catch {
        if (cancelled) return
        setOrders([])
      }
    })()

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

  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.filter((s) => s.playerId === player.id).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="hover:shadow-card-hover">
          <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="hover:shadow-card-hover">
          <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="hover:shadow-card-hover">
          <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="hover:shadow-card-hover">
          <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 ? "¥12,800" : serviceCount}</div>
          </CardContent>
        </Card>
      </div>

      <Card className="hover:shadow-card-hover">
        <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>
          <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 p-3 hover:bg-muted/50 transition-colors">
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-medium truncate">{order.service.title}</p>
                    <p className="text-xs text-muted-foreground">
                      {order.consumerName} → {order.playerName}
                    </p>
                  </div>
                  <div className="flex items-center gap-3 shrink-0">
                    <span className="text-sm font-medium">¥{order.totalPrice}</span>
                    <Badge variant="outline" className="text-xs">
                      {statusLabels[order.status]}
                    </Badge>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </CardContent>
      </Card>

      {!isOwner && (
        <Card className="hover:shadow-card-hover">
          <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>
  )
}
