'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/navigation'
import axios from 'axios'
import { toast } from 'sonner'
import { formatCurrency, fmtDate, cn } from '@/lib/utils'
import { CreditCard, Plus, Bell, Search, ChevronRight, AlertTriangle, Clock } from 'lucide-react'
import {
  Card, CardHeader, CardTitle, Badge, Button, Modal, Input, Select,
  PageHeader, Pagination, Amount, Alert, StatCard, FormGrid,
} from '@/components/ui/components'

const STATUS_VARIANT: Record<string, any> = {
  DRAFT: 'default', PENDING_APPRAISAL: 'warning', APPRAISED: 'info',
  PENDING_L1: 'warning', PENDING_L2: 'warning', PENDING_L3: 'warning',
  APPROVED: 'info', ACTIVE: 'success', CLOSED: 'default',
  DECLINED: 'danger', CANCELLED: 'default', WRITTEN_OFF: 'danger',
}

export default function LoansPage() {
  const router = useRouter()
  const qc     = useQueryClient()

  const [page,   setPage]   = useState(1)
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')
  const [showNotif, setShowNotif] = useState(false)
  const [newModal,  setNewModal]  = useState(false)
  const [feeModal,  setFeeModal]  = useState(false)   // processing fee upfront

  const [form, setForm] = useState({
    memberId: '', productId: '', principalAmount: '', tenor: '',
    tenorUnit: 'MONTHS', purpose: '', applicationDate: '',
  })

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

  const { data: pendingData } = useQuery({
    queryKey: ['pending-approvals'],
    queryFn:  () => axios.get('/api/loans?sub=pending_approvals').then(r => r.data),
    refetchInterval: 30_000,  // refresh every 30s
  })

  const { data: productsData } = useQuery({
    queryKey: ['loan-products-mini'],
    queryFn:  () => axios.get('/api/loans/products?pageSize=100').then(r => r.data.data),
    enabled:  newModal,
  })

  const { data: membersData } = useQuery({
    queryKey: ['members-mini'],
    queryFn:  () => axios.get('/api/members?pageSize=200&status=ACTIVE').then(r => r.data.data),
    enabled:  newModal,
  })

  // ── Mutations ─────────────────────────────────────────────────────────────
  const createMutation = useMutation({
    mutationFn: (p: any) => axios.post('/api/loans', p),
    onSuccess: (res) => {
      toast.success('Loan application created')
      qc.invalidateQueries({ queryKey: ['loans'] })
      setNewModal(false)
      // Navigate to new loan
      router.push(`/loans/${res.data.data.id}`)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to create loan'),
  })

  // ── Derived ───────────────────────────────────────────────────────────────
  const loans        = data?.data        ?? []
  const total        = data?.total       ?? 0
  const pendingCount = data?.pendingCount ?? 0
  const isSuperAdmin = data?.isSuperAdmin ?? false
  const pendingList  = pendingData?.data  ?? []

  const STATUS_OPTIONS = [
    '', 'DRAFT', 'PENDING_APPRAISAL', 'PENDING_L1', 'PENDING_L2', 'APPROVED',
    'ACTIVE', 'CLOSED', 'DECLINED', 'WRITTEN_OFF',
  ]

  function setField(k: string, v: string) { setForm(p => ({ ...p, [k]: v })) }

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">

      <PageHeader
        title="Loans"
        description={isSuperAdmin ? 'All loans across the organisation' : 'Loans you have initiated'}
        icon={<CreditCard className="w-6 h-6" />}
        actions={
          <div className="flex items-center gap-2">
            {/* Pending approval notification bell */}
            <button
              className="relative p-2 rounded-lg hover:bg-muted transition-colors"
              onClick={() => setShowNotif(true)}
            >
              <Bell className="w-5 h-5" />
              {pendingCount > 0 && (
                <span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] bg-red-500 text-white text-xs rounded-full flex items-center justify-center font-bold px-0.5">
                  {pendingCount > 99 ? '99+' : pendingCount}
                </span>
              )}
            </button>
            <Button size="sm" icon={<Plus className="w-4 h-4" />} onClick={() => setNewModal(true)}>
              New Loan
            </Button>
          </div>
        }
      />

      {/* Pending approvals inline alert */}
      {pendingCount > 0 && (
        <Alert variant="warning">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Clock className="w-4 h-4 shrink-0" />
              <span>
                <strong>{pendingCount} loan{pendingCount > 1 ? 's' : ''}</strong> pending your approval action.
              </span>
            </div>
            <button className="text-xs underline" onClick={() => setShowNotif(true)}>View all</button>
          </div>
        </Alert>
      )}

      {/* Loans table */}
      <Card>
        <CardHeader>
          <CardTitle>Loan Applications</CardTitle>
          <div className="flex items-center gap-2 flex-wrap">
            <div className="relative">
              <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none" />
              <input
                className="pl-8 pr-3 py-1.5 text-sm border rounded-md w-52 bg-background focus:outline-none focus:ring-1 focus:ring-primary"
                placeholder="Loan ref, member name…"
                value={search}
                onChange={e => { setSearch(e.target.value); setPage(1) }}
              />
            </div>
            <select
              className="text-sm border rounded-md px-2.5 py-1.5 bg-background"
              value={status}
              onChange={e => { setStatus(e.target.value); setPage(1) }}
            >
              <option value="">All Status</option>
              {STATUS_OPTIONS.filter(Boolean).map(s => (
                <option key={s} value={s}>{s.replace(/_/g, ' ')}</option>
              ))}
            </select>
          </div>
        </CardHeader>

        <div className="overflow-x-auto">
          <table className="table-lms w-full">
            <thead>
              <tr>
                <th>Loan Ref</th>
                <th>Member</th>
                <th>Product</th>
                <th>Principal</th>
                <th>Outstanding</th>
                <th>Status</th>
                <th>Applied</th>
                {isSuperAdmin && <th>Created By</th>}
                <th></th>
              </tr>
            </thead>
            <tbody>
              {isLoading ? (
                Array.from({ length: 8 }).map((_, i) => (
                  <tr key={i}>{Array.from({ length: isSuperAdmin ? 8 : 7 }).map((_, j) => <td key={j}><div className="h-4 bg-muted rounded animate-pulse" /></td>)}</tr>
                ))
              ) : loans.length === 0 ? (
                <tr>
                  <td colSpan={isSuperAdmin ? 8 : 7} className="text-center py-10 text-muted-foreground">
                    {search ? `No loans found for "${search}"` : 'No loans found'}
                  </td>
                </tr>
              ) : (
                loans.map((l: any) => (
                  <tr
                    key={l.id}
                    className="cursor-pointer hover:bg-muted/30 transition-colors"
                    onClick={() => router.push(`/loans/${l.id}`)}
                  >
                    <td className="font-mono text-xs font-semibold">{l.loanRef}</td>
                    <td>
                      <p className="font-medium text-sm">{l.member?.fullName}</p>
                      <p className="text-xs text-muted-foreground">{l.member?.memberNo}</p>
                    </td>
                    <td className="text-sm">{l.product?.name}</td>
                    <td><Amount value={l.principalAmount} size="sm" /></td>
                    <td className="font-semibold">
                      <Amount value={l.outstandingBalance} size="sm"
                        className={parseFloat(l.outstandingBalance) > 0 ? 'text-amber-600' : 'text-green-600'} />
                    </td>
                    <td>
                      <div className="space-y-0.5">
                        <Badge variant={STATUS_VARIANT[l.status] ?? 'default'}>
                          {l.status?.replace(/_/g, ' ')}
                        </Badge>
                        {l.daysOverdue > 0 && (
                          <p className="text-xs text-red-600">{l.daysOverdue}d overdue</p>
                        )}
                      </div>
                    </td>
                    <td className="text-xs text-muted-foreground">{fmtDate(l.createdAt)}</td>
                    {isSuperAdmin && (
                      <td className="text-xs text-muted-foreground">{l.creatorName}</td>
                    )}
                    <td>
                      <ChevronRight className="w-4 h-4 text-muted-foreground" />
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        <Pagination page={page} pages={Math.ceil(total / 20)} total={total} pageSize={20} onPage={setPage} />
      </Card>

      {/* ══ Pending Approvals Modal ══ */}
      <Modal
        open={showNotif}
        onClose={() => setShowNotif(false)}
        title={`Pending Approvals (${pendingList.length})`}
      >
        <div className="space-y-2 max-h-[60vh] overflow-y-auto">
          {pendingList.length === 0 ? (
            <p className="text-center py-8 text-muted-foreground text-sm">No pending approvals for you.</p>
          ) : (
            pendingList.map((a: any) => (
              <div
                key={a.id}
                className="border rounded-lg p-3 cursor-pointer hover:bg-muted/30 transition-colors"
                onClick={() => { setShowNotif(false); router.push(`/loans/${a.loan?.id}`) }}
              >
                <div className="flex items-start justify-between">
                  <div>
                    <p className="font-semibold text-sm font-mono">{a.loan?.loanRef}</p>
                    <p className="text-xs text-muted-foreground">{a.loan?.member?.fullName} · {a.loan?.member?.memberNo}</p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      Level {a.level} approval · {formatCurrency(a.loan?.principalAmount)}
                    </p>
                  </div>
                  <div className="text-right">
                    <Badge variant="warning">PENDING</Badge>
                    <p className="text-xs text-muted-foreground mt-1">{fmtDate(a.loan?.createdAt)}</p>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>
      </Modal>

      {/* ══ New Loan Modal ══ */}
      <Modal
        open={newModal}
        onClose={() => setNewModal(false)}
        size="2xl"
        title="New Loan Application"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setNewModal(false)}>Cancel</Button>
            <Button
              size="sm"
              loading={createMutation.isPending}
              onClick={() => createMutation.mutate({
                memberId:        form.memberId,
                productId:       form.productId,
                principalAmount: parseFloat(form.principalAmount || '0'),
                tenor:           parseInt(form.tenor || '0'),
                tenorUnit:       form.tenorUnit,
                purpose:         form.purpose         || undefined,
                applicationDate: form.applicationDate || undefined,
              })}
            >
              Create Loan Application
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Alert variant="info">
            A loan schedule will be generated automatically based on the selected product's settings.
            You can add collateral, guarantors and appraisal after creation.
          </Alert>
          <FormGrid cols={2}>
            <Select
              label="Member" required
              value={form.memberId}
              onChange={e => setField('memberId', e.target.value)}
              placeholder="Select member…"
              options={(membersData ?? []).map((m: any) => ({ value: m.id, label: `${m.fullName} (${m.memberNo})` }))}
            />
            <Select
              label="Loan Product" required
              value={form.productId}
              onChange={e => setField('productId', e.target.value)}
              placeholder="Select product…"
              options={(productsData ?? []).map((p: any) => ({ value: p.id, label: p.name }))}
            />
            <Input
              label="Principal Amount (KES)" required type="number" min={0}
              value={form.principalAmount}
              onChange={e => setField('principalAmount', e.target.value)}
            />
            <div className="flex gap-2">
              <div className="flex-1">
                <Input
                  label="Tenor" required type="number" min={1}
                  value={form.tenor}
                  onChange={e => setField('tenor', e.target.value)}
                />
              </div>
              <div className="w-32">
                <Select
                  label="Unit"
                  value={form.tenorUnit}
                  onChange={e => setField('tenorUnit', e.target.value)}
                  options={[
                    { value: 'MONTHS', label: 'Months' },
                    { value: 'WEEKS',  label: 'Weeks'  },
                    { value: 'DAYS',   label: 'Days'   },
                  ]}
                />
              </div>
            </div>
            <Input
              label="Application Date"
              type="date"
              hint="Leave blank for today. Use this to backdate."
              value={form.applicationDate}
              onChange={e => setField('applicationDate', e.target.value)}
            />
            <Input
              label="Purpose"
              value={form.purpose}
              onChange={e => setField('purpose', e.target.value)}
              placeholder="Business expansion, school fees…"
            />
          </FormGrid>
        </div>
      </Modal>
    </div>
  )
}
