import React, { useState, Fragment } from 'react'
import DashboardLayout from '@/components/layout/DashboardLayout'
import { useSession } from 'next-auth/react'
import {
  MagnifyingGlassIcon,
  FunnelIcon,
  EllipsisHorizontalIcon,
  PhoneIcon,
  EnvelopeIcon,
  MapPinIcon,
  IdentificationIcon,
  BuildingOfficeIcon,
  BanknotesIcon,
  ArrowDownTrayIcon,
  XMarkIcon,
  CheckCircleIcon,
  XCircleIcon,
  ChartBarIcon,
  ClockIcon,
  DocumentTextIcon,
} from '@heroicons/react/24/outline'
import { Menu, Transition, Dialog } from '@headlessui/react'

type BusinessType = 'Retail' | 'Agriculture' | 'Transport' | 'Manufacturing' | 'Services' | 'Technology'
type ClientStatus = 'Active' | 'Defaulted' | 'Pending Review' | 'Blacklisted' | 'Completed'

interface Client {
  id: string
  name: string
  nationalId: string
  businessName: string
  businessType: BusinessType
  businessLocation: string
  email: string
  phone: string
  status: ClientStatus
  joinDate: string
  activeLoans: number
  totalBorrowed: number
  totalRepaid: number
  creditScore: number
  guarantors: string[]
  mpesaStatements: boolean
  bankStatements: boolean
  businessRegistration: boolean
  collateral?: {
    type: string
    value: number
    description: string
  }
}

const sampleClients: Client[] = [
  {
    id: 'C001',
    name: 'Wanjiku Kamau',
    nationalId: '24891234',
    businessName: 'Kamau Fresh Produce',
    businessType: 'Agriculture',
    businessLocation: 'Nyeri Town, Nyeri',
    email: 'wanjiku@gmail.com',
    phone: '+254 712 345 678',
    status: 'Active',
    joinDate: '2024-01-15',
    activeLoans: 1,
    totalBorrowed: 250000,
    totalRepaid: 150000,
    creditScore: 85,
    guarantors: ['John Mwangi', 'Grace Njeri'],
    mpesaStatements: true,
    bankStatements: true,
    businessRegistration: true,
    collateral: {
      type: 'Land',
      value: 1000000,
      description: '2 Acres Agricultural Land in Nyeri'
    }
  },
  {
    id: 'C002',
    name: 'Odhiambo Otieno',
    nationalId: '29876543',
    businessName: 'Quick Shuttle Services',
    businessType: 'Transport',
    businessLocation: 'Kisumu CBD',
    email: 'odhiambo@yahoo.com',
    phone: '+254 722 987 654',
    status: 'Active',
    joinDate: '2024-02-01',
    activeLoans: 2,
    totalBorrowed: 500000,
    totalRepaid: 200000,
    creditScore: 75,
    guarantors: ['Peter Ouko', 'Sarah Akinyi'],
    mpesaStatements: true,
    bankStatements: true,
    businessRegistration: true,
    collateral: {
      type: 'Vehicle',
      value: 800000,
      description: '2020 Toyota Hiace'
    }
  },
  {
    id: 'C003',
    name: 'Amina Hassan',
    nationalId: '31234567',
    businessName: 'Amina Beauty Shop',
    businessType: 'Retail',
    businessLocation: 'Mombasa Road, Nairobi',
    email: 'amina.hassan@gmail.com',
    phone: '+254 733 123 456',
    status: 'Pending Review',
    joinDate: '2024-02-10',
    activeLoans: 0,
    totalBorrowed: 0,
    totalRepaid: 0,
    creditScore: 70,
    guarantors: ['Fatuma Ali'],
    mpesaStatements: true,
    bankStatements: false,
    businessRegistration: true
  },
  {
    id: 'C004',
    name: 'Kipchoge Kiprotich',
    nationalId: '27654321',
    businessName: 'Tech Solutions Kenya',
    businessType: 'Technology',
    businessLocation: 'Westlands, Nairobi',
    email: 'kipchoge@techsolutions.co.ke',
    phone: '+254 755 789 012',
    status: 'Defaulted',
    joinDate: '2023-08-15',
    activeLoans: 1,
    totalBorrowed: 300000,
    totalRepaid: 100000,
    creditScore: 45,
    guarantors: ['William Ruto', 'David Kimani'],
    mpesaStatements: true,
    bankStatements: true,
    businessRegistration: true
  },
  {
    id: 'C005',
    name: 'Njeri Muthoni',
    nationalId: '25789012',
    businessName: 'Njeri Cereals & Supplies',
    businessType: 'Retail',
    businessLocation: 'Nakuru Town',
    email: 'njeri.muthoni@yahoo.com',
    phone: '+254 745 678 901',
    status: 'Completed',
    joinDate: '2023-06-20',
    activeLoans: 0,
    totalBorrowed: 450000,
    totalRepaid: 450000,
    creditScore: 92,
    guarantors: ['James Kariuki', 'Mary Wangari'],
    mpesaStatements: true,
    bankStatements: true,
    businessRegistration: true,
    collateral: {
      type: 'Commercial Property',
      value: 2000000,
      description: 'Shop Space in Nakuru CBD'
    }
  }
]

