import { useState } from 'react'
import { Link } from 'react-router'
import { useDeleteObject, useObjectsList } from '../../hooks/useObjects'
import { Button } from '../../components/Button'

export function ObjectListPage() {
  const [search, setSearch] = useState('')
  const { data: objects, isLoading } = useObjectsList(search)
  const deleteObject = useDeleteObject()

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-2">
        <h1 className="text-xl font-semibold">Объекты</h1>
        <Link to="/admin/objects/new">
          <Button>Добавить</Button>
        </Link>
      </div>

      <input
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        placeholder="Поиск по номеру или названию..."
        className="w-full rounded-md border border-slate-300 px-3 py-2 dark:border-slate-700 dark:bg-slate-900"
      />

      {isLoading && <p className="text-slate-500">Загрузка...</p>}

      <div className="divide-y divide-slate-200 dark:divide-slate-800">
        {objects?.map((object) => (
          <div key={object.id} className="flex items-center justify-between gap-2 py-3">
            <div>
              <p className="font-medium">{object.name}</p>
              <p className="text-sm text-slate-500 dark:text-slate-400">
                {object.inventory_number}
                {object.box && ` · ${object.box.name}`}
              </p>
            </div>
            <div className="flex shrink-0 gap-2">
              <Link to={`/admin/objects/${object.id}/edit`}>
                <Button variant="secondary">Изменить</Button>
              </Link>
              <Button
                variant="danger"
                onClick={() => {
                  if (confirm(`Удалить объект «${object.name}»?`)) deleteObject.mutate(object.id)
                }}
              >
                Удалить
              </Button>
            </div>
          </div>
        ))}
        {objects?.length === 0 && !isLoading && <p className="py-4 text-slate-500">Ничего не найдено</p>}
      </div>
    </div>
  )
}
