"use client"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { listChatSessions, listOrders } from "@/lib/api"
import { statusLabels } from "@/lib/constants"
import {
  isActiveOrder,
  isCompletedOrder,
  isDisputedOrder,
  isPendingDispatch,
} from "@/lib/domain/order-filters"
import { resolveOwnerShop } from "@/lib/domain/resolve-current-shop"
import type { OrderStatus, UserRole } from "@/lib/types"
import { cn } from "@/lib/utils"
import { useAuthStore } from "@/store/auth"
import { useShopStore } from "@/store/shops"
import { Clock, MessageSquare, RefreshCw } from "lucide-react"
import Link from "next/link"
import { useEffect, useState } from "react"

const statusColors: Record<OrderStatus, string> = {
  pending_payment: "bg-yellow-100 text-yellow-800",
  pending_accept: "bg-blue-100 text-blue-800",
  in_progress: "bg-green-100 text-green-800",
  pending_close: "bg-orange-100 text-orange-800",
  pending_review: "bg-purple-100 text-purple-800",
  disputed: "bg-red-100 text-red-800",
  completed: "bg-gray-100 text-gray-800",
  cancelled: "bg-gray-100 text-gray-500",
}

type TabFilter = "all" | "active" | "completed" | "disputed"

const consumerTabs = [
  { value: "all", label: "全部" },
  { value: "active", label: "进行中" },
  { value: "completed", label: "已完成" },
  { value: "disputed", label: "争议" },
]

const playerTabs = [
  { value: "all", label: "全部" },
  { value: "pending", label: "待接单" },
  { value: "active", label: "进行中" },
  { value: "completed", label: "已完成" },
]

const ownerTabs = [
  { value: "all", label: "全部" },
  { value: "pending", label: "待派单" },
  { value: "active", label: "进行中" },
  { value: "completed", label: "已完成" },
  { value: "disputed", label: "争议" },
]

export default function OrderListPage() {
  const { currentRole, user } = useAuthStore()
  const shops = useShopStore((state) => state.shops)
  const ownerShop = resolveOwnerShop(user?.id, shops)

  return (
    <OrderListContent
      key={currentRole}
      currentRole={currentRole}
      userId={user?.id}
      ownerShopId={ownerShop?.id}
    />
  )
}

function OrderListContent({
  currentRole,
  userId,
  ownerShopId,
}: {
  currentRole: UserRole
  userId?: string
  ownerShopId?: string
}) {
  const [tab, setTab] = useState<TabFilter | "pending">("all")
  const [orders, setOrders] = useState<Awaited<ReturnType<typeof listOrders>>>([])
  const [sessions, setSessions] = useState<Awaited<ReturnType<typeof listChatSessions>>>([])

  useEffect(() => {
    let cancelled = false

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

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

  useEffect(() => {
    let cancelled = false

    void (async () => {
      try {
        const items = await Promise.resolve(listChatSessions())
        if (cancelled) return
        setSessions(items)
      } catch {
        if (cancelled) return
        setSessions([])
      }
    })()

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

  const tabs =
    currentRole === "consumer" ? consumerTabs : currentRole === "player" ? playerTabs : ownerTabs

  const roleFiltered = orders.filter((order) => {
    if (currentRole === "consumer") return userId ? order.consumerId === userId : false
    if (currentRole === "player") return userId ? order.playerId === userId : false
    return ownerShopId ? order.shopId === ownerShopId : false
  })

  const filtered = roleFiltered.filter((order) => {
    if (tab === "pending") return isPendingDispatch(order.status)
    if (tab === "active") return isActiveOrder(order.status)
    if (tab === "completed") return isCompletedOrder(order.status, { includeCancelled: true })
    if (tab === "disputed") return isDisputedOrder(order.status)
    return true
  })

  return (
    <div className="container mx-auto max-w-3xl px-4 py-8 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">我的订单</h1>
        <Badge variant="outline" className="text-xs">
          {currentRole === "consumer"
            ? "客户视角"
            : currentRole === "player"
              ? "打手视角"
              : "店主视角"}
        </Badge>
      </div>

      <Tabs value={tab} onValueChange={(v) => setTab(v as TabFilter | "pending")}>
        <TabsList>
          {tabs.map((item) => (
            <TabsTrigger key={item.value} value={item.value}>
              {item.label}
            </TabsTrigger>
          ))}
        </TabsList>

        <TabsContent value={tab} className="mt-4 space-y-4">
          {filtered.length === 0 ? (
            <Card className="hover:shadow-card-hover">
              <CardContent className="py-8 text-center text-sm text-muted-foreground">
                暂无订单
              </CardContent>
            </Card>
          ) : (
            filtered.map((order) => (
              <Card key={order.id} className="hover:shadow-card-hover">
                <CardHeader className="pb-3">
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-base">{order.service.title}</CardTitle>
                    <Badge className={cn("text-xs", statusColors[order.status])}>
                      {statusLabels[order.status]}
                    </Badge>
                  </div>
                  <p className="text-sm text-muted-foreground">{order.service.title}</p>
                </CardHeader>
                <CardContent>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4 text-sm text-muted-foreground">
                      <span className="font-medium text-foreground">¥{order.totalPrice}</span>
                      <span className="flex items-center gap-1">
                        <Clock className="h-3.5 w-3.5" />
                        {new Date(order.createdAt).toLocaleDateString("zh-CN")}
                      </span>
                    </div>
                    <div className="flex gap-2">
                      {(() => {
                        if (order.status !== "in_progress" && order.status !== "pending_close")
                          return null
                        const session = sessions.find(
                          (item) => item.type === "order" && item.orderId === order.id,
                        )
                        if (!session) return null
                        return (
                          <Button variant="outline" size="sm" asChild>
                            <Link href={`/chat/${session.id}`}>
                              <MessageSquare className="mr-1 h-3.5 w-3.5" />
                              聊天
                            </Link>
                          </Button>
                        )
                      })()}
                      {order.status === "completed" && (
                        <Button variant="outline" size="sm" asChild>
                          <Link href={`/order/new?serviceId=${order.service.id}`}>
                            <RefreshCw className="mr-1 h-3.5 w-3.5" />
                            再来一单
                          </Link>
                        </Button>
                      )}
                      <Button size="sm" asChild>
                        <Link href={`/order/${order.id}`}>查看详情</Link>
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))
          )}
        </TabsContent>
      </Tabs>
    </div>
  )
}
