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

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

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

  const accounts = 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="Share Register" description={`${total.toLocaleString()} share accounts`} icon={<TrendingUp className="w-6 h-6"/>}/>
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <StatCard label="Total Share Capital" value={formatCurrency(summary.totalValue)} icon={<TrendingUp className="w-5 h-5"/>} color="purple"/>
        <StatCard label="Total Shares Issued" value={(summary.totalShares ?? 0).toLocaleString()} icon={<TrendingUp className="w-5 h-5"/>} color="blue"/>
        <StatCard label="Par Value / Share" value={formatCurrency(summary.parValue ?? 50)} icon={<TrendingUp className="w-5 h-5"/>} color="green"/>
      </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 member, account no…" 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>Account No.</th><th>Member</th><th>Shares Held</th><th>Par Value/Share</th><th>Total Value</th><th>Dividends Paid</th><th>Status</th></tr></thead>
            <tbody>
              {isLoading ? Array.from({length:8}).map((_,i)=><tr key={i}>{Array.from({length:7}).map((_,j)=><td key={j}><div className="h-4 bg-muted rounded animate-pulse"/></td>)}</tr>)
              : accounts.length === 0 ? <tr><td colSpan={7} className="text-center py-8 text-muted-foreground">No share accounts found</td></tr>
              : accounts.map((a: any)=>(
                <tr key={a.id}>
                  <td className="font-mono text-sm">{a.accountNo}</td>
                  <td><p className="text-sm font-medium">{a.member?.fullName}</p><p className="text-xs text-muted-foreground">{a.member?.memberNo}</p></td>
                  <td className="text-sm font-semibold text-center">{(a.sharesHeld||0).toLocaleString()}</td>
                  <td><Amount value={a.parValuePerShare}/></td>
                  <td className="font-bold text-purple-600"><Amount value={a.totalShareValue}/></td>
                  <td><Amount value={a.totalDividendsPaid}/></td>
                  <td><Badge variant={a.isActive?'success':'default'}>{a.isActive?'ACTIVE':'INACTIVE'}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pagination page={page} pages={Math.ceil(total/pageSize)} total={total} pageSize={pageSize} onPage={setPage}/>
      </Card>
    </div>
  )
}
