"use client"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { deletePlayerService, listPlayers, listServices } from "@/lib/api"
import { resolveOwnerShop } from "@/lib/domain/resolve-current-shop"
import { toApiError } from "@/lib/errors"
import { notifyInfo, notifySuccess } from "@/lib/toast"
import type { Player, PlayerService } from "@/lib/types"
import { useAuthStore } from "@/store/auth"
import { useShopStore } from "@/store/shops"
import { Edit, Plus, Trash2 } from "lucide-react"
import Link from "next/link"
import { useCallback, useEffect, useMemo, useState } from "react"

export default function ServicesPage() {
  const userId = useAuthStore((state) => state.user?.id)
  const currentRole = useAuthStore((state) => state.currentRole)
  const shops = useShopStore((state) => state.shops)
  const [players, setPlayers] = useState<Player[]>([])
  const [services, setServices] = useState<PlayerService[]>([])
  const [loading, setLoading] = useState(true)
  const ownerShop = resolveOwnerShop(userId, shops)

  const loadData = useCallback(async () => {
    try {
      const [nextPlayers, nextServices] = await Promise.all([listPlayers(), listServices()])
      setPlayers(nextPlayers)
      setServices(nextServices)
    } catch (error) {
      notifyInfo(toApiError(error).msg)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    let cancelled = false

    Promise.all([listPlayers(), listServices()])
      .then(([nextPlayers, nextServices]) => {
        if (cancelled) return
        setPlayers(nextPlayers)
        setServices(nextServices)
      })
      .catch((error) => {
        if (cancelled) return
        notifyInfo(toApiError(error).msg)
      })
      .finally(() => {
        if (cancelled) return
        setLoading(false)
      })

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

  const scopedPlayerIdSet = useMemo(() => {
    if (currentRole === "player") {
      const player = players.find((item) => item.user.id === userId)
      return new Set(player ? [player.id] : [])
    }

    if (currentRole === "owner" && ownerShop) {
      return new Set(
        players.filter((player) => player.shopId === ownerShop.id).map((player) => player.id),
      )
    }

    return new Set<string>()
  }, [currentRole, ownerShop, players, userId])

  const scopedServices = services.filter((service) => scopedPlayerIdSet.has(service.playerId))

  async function handleDelete(service: PlayerService) {
    if (!scopedPlayerIdSet.has(service.playerId)) return

    try {
      await deletePlayerService(service.id)
      notifySuccess("服务已删除")
      await loadData()
    } catch (error) {
      notifyInfo(toApiError(error).msg)
    }
  }

  return (
    <div className="container mx-auto max-w-6xl px-4 py-8 space-y-8">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">服务管理</h1>
        <Button asChild>
          <Link href="/dashboard/services/new">
            <Plus className="mr-1 h-4 w-4" />
            发布服务
          </Link>
        </Button>
      </div>

      <Card className="hover:shadow-card-hover">
        <CardHeader>
          <CardTitle className="text-base">已发布的服务</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>服务名称</TableHead>
                <TableHead>游戏</TableHead>
                <TableHead>价格</TableHead>
                <TableHead>段位范围</TableHead>
                <TableHead>可用时间</TableHead>
                <TableHead className="text-right">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-sm text-muted-foreground">
                    加载中...
                  </TableCell>
                </TableRow>
              ) : scopedServices.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-sm text-muted-foreground">
                    暂无服务
                  </TableCell>
                </TableRow>
              ) : (
                scopedServices.map((service) => (
                  <TableRow key={service.id}>
                    <TableCell className="font-medium">{service.title}</TableCell>
                    <TableCell>
                      <Badge variant="secondary">{service.gameName}</Badge>
                    </TableCell>
                    <TableCell>
                      ¥{service.price}/{service.unit}
                    </TableCell>
                    <TableCell>{service.rankRange ?? "-"}</TableCell>
                    <TableCell>
                      <div className="text-xs text-muted-foreground">
                        {service.availability.map((a) => (
                          <div key={a}>{a}</div>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-1">
                        <Button variant="ghost" size="icon" asChild>
                          <Link href={`/dashboard/services/new?serviceId=${service.id}`}>
                            <Edit className="h-4 w-4" />
                          </Link>
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => {
                            void handleDelete(service)
                          }}
                        >
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  )
}