const statusColors: Record<ClientStatus, string> = {
  'Active': 'bg-green-100 text-green-800',
  'Defaulted': 'bg-red-100 text-red-800',
  'Pending Review': 'bg-yellow-100 text-yellow-800',
  'Blacklisted': 'bg-gray-100 text-gray-800',
  'Completed': 'bg-blue-100 text-blue-800'
}

const businessTypeIcons: Record<BusinessType, any> = {
  'Retail': BuildingOfficeIcon,
  'Agriculture': BuildingOfficeIcon,
  'Transport': BuildingOfficeIcon,
  'Manufacturing': BuildingOfficeIcon,
  'Services': BuildingOfficeIcon,
  'Technology': BuildingOfficeIcon
}

interface ClientModalProps {
  client: Client
  isOpen: boolean
  onClose: () => void
}

const ClientModal: React.FC<ClientModalProps> = ({ client, isOpen, onClose }) => {
  const [activeTab, setActiveTab] = useState<'info' | 'loans' | 'documents'>('info')

  const downloadDocument = (documentType: string) => {
    // TODO: Implement actual document download
    console.log(`Downloading ${documentType} for client ${client.id}`)
  }

  return (
    <Dialog as="div" className="relative z-50" open={isOpen} onClose={onClose}>
      <div className="fixed inset-0 bg-black/30" aria-hidden="true" />
      
      <div className="fixed inset-0 overflow-y-auto">
        <div className="flex min-h-full items-center justify-center p-4">
          <Dialog.Panel className="mx-auto max-w-4xl rounded-xl bg-white p-6 shadow-xl">
            <div className="flex justify-between items-center mb-4">
              <Dialog.Title className="text-xl font-semibold">
                Client Profile: {client.name}
              </Dialog.Title>
              <button
                onClick={onClose}
                className="text-gray-400 hover:text-gray-500"
              >
                <XMarkIcon className="h-6 w-6" />
              </button>
            </div>

            {/* Tabs */}
            <div className="border-b border-gray-200 mb-6">
              <nav className="-mb-px flex space-x-8">
                <button
                  onClick={() => setActiveTab('info')}
                  className={`${
                    activeTab === 'info'
                      ? 'border-primary text-primary'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  } whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm`}
                >
                  Basic Information
                </button>
                <button
                  onClick={() => setActiveTab('loans')}
                  className={`${
                    activeTab === 'loans'
                      ? 'border-primary text-primary'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  } whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm`}
                >
                  Loan History
                </button>
                <button
                  onClick={() => setActiveTab('documents')}
                  className={`${
                    activeTab === 'documents'
                      ? 'border-primary text-primary'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  } whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm`}
                >
                  Documents
                </button>
              </nav>
            </div>

            {/* Tab Content */}
            <div className="mt-4">
              {activeTab === 'info' && (
                <div className="grid grid-cols-2 gap-6">
                  <div className="space-y-4">
                    <h3 className="font-semibold text-lg">Personal Information</h3>
                    <div>
                      <p className="text-sm text-gray-500">Full Name</p>
                      <p className="font-medium">{client.name}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">National ID</p>
                      <p className="font-medium">{client.nationalId}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Contact</p>
                      <p className="font-medium flex items-center gap-2">
                        <PhoneIcon className="h-4 w-4" /> {client.phone}
                      </p>
                      <p className="font-medium flex items-center gap-2">
                        <EnvelopeIcon className="h-4 w-4" /> {client.email}
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Credit Score</p>
                      <p className="font-medium">{client.creditScore} / 100</p>
                    </div>
                  </div>

                  <div className="space-y-4">
                    <h3 className="font-semibold text-lg">Business Information</h3>
                    <div>
                      <p className="text-sm text-gray-500">Business Name</p>
                      <p className="font-medium">{client.businessName}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Type</p>
                      <p className="font-medium">{client.businessType}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-500">Location</p>
                      <p className="font-medium flex items-center gap-2">
                        <MapPinIcon className="h-4 w-4" />
                        {client.businessLocation}
                      </p>
                    </div>
                    {client.collateral && (
                      <div>
                        <p className="text-sm text-gray-500">Collateral</p>
                        <div className="bg-gray-50 p-3 rounded-lg">
                          <p className="font-medium">{client.collateral.type}</p>
                          <p className="text-sm">Value: KES {client.collateral.value.toLocaleString()}</p>
                          <p className="text-sm text-gray-600">{client.collateral.description}</p>
                        </div>
                      </div>
                    )}
                  </div>

                  <div className="col-span-2 space-y-4">
                    <h3 className="font-semibold text-lg">Loan Summary</h3>
                    <div className="grid grid-cols-4 gap-4">
                      <div className="bg-gray-50 p-4 rounded-lg">
                        <p className="text-sm text-gray-500">Active Loans</p>
                        <p className="text-xl font-semibold">{client.activeLoans}</p>
                      </div>
                      <div className="bg-gray-50 p-4 rounded-lg">
                        <p className="text-sm text-gray-500">Total Borrowed</p>
                        <p className="text-xl font-semibold">KES {client.totalBorrowed.toLocaleString()}</p>
                      </div>
                      <div className="bg-gray-50 p-4 rounded-lg">
                        <p className="text-sm text-gray-500">Total Repaid</p>
                        <p className="text-xl font-semibold">KES {client.totalRepaid.toLocaleString()}</p>
                      </div>
                      <div className="bg-gray-50 p-4 rounded-lg">
                        <p className="text-sm text-gray-500">Status</p>
                        <p className={`inline-flex rounded-full px-2 text-xs font-semibold leading-5 ${statusColors[client.status]}`}>
                          {client.status}
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="col-span-2">
                    <h3 className="font-semibold text-lg mb-4">Guarantors</h3>
                    <div className="grid grid-cols-2 gap-4">
                      {client.guarantors.map((guarantor, index) => (
                        <div key={index} className="bg-gray-50 p-3 rounded-lg">
                          <p className="font-medium">{guarantor}</p>
                          <p className="text-sm text-gray-500">Guarantor {index + 1}</p>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {activeTab === 'loans' && (
                <div className="space-y-6">
                  <div className="flex justify-between items-center">
                    <h3 className="font-semibold text-lg">Loan History</h3>
                    <button className="text-primary hover:text-secondary font-medium text-sm">
                      View Full History
                    </button>
                  </div>
                  
                  <div className="space-y-4">
                    {/* Sample loan history - replace with actual data */}
                    <div className="border rounded-lg p-4">
                      <div className="flex justify-between items-start mb-4">
                        <div>
                          <p className="font-medium">Working Capital Loan</p>
                          <p className="text-sm text-gray-500">KES 250,000 @ 15%</p>
                        </div>
                        <span className="inline-flex rounded-full px-2 text-xs font-semibold leading-5 bg-green-100 text-green-800">
                          Active
                        </span>
                      </div>
                      <div className="grid grid-cols-4 gap-4 text-sm">
                        <div>
                          <p className="text-gray-500">Disbursed</p>
                          <p className="font-medium">Jan 15, 2024</p>
                        </div>
                        <div>
                          <p className="text-gray-500">Due Date</p>
                          <p className="font-medium">Jul 15, 2024</p>
                        </div>
                        <div>
                          <p className="text-gray-500">Repaid</p>
                          <p className="font-medium">KES 100,000</p>
                        </div>
                        <div>
                          <p className="text-gray-500">Balance</p>
                          <p className="font-medium">KES 150,000</p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {activeTab === 'documents' && (
                <div className="space-y-6">
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <h3 className="font-semibold text-lg mb-4">Required Documents</h3>
                      <div className="space-y-4">
                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                          <div className="flex items-center gap-3">
                            <DocumentTextIcon className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="font-medium">National ID</p>
                              <p className="text-sm text-gray-500">Front and back scanned copies</p>
                            </div>
                          </div>
                          {client.mpesaStatements ? (
                            <div className="flex items-center gap-2">
                              <CheckCircleIcon className="h-5 w-5 text-green-500" />
                              <button
                                onClick={() => downloadDocument('national-id')}
                                className="text-primary hover:text-secondary"
                              >
                                <ArrowDownTrayIcon className="h-5 w-5" />
                              </button>
                            </div>
                          ) : (
                            <XCircleIcon className="h-5 w-5 text-red-500" />
                          )}
                        </div>

                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                          <div className="flex items-center gap-3">
                            <DocumentTextIcon className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="font-medium">M-PESA Statements</p>
                              <p className="text-sm text-gray-500">Last 6 months</p>
                            </div>
                          </div>
                          {client.mpesaStatements ? (
                            <div className="flex items-center gap-2">
                              <CheckCircleIcon className="h-5 w-5 text-green-500" />
                              <button
                                onClick={() => downloadDocument('mpesa-statements')}
                                className="text-primary hover:text-secondary"
                              >
                                <ArrowDownTrayIcon className="h-5 w-5" />
                              </button>
                            </div>
                          ) : (
                            <XCircleIcon className="h-5 w-5 text-red-500" />
                          )}
                        </div>

                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                          <div className="flex items-center gap-3">
                            <DocumentTextIcon className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="font-medium">Bank Statements</p>
                              <p className="text-sm text-gray-500">Last 6 months</p>
                            </div>
                          </div>
                          {client.bankStatements ? (
                            <div className="flex items-center gap-2">
                              <CheckCircleIcon className="h-5 w-5 text-green-500" />
                              <button
                                onClick={() => downloadDocument('bank-statements')}
                                className="text-primary hover:text-secondary"
                              >
                                <ArrowDownTrayIcon className="h-5 w-5" />
                              </button>
                            </div>
                          ) : (
                            <XCircleIcon className="h-5 w-5 text-red-500" />
                          )}
                        </div>

                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                          <div className="flex items-center gap-3">
                            <DocumentTextIcon className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="font-medium">Business Registration</p>
                              <p className="text-sm text-gray-500">Certificate and permits</p>
                            </div>
                          </div>
                          {client.businessRegistration ? (
                            <div className="flex items-center gap-2">
                              <CheckCircleIcon className="h-5 w-5 text-green-500" />
                              <button
                                onClick={() => downloadDocument('business-registration')}
                                className="text-primary hover:text-secondary"
                              >
                                <ArrowDownTrayIcon className="h-5 w-5" />
                              </button>
                            </div>
                          ) : (
                            <XCircleIcon className="h-5 w-5 text-red-500" />
                          )}
                        </div>
                      </div>
                    </div>

                    <div>
                      <h3 className="font-semibold text-lg mb-4">Loan Documents</h3>
                      <div className="space-y-4">
                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                          <div className="flex items-center gap-3">
                            <DocumentTextIcon className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="font-medium">Loan Applications</p>
                              <p className="text-sm text-gray-500">All submitted applications</p>
                            </div>
                          </div>
                          <button
                            onClick={() => downloadDocument('loan-applications')}
                            className="text-primary hover:text-secondary"
                          >
                            <ArrowDownTrayIcon className="h-5 w-5" />
                          </button>
                        </div>

                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                          <div className="flex items-center gap-3">
                            <DocumentTextIcon className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="font-medium">Contracts</p>
                              <p className="text-sm text-gray-500">Signed loan agreements</p>
                            </div>
                          </div>
                          <button
                            onClick={() => downloadDocument('contracts')}
                            className="text-primary hover:text-secondary"
                          >
                            <ArrowDownTrayIcon className="h-5 w-5" />
                          </button>
                        </div>

                        <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                          <div className="flex items-center gap-3">
                            <DocumentTextIcon className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="font-medium">Payment History</p>
                              <p className="text-sm text-gray-500">Complete repayment records</p>
                            </div>
                          </div>
                          <button
                            onClick={() => downloadDocument('payment-history')}
                            className="text-primary hover:text-secondary"
                          >
                            <ArrowDownTrayIcon className="h-5 w-5" />
                          </button>
                        </div>

                        {client.collateral && (
                          <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                            <div className="flex items-center gap-3">
                              <DocumentTextIcon className="h-5 w-5 text-gray-400" />
                              <div>
                                <p className="font-medium">Collateral Documents</p>
                                <p className="text-sm text-gray-500">Asset documentation</p>
                              </div>
                            </div>
                            <button
                              onClick={() => downloadDocument('collateral-docs')}
                              className="text-primary hover:text-secondary"
                            >
                              <ArrowDownTrayIcon className="h-5 w-5" />
                            </button>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>

            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={onClose}
                className="rounded-md px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
              >
                Close
              </button>
              <button
                onClick={() => {/* TODO: Implement edit functionality */}}
                className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-secondary"
              >
                Edit Client
              </button>
            </div>
          </Dialog.Panel>
        </div>
      </div>
    </Dialog>
  )
}

export default function ClientsPage() {
  const { data: session, status } = useSession()
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedStatus, setSelectedStatus] = useState<'all' | ClientStatus>('all')
  const [selectedBusinessType, setSelectedBusinessType] = useState<'all' | BusinessType>('all')
  const [selectedClient, setSelectedClient] = useState<Client | null>(null)

  if (status === 'loading') {
    return <div>Loading...</div>
  }

  if (!session) {
    return null
  }

  const filteredClients = sampleClients.filter(client => {
    const matchesSearch = 
      client.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      client.businessName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      client.nationalId.includes(searchTerm) ||
      client.phone.includes(searchTerm)
    
    const matchesStatus = selectedStatus === 'all' || client.status === selectedStatus
    const matchesType = selectedBusinessType === 'all' || client.businessType === selectedBusinessType

    return matchesSearch && matchesStatus && matchesType
  })

  return (
    <DashboardLayout session={session}>
      <div>
        <div className="sm:flex sm:items-center">
          <div className="sm:flex-auto">
            <h1 className="text-2xl font-semibold text-text-dark">Client Management</h1>
            <p className="mt-2 text-sm text-gray-700">
              Manage client information, loan history, and documentation.
            </p>
          </div>
          <div className="mt-4 sm:ml-16 sm:mt-0 sm:flex-none">
            <button
              type="button"
              className="block rounded-md bg-primary px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-secondary"
            >
              Add New Client
            </button>
          </div>
        </div>

        {/* Filters and Search */}
        <div className="mt-6 flex flex-col sm:flex-row gap-4">
          <div className="relative flex-1">
            <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
              <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
            </div>
            <input
              type="text"
              className="block w-full rounded-md border-0 py-1.5 pl-10 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6"
              placeholder="Search by name, business, ID, or phone..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <FunnelIcon className="h-5 w-5 text-gray-400" />
              <select
                value={selectedStatus}
                onChange={(e) => setSelectedStatus(e.target.value as 'all' | ClientStatus)}
                className="rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary sm:text-sm sm:leading-6"
              >
                <option value="all">All Status</option>
                <option value="Active">Active</option>
                <option value="Defaulted">Defaulted</option>
                <option value="Pending Review">Pending Review</option>
                <option value="Blacklisted">Blacklisted</option>
                <option value="Completed">Completed</option>
              </select>
            </div>
            <div className="flex items-center gap-2">
              <BuildingOfficeIcon className="h-5 w-5 text-gray-400" />
              <select
                value={selectedBusinessType}
                onChange={(e) => setSelectedBusinessType(e.target.value as 'all' | BusinessType)}
                className="rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary sm:text-sm sm:leading-6"
              >
                <option value="all">All Business Types</option>
                <option value="Retail">Retail</option>
                <option value="Agriculture">Agriculture</option>
                <option value="Transport">Transport</option>
                <option value="Manufacturing">Manufacturing</option>
                <option value="Services">Services</option>
                <option value="Technology">Technology</option>
              </select>
            </div>
          </div>
        </div>

        {/* Clients Table */}
        <div className="mt-8 flow-root">
          <div className="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
            <div className="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8">
              <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 sm:rounded-lg">
                <table className="min-w-full divide-y divide-gray-300">
                  <thead className="bg-gray-50">
                    <tr>
                      <th scope="col" className="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6">
                        Client Information
                      </th>
                      <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                        Business Details
                      </th>
                      <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                        Loan Status
                      </th>
                      <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                        Documentation
                      </th>
                      <th scope="col" className="relative py-3.5 pl-3 pr-4 sm:pr-6">
                        <span className="sr-only">Actions</span>
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 bg-white">
                    {filteredClients.map((client) => (
                      <tr 
                        key={client.id}
                        onClick={() => setSelectedClient(client)}
                        className="cursor-pointer hover:bg-gray-50"
                      >
                        <td className="whitespace-nowrap py-4 pl-4 pr-3 sm:pl-6">
                          <div className="flex flex-col">
                            <div className="font-medium text-gray-900">{client.name}</div>
                            <div className="text-gray-500">ID: {client.nationalId}</div>
                            <div className="flex items-center gap-2 text-gray-500">
                              <PhoneIcon className="h-4 w-4" />
                              {client.phone}
                            </div>
                            <div className="flex items-center gap-2 text-gray-500">
                              <EnvelopeIcon className="h-4 w-4" />
                              {client.email}
                            </div>
                          </div>
                        </td>
                        <td className="whitespace-nowrap px-3 py-4">
                          <div className="flex flex-col">
                            <div className="font-medium text-gray-900">{client.businessName}</div>
                            <div className="text-gray-500">{client.businessType}</div>
                            <div className="flex items-center gap-2 text-gray-500">
                              <MapPinIcon className="h-4 w-4" />
                              {client.businessLocation}
                            </div>
                          </div>
                        </td>
                        <td className="whitespace-nowrap px-3 py-4">
                          <div className="flex flex-col gap-2">
                            <span className={`inline-flex rounded-full px-2 text-xs font-semibold leading-5 ${statusColors[client.status]}`}>
                              {client.status}
                            </span>
                            <div className="text-sm">
                              <div className="font-medium text-gray-900">
                                Active Loans: {client.activeLoans}
                              </div>
                              <div className="text-gray-500">
                                Total Borrowed: KES {client.totalBorrowed.toLocaleString()}
                              </div>
                              <div className="text-gray-500">
                                Total Repaid: KES {client.totalRepaid.toLocaleString()}
                              </div>
                              <div className="text-gray-500">
                                Credit Score: {client.creditScore}
                              </div>
                            </div>
                          </div>
                        </td>
                        <td className="whitespace-nowrap px-3 py-4">
                          <div className="flex flex-col gap-1">
                            <div className={`flex items-center gap-1 ${client.mpesaStatements ? 'text-green-600' : 'text-gray-400'}`}>
                              <IdentificationIcon className="h-4 w-4" />
                              <span>M-PESA Statements</span>
                            </div>
                            <div className={`flex items-center gap-1 ${client.bankStatements ? 'text-green-600' : 'text-gray-400'}`}>
                              <BanknotesIcon className="h-4 w-4" />
                              <span>Bank Statements</span>
                            </div>
                            <div className={`flex items-center gap-1 ${client.businessRegistration ? 'text-green-600' : 'text-gray-400'}`}>
                              <BuildingOfficeIcon className="h-4 w-4" />
                              <span>Business Registration</span>
                            </div>
                          </div>
                        </td>
                        <td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
                          <Menu as="div" className="relative inline-block text-left">
                            <div>
                              <Menu.Button className="flex items-center rounded-full bg-gray-100 text-gray-400 hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">
                                <span className="sr-only">Open options</span>
                                <EllipsisHorizontalIcon className="h-5 w-5" aria-hidden="true" />
                              </Menu.Button>
                            </div>

                            <Transition
                              as={Fragment}
                              enter="transition ease-out duration-100"
                              enterFrom="transform opacity-0 scale-95"
                              enterTo="transform opacity-100 scale-100"
                              leave="transition ease-in duration-75"
                              leaveFrom="transform opacity-100 scale-100"
                              leaveTo="transform opacity-0 scale-95"
                            >
                              <Menu.Items className="absolute right-0 z-10 mt-2 w-56 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                                <div className="py-1">
                                  <Menu.Item>
                                    {({ active }) => (
                                      <a
                                        href="#"
                                        className={`${
                                          active ? 'bg-gray-100 text-gray-900' : 'text-gray-700'
                                        } block px-4 py-2 text-sm`}
                                      >
                                        View Profile
                                      </a>
                                    )}
                                  </Menu.Item>
                                  <Menu.Item>
                                    {({ active }) => (
                                      <a
                                        href="#"
                                        className={`${
                                          active ? 'bg-gray-100 text-gray-900' : 'text-gray-700'
                                        } block px-4 py-2 text-sm`}
                                      >
                                        New Loan Application
                                      </a>
                                    )}
                                  </Menu.Item>
                                  <Menu.Item>
                                    {({ active }) => (
                                      <a
                                        href="#"
                                        className={`${
                                          active ? 'bg-gray-100 text-gray-900' : 'text-gray-700'
                                        } block px-4 py-2 text-sm`}
                                      >
                                        View Documents
                                      </a>
                                    )}
                                  </Menu.Item>
                                  <Menu.Item>
                                    {({ active }) => (
                                      <a
                                        href="#"
                                        className={`${
                                          active ? 'bg-gray-100 text-gray-900' : 'text-gray-700'
                                        } block px-4 py-2 text-sm`}
                                      >
                                        Payment History
                                      </a>
                                    )}
                                  </Menu.Item>
                                  <Menu.Item>
                                    {({ active }) => (
                                      <a
                                        href="#"
                                        className={`${
                                          active ? 'bg-gray-100 text-gray-900' : 'text-gray-700'
                                        } block px-4 py-2 text-sm text-red-600`}
                                      >
                                        Mark as Defaulted
                                      </a>
                                    )}
                                  </Menu.Item>
                                </div>
                              </Menu.Items>
                            </Transition>
                          </Menu>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Client Modal */}
      {selectedClient && (
        <ClientModal
          client={selectedClient}
          isOpen={!!selectedClient}
          onClose={() => setSelectedClient(null)}
        />
      )}
    </DashboardLayout>
  )
} 