import { useState, type FormEvent } from "react"
import { Loader2Icon, SearchIcon, XIcon } from "lucide-react"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { useMyBorrows, useSearchMyBorrows, useReturnBook } from "./hooks"
import { formatDateTime } from "@/lib/formatters"
import { useIsMobile } from "@/hooks/useIsMobile"
import { getErrorMessage } from "@/lib/errors"

export default function MyBorrowsPage() {
  const returnBook = useReturnBook()
  const isMobile = useIsMobile()
  const sel = { "data-selectable": true } as const

  const [searchText, setSearchText] = useState("")
  const [submitted, setSubmitted] = useState("")

  const isSearching = submitted.length > 0
  const allQuery = useMyBorrows()
  const searchQuery = useSearchMyBorrows(submitted)
  const { data, isLoading, error } = isSearching ? searchQuery : allQuery

  function doSearch(e: FormEvent) {
    e.preventDefault()
    setSubmitted(searchText.trim())
  }

  function clearSearch() {
    setSearchText("")
    setSubmitted("")
  }

  const list = data ?? []

  const searchBar = (
    <form onSubmit={doSearch} className="mb-4 flex gap-2">
      <div className="relative flex-1 max-w-sm">
        <Input
          placeholder="搜索书名..."
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
        />
        {isSearching && (
          <button
            type="button"
            onClick={clearSearch}
            className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
          >
            <XIcon className="size-4" />
          </button>
        )}
      </div>
      <Button type="submit" size="icon-sm" variant="outline">
        <SearchIcon className="size-4" />
      </Button>
    </form>
  )

  const content = isLoading ? (
    <MyBorrowsSkeleton isMobile={isMobile} />
  ) : error ? (
    <div className="rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive">
      加载失败：{getErrorMessage(error)}
    </div>
  ) : list.length === 0 ? (
    <div className="py-16 text-center text-muted-foreground">
      <p className="text-lg">{isSearching ? "无匹配记录" : "暂无借阅记录"}</p>
      {!isSearching && <p className="mt-1 text-sm">去书目页面借阅你感兴趣的图书吧</p>}
    </div>
  ) : !isMobile ? (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>书名</TableHead>
          <TableHead>作者</TableHead>
          <TableHead>借阅时间</TableHead>
          <TableHead>归还时间</TableHead>
          <TableHead>状态</TableHead>
          <TableHead className="w-[100px]">操作</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {list.map((r) => (
          <TableRow key={r.id}>
            <TableCell className="font-medium" {...sel}>{r.bookBorrowVo?.name ?? "-"}</TableCell>
            <TableCell {...sel}>{r.bookBorrowVo?.author ?? "-"}</TableCell>
            <TableCell>{formatDateTime(r.borrowTime)}</TableCell>
            <TableCell>
              {r.returnTime ? formatDateTime(r.returnTime) : "-"}
            </TableCell>
            <TableCell>
              <Badge variant={r.status === "BORROWED" ? "default" : "secondary"}>
                {r.status === "BORROWED" ? "借阅中" : "已归还"}
              </Badge>
            </TableCell>
            <TableCell>
              {r.status === "BORROWED" && (
                <Button
                  size="sm"
                  variant="outline"
                  disabled={returnBook.isPending}
                  onClick={() => returnBook.mutate(r.id)}
                >
                  {returnBook.isPending && <Loader2Icon className="animate-spin" />}
                  归还
                </Button>
              )}
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  ) : (
    <div className="space-y-3">
      {list.map((r) => (
        <Card key={r.id}>
          <CardContent className="space-y-1.5 p-4">
            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">#{r.id}</span>
              <Badge variant={r.status === "BORROWED" ? "default" : "secondary"}>
                {r.status === "BORROWED" ? "借阅中" : "已归还"}
              </Badge>
            </div>
            <div className="font-medium" {...sel}>{r.bookBorrowVo?.name ?? "-"}</div>
            <div className="text-sm text-muted-foreground" {...sel}>{r.bookBorrowVo?.author ?? "-"}</div>
            <div className="text-sm text-muted-foreground">
              借阅：{formatDateTime(r.borrowTime)}
              {r.returnTime && ` | 归还：${formatDateTime(r.returnTime)}`}
            </div>
            {r.status === "BORROWED" && (
              <div className="pt-1">
                <Button
                  size="sm"
                  variant="outline"
                  disabled={returnBook.isPending}
                  onClick={() => returnBook.mutate(r.id)}
                >
                  {returnBook.isPending && <Loader2Icon className="animate-spin" />}
                  归还
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      ))}
    </div>
  )

  if (isMobile) {
    return (
      <div className="px-4 py-4">
        <h1 className="mb-4 text-xl font-semibold">我的借阅</h1>
        {searchBar}
        {content}
      </div>
    )
  }

  return (
    <div className="mx-auto max-w-[1200px] px-4 py-8">
      <h1 className="mb-4 text-xl font-semibold">我的借阅</h1>
      {searchBar}
      {content}
    </div>
  )
}

function MyBorrowsSkeleton({ isMobile }: { isMobile: boolean }) {
  if (isMobile) {
    return (
      <div className="space-y-3">
        {Array.from({ length: 5 }).map((_, i) => (
          <Card key={i}>
            <CardContent className="space-y-2 p-4">
              <Skeleton className="h-4 w-16" />
              <Skeleton className="h-5 w-36" />
              <Skeleton className="h-4 w-28" />
              <Skeleton className="h-4 w-40" />
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-2">
      {Array.from({ length: 5 }).map((_, i) => (
        <Skeleton key={i} className="h-10 w-full" />
      ))}
    </div>
  )
}
