'use client'
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { formatCurrency, fmtDate } from '@/lib/utils'
import { HardDrive, Plus, Search } from 'lucide-react'
import { StatCard, Card, Badge, Button, PageHeader, Pagination, Amount } from '@/components/ui/components'

export default function AssetsPage() {
  const [search, setSearch] = useState('')
  const [page, setPage] = useState(1)
  const pageSize = 20

  const { data, isLoading } = useQuery({
    queryKey: ['assets', { search, page }],
    queryFn: () => axios.get(`/api/assets?search=${search}&page=${page}&pageSize=${pageSize}`).then(r => r.data),
    placeholderData: (prev: unknown) => prev,
  })

  const assets = data?.data ?? []
  const total  = data?.total ?? 0
  const summary = data?.summary ?? {}

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader title="Fixed Assets" description={`${total} assets`} icon={<HardDrive className="w-6 h-6"/>}
        actions={<Button size="sm" icon={<Plus className="w-4 h-4"/>}>Add Asset</Button>}
      />
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <StatCard label="Total Asset Value" value={formatCurrency(summary.totalCost)} icon={<HardDrive className="w-5 h-5"/>} color="blue"/>
        <StatCard label="Net Book Value" value={formatCurrency(summary.totalNbv)} icon={<HardDrive className="w-5 h-5"/>} color="green"/>
        <StatCard label="Accumulated Depreciation" value={formatCurrency(summary.totalDepreciation)} icon={<HardDrive className="w-5 h-5"/>} color="amber"/>
      </div>
      <div className="relative"><Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"/><input value={search} onChange={e=>{setSearch(e.target.value);setPage(1)}} placeholder="Search asset name, serial number…" className="w-full pl-9 pr-4 py-2 text-sm border rounded-lg focus:outline-none bg-card"/></div>
      <Card>
        <div className="overflow-x-auto">
          <table className="table-lms w-full">
            <thead><tr><th>Asset</th><th>Category</th><th>Location</th><th>Cost</th><th>Depreciation</th><th>Net Book Value</th><th>Status</th><th>Purchase Date</th></tr></thead>
            <tbody>
              {isLoading ? Array.from({length:8}).map((_,i)=><tr key={i}>{Array.from({length:8}).map((_,j)=><td key={j}><div className="h-4 bg-muted rounded animate-pulse"/></td>)}</tr>)
              : assets.length === 0 ? <tr><td colSpan={8} className="text-center py-8 text-muted-foreground">No assets found</td></tr>
              : assets.map((a: any) => (
                <tr key={a.id}>
                  <td><p className="font-medium text-sm">{a.assetName}</p><p className="text-xs text-muted-foreground">SN: {a.serialNumber}</p></td>
                  <td className="text-sm">{a.category?.replace(/_/g,' ')}</td>
                  <td className="text-sm text-muted-foreground">{a.location}</td>
                  <td><Amount value={a.purchaseCost}/></td>
                  <td className="text-amber-600"><Amount value={a.accumulatedDepreciation}/></td>
                  <td className="font-bold text-blue-600"><Amount value={a.netBookValue}/></td>
                  <td><Badge variant={a.status==='IN_USE'?'success':a.status==='DISPOSED'?'danger':'warning'}>{a.status?.replace(/_/g,' ')}</Badge></td>
                  <td className="text-xs text-muted-foreground">{fmtDate(a.purchaseDate)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pagination page={page} pages={Math.ceil(total/pageSize)} total={total} pageSize={pageSize} onPage={setPage}/>
      </Card>
    </div>
  )
}
