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 { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { useBooks, useSearchBooks, useBorrowBook } from "./hooks"
import { useAuthStore } from "@/store/authStore"
import { useIsMobile } from "@/hooks/useIsMobile"
import { getErrorMessage } from "@/lib/errors"

export default function BooksPage() {
  const borrow = useBorrowBook()
  const token = useAuthStore((s) => s.token)
  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 = useBooks()
  const searchQuery = useSearchBooks(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 ? (
    <BooksSkeleton 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 ? (
    <p className="py-16 text-center text-muted-foreground">
      {isSearching ? "无匹配书目" : "暂无书目"}
    </p>
  ) : !isMobile ? (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>书名</TableHead>
          <TableHead>作者</TableHead>
          <TableHead>库存</TableHead>
          {token && <TableHead className="w-[120px]">操作</TableHead>}
        </TableRow>
      </TableHeader>
      <TableBody>
        {list.map((book) => (
          <TableRow key={book.id}>
            <TableCell className="font-medium" {...sel}>{book.name}</TableCell>
            <TableCell {...sel}>{book.author}</TableCell>
            <TableCell>{book.stock}</TableCell>
            {token && (
              <TableCell>
                <Button
                  size="sm"
                  disabled={book.stock <= 0 || borrow.isPending}
                  onClick={() => borrow.mutate(book.id!)}
                >
                  {borrow.isPending && <Loader2Icon className="animate-spin" />}
                  {book.stock <= 0 ? "暂无库存" : "借阅"}
                </Button>
              </TableCell>
            )}
          </TableRow>
        ))}
      </TableBody>
    </Table>
  ) : (
    <div className="space-y-3">
      {list.map((book) => (
        <Card key={book.id}>
          <CardContent className="flex items-center justify-between p-4">
            <div className="space-y-0.5">
              <div className="font-medium" {...sel}>{book.name}</div>
              <div className="text-sm text-muted-foreground" {...sel}>{book.author}</div>
              <div className="text-sm text-muted-foreground">库存：{book.stock}</div>
            </div>
            {token && (
              <Button
                size="sm"
                disabled={book.stock <= 0 || borrow.isPending}
                onClick={() => borrow.mutate(book.id!)}
              >
                {borrow.isPending && <Loader2Icon className="animate-spin" />}
                {book.stock <= 0 ? "暂无库存" : "借阅"}
              </Button>
            )}
          </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 BooksSkeleton({ isMobile }: { isMobile: boolean }) {
  if (isMobile) {
    return (
      <div className="space-y-3">
        {Array.from({ length: 5 }).map((_, i) => (
          <Card key={i}>
            <CardContent className="flex items-center justify-between p-4">
              <div className="space-y-2">
                <Skeleton className="h-5 w-32" />
                <Skeleton className="h-4 w-20" />
                <Skeleton className="h-4 w-16" />
              </div>
              <Skeleton className="h-8 w-16 rounded-lg" />
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

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