'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import axios from 'axios'
import { formatCurrency, fmtDate } from '@/lib/utils'
import { Loader2, CreditCard } from 'lucide-react'

export default function PortalLoans() {
  const router = useRouter()
  const [member, setMember] = useState<any>(null)
  const [loans, setLoans] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    axios.get('/api/auth/member/me')
      .then(async (r) => {
        setMember(r.data.data)
        const res = await axios.get(`/api/members/${r.data.data.id}/loans`)
        setLoans(res.data.data ?? [])
      })
      .catch(() => router.push('/portal/login'))
      .finally(() => setLoading(false))
  }, [router])

  if (loading) return <div className="flex items-center justify-center h-64"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div>

  const activeLoans = loans.filter(l => l.status === 'ACTIVE')
  const totalOutstanding = activeLoans.reduce((s: number, l: any) => s + parseFloat(l.outstandingBalance ?? 0), 0)

  return (
    <div className="space-y-6">
      <div><h1 className="text-2xl font-bold">My Loans</h1><p className="text-sm text-muted-foreground">View your loan details and repayment status</p></div>

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border p-4">
          <p className="text-xs text-muted-foreground">Active Loans</p>
          <p className="text-2xl font-bold text-amber-600">{activeLoans.length}</p>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <p className="text-xs text-muted-foreground">Outstanding Balance</p>
          <p className="text-2xl font-bold text-amber-600">{formatCurrency(totalOutstanding)}</p>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <p className="text-xs text-muted-foreground">Total Loans Taken</p>
          <p className="text-2xl font-bold text-blue-600">{loans.length}</p>
        </div>
      </div>

      <div className="bg-white rounded-xl border overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-gray-50 border-b">
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">Reference</th>
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">Product</th>
                <th className="text-right px-4 py-3 font-medium text-muted-foreground">Principal</th>
                <th className="text-right px-4 py-3 font-medium text-muted-foreground">Outstanding</th>
                <th className="text-right px-4 py-3 font-medium text-muted-foreground">Monthly</th>
                <th className="text-center px-4 py-3 font-medium text-muted-foreground">Status</th>
                <th className="text-center px-4 py-3 font-medium text-muted-foreground">Disbursed</th>
              </tr>
            </thead>
            <tbody>
              {!loans.length
                ? <tr><td colSpan={7} className="text-center py-10 text-muted-foreground">No loans found.</td></tr>
                : loans.map((l: any) => (
                    <tr key={l.id} className="border-b hover:bg-gray-50">
                      <td className="px-4 py-3 font-mono text-xs text-primary">{l.loanRef}</td>
                      <td className="px-4 py-3">{l.product?.name ?? '—'}</td>
                      <td className="px-4 py-3 text-right font-medium">{formatCurrency(l.principalAmount)}</td>
                      <td className="px-4 py-3 text-right font-semibold text-amber-600">{formatCurrency(l.outstandingBalance)}</td>
                      <td className="px-4 py-3 text-right">{formatCurrency(l.monthlyPayment)}</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                          l.status === 'ACTIVE' ? 'bg-green-100 text-green-800' :
                          l.status === 'CLOSED' ? 'bg-gray-100 text-gray-700' :
                          l.status === 'DISBURSED' ? 'bg-blue-100 text-blue-800' :
                          l.status === 'APPROVED' ? 'bg-blue-100 text-blue-800' :
                          'bg-amber-100 text-amber-800'
                        }`}>{l.status.replace(/_/g, ' ')}</span>
                      </td>
                      <td className="px-4 py-3 text-center text-xs text-muted-foreground">{fmtDate(l.disbursedAt)}</td>
                    </tr>
                  ))
              }
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
