'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 { Clock, CheckCircle2, XCircle, RotateCcw, Eye, User, Users, Shield } from 'lucide-react'
import { StatCard, Card, Badge, Button, Modal, Textarea, PageHeader, Amount, LoadingSpinner } from '@/components/ui/components'

export default function ApprovalsPage() {
  const router = useRouter()
  const qc     = useQueryClient()
  const [selected, setSelected] = useState<any>(null)
  const [action, setAction]     = useState<'APPROVE' | 'DECLINE' | 'RETURN'>('APPROVE')
  const [comments, setComments] = useState('')
  const [modal, setModal]       = useState(false)

  // Use the pending_approvals endpoint that respects assignedToId, role & group membership
  const { data, isLoading } = useQuery({
    queryKey: ['pending-approvals'],
    queryFn: () => axios.get('/api/loans?sub=pending_approvals').then(r => r.data),
    refetchInterval: 30000,
  })

  const actMutation = useMutation({
    mutationFn: ({ loanId, level, action, comments }: any) =>
      axios.patch(`/api/loans/${loanId}`, { action, level, comments }),
    onSuccess: () => {
      toast.success(`Loan ${action.toLowerCase()}d`)
      qc.invalidateQueries({ queryKey: ['pending-approvals'] })
      setModal(false); setComments('')
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? e.message ?? 'Action failed'),
  })

  const approvals = data?.data ?? []

  function openAction(loan: any, act: 'APPROVE' | 'DECLINE' | 'RETURN') {
    setSelected(loan)
    setAction(act)
    setComments('')
    setModal(true)
  }

  const pendingLevel = (loan: any) => loan.status === 'PENDING_L1' ? 1 : loan.status === 'PENDING_L2' ? 2 : 3

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">
      <PageHeader title="Pending Approvals" description="Loans awaiting your decision" icon={<Clock className="w-6 h-6" />} />

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <StatCard label="My Pending Approvals" value={approvals.length} sub="Assigned to you" icon={<Clock className="w-5 h-5" />} color="amber" />
        <StatCard label="Levels" value={[...new Set(approvals.map((a: any) => a.level))].length} sub="Unique levels" icon={<Shield className="w-5 h-5" />} color="blue" />
        <StatCard label="Total Pending" value={approvals.length} sub="Awaiting your decision" icon={<Clock className="w-5 h-5" />} color="red" />
      </div>

      {isLoading ? <LoadingSpinner /> : (
        <Card>
          <div className="overflow-x-auto">
            <table className="table-lms w-full">
              <thead>
                <tr>
                  <th>Loan Ref</th><th>Member</th><th>Product</th><th>Amount</th>
                  <th>Level</th><th>Assignment</th><th>Submitted</th><th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {approvals.length === 0 ? (
                  <tr><td colSpan={8} className="text-center py-12 text-muted-foreground">
                    <CheckCircle2 className="w-10 h-10 mx-auto mb-2 text-green-500 opacity-50" />
                    No pending approvals — all clear!
                  </td></tr>
                ) : approvals.map((a: any) => {
                  const loan = a.loan ?? a
                  return (
                  <tr key={a.id}>
                    <td>
                      <a className="text-primary hover:underline font-mono text-sm cursor-pointer"
                        onClick={() => router.push(`/loans/${loan.id}`)}>{loan.loanRef}</a>
                    </td>
                    <td>
                      <p className="font-medium text-sm">{loan.member?.fullName}</p>
                      <p className="text-xs text-muted-foreground">{loan.member?.memberNo}</p>
                    </td>
                    <td className="text-sm">{loan.product?.name}</td>
                    <td className="font-semibold"><Amount value={loan.principalAmount} /></td>
                    <td>
                      <Badge variant={a.level === 1 ? 'warning' : a.level === 2 ? 'info' : 'default'}>
                        Level {a.level}
                      </Badge>
                    </td>
                    <td>
                      <div className="flex items-center gap-1 text-xs text-muted-foreground">
                        {a.assignedToId ? <><User className="w-3 h-3"/> Assigned</> : a.requiredRoleId ? <><Shield className="w-3 h-3"/> Role</> : <><Users className="w-3 h-3"/> Group</>}
                      </div>
                    </td>
                    <td className="text-xs text-muted-foreground">{fmtDate(loan.createdAt ?? a.createdAt)}</td>
                    <td>
                      <div className="flex items-center gap-1">
                        <Button size="xs" variant="ghost" icon={<Eye className="w-3.5 h-3.5" />}
                          onClick={() => router.push(`/loans/${loan.id}`)}>View</Button>
                        <Button size="xs" variant="success" icon={<CheckCircle2 className="w-3.5 h-3.5" />}
                          onClick={() => openAction({ ...loan, level: a.level }, 'APPROVE')}>Approve</Button>
                        <Button size="xs" variant="outline" icon={<RotateCcw className="w-3.5 h-3.5" />}
                          onClick={() => openAction({ ...loan, level: a.level }, 'RETURN')}>Return</Button>
                        <Button size="xs" variant="destructive" icon={<XCircle className="w-3.5 h-3.5" />}
                          onClick={() => openAction({ ...loan, level: a.level }, 'DECLINE')}>Decline</Button>
                      </div>
                    </td>
                  </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* Action modal */}
      <Modal
        open={modal}
        onClose={() => setModal(false)}
        title={`${action === 'APPROVE' ? 'Approve' : action === 'DECLINE' ? 'Decline' : 'Return'} Loan — ${selected?.loanRef}`}
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setModal(false)}>Cancel</Button>
            <Button
              variant={action === 'APPROVE' ? 'success' : action === 'DECLINE' ? 'destructive' : 'outline'}
              size="sm"
              loading={actMutation.isPending}
              onClick={() => actMutation.mutate({ loanId: selected?.id, level: selected?.level, action, comments })}
            >
              Confirm {action === 'APPROVE' ? 'Approval' : action === 'DECLINE' ? 'Decline' : 'Return'}
            </Button>
          </>
        }
      >
        {selected && (
          <div className="space-y-4">
            <div className="p-4 bg-muted/40 rounded-lg grid grid-cols-2 gap-3 text-sm">
              <div><p className="text-xs text-muted-foreground">Member</p><p className="font-medium">{selected.member?.fullName}</p></div>
              <div><p className="text-xs text-muted-foreground">Amount</p><p className="font-bold text-lg"><Amount value={selected.principalAmount} /></p></div>
              <div><p className="text-xs text-muted-foreground">Product</p><p className="font-medium">{selected.product?.name}</p></div>
              <div><p className="text-xs text-muted-foreground">Purpose</p><p className="font-medium">{selected.purpose}</p></div>
            </div>
            <Textarea
              label={action === 'APPROVE' ? 'Approval Conditions (optional)' : action === 'DECLINE' ? 'Decline Reason (required)' : 'Return Reason / Feedback (required)'}
              required={action !== 'APPROVE'}
              rows={4}
              value={comments}
              onChange={e => setComments(e.target.value)}
              placeholder={
                action === 'APPROVE' ? 'Add any conditions or notes...'
                  : action === 'DECLINE' ? 'State the reason for declining...'
                  : 'Describe what needs to be corrected...'
              }
            />
          </div>
        )}
      </Modal>
    </div>
  )
}
