import React, { useState } from 'react'
import DashboardLayout from '@/components/layout/DashboardLayout'
import { useSession } from 'next-auth/react'
import {
  MagnifyingGlassIcon,
  FunnelIcon,
  EllipsisHorizontalIcon,
  CalendarIcon,
  BanknotesIcon,
  ClockIcon,
  ExclamationTriangleIcon,
  DocumentTextIcon,
} from '@heroicons/react/24/outline'
import { Menu, Transition } from '@headlessui/react'
import { Fragment } from 'react'

type LoanStatus = 'Active' | 'Pending Approval' | 'Overdue' | 'Completed' | 'Defaulted' | 'Restructured'
type LoanType = 'Business Expansion' | 'Working Capital' | 'Asset Financing' | 'Invoice Discounting' | 'Emergency Loan'
type RepaymentFrequency = 'Daily' | 'Weekly' | 'Monthly' | 'Quarterly'

interface Loan {
  id: string
  clientName: string
  businessName: string
  loanType: LoanType
  amount: number
  interestRate: number
  disbursementDate: string
  dueDate: string
  status: LoanStatus
  repaymentFrequency: RepaymentFrequency
  totalRepaid: number
  remainingBalance: number
  nextPaymentDate: string
  nextPaymentAmount: number
  collateral?: {
    type: string
    value: number
    description: string
  }
  guarantors: string[]
  latePayments: number
  restructured: boolean
  documents: {
    offerLetter: boolean
    contract: boolean
    collateralDocs: boolean
    guarantorForms: boolean
  }
}

const sampleLoans: Loan[] = [
  {
    id: 'L001',
    clientName: 'Wanjiku Kamau',
    businessName: 'Kamau Fresh Produce',
    loanType: 'Working Capital',
    amount: 250000,
    interestRate: 15,
    disbursementDate: '2024-01-15',
    dueDate: '2024-07-15',
    status: 'Active',
    repaymentFrequency: 'Monthly',
    totalRepaid: 100000,
    remainingBalance: 150000,
    nextPaymentDate: '2024-03-15',
    nextPaymentAmount: 25000,
    collateral: {
      type: 'Land',
      value: 1000000,
      description: '2 Acres Agricultural Land in Nyeri'
    },
    guarantors: ['John Mwangi', 'Grace Njeri'],
    latePayments: 0,
    restructured: false,
    documents: {
      offerLetter: true,
      contract: true,
      collateralDocs: true,
      guarantorForms: true
    }
  },
  {
    id: 'L002',
    clientName: 'Odhiambo Otieno',
    businessName: 'Quick Shuttle Services',
    loanType: 'Asset Financing',
    amount: 500000,
    interestRate: 18,
    disbursementDate: '2024-02-01',
    dueDate: '2025-02-01',
    status: 'Active',
    repaymentFrequency: 'Monthly',
    totalRepaid: 50000,
    remainingBalance: 450000,
    nextPaymentDate: '2024-03-01',
    nextPaymentAmount: 50000,
    collateral: {
      type: 'Vehicle',
      value: 800000,
      description: '2020 Toyota Hiace'
    },
    guarantors: ['Peter Ouko', 'Sarah Akinyi'],
    latePayments: 1,
    restructured: false,
    documents: {
      offerLetter: true,
      contract: true,
      collateralDocs: true,
      guarantorForms: true
    }
  },
  {
    id: 'L003',
    clientName: 'Amina Hassan',
    businessName: 'Amina Beauty Shop',
    loanType: 'Business Expansion',
    amount: 150000,
    interestRate: 15,
    disbursementDate: '2024-02-10',
    dueDate: '2024-08-10',
    status: 'Pending Approval',
    repaymentFrequency: 'Monthly',
    totalRepaid: 0,
    remainingBalance: 150000,
    nextPaymentDate: '2024-03-10',
    nextPaymentAmount: 30000,
    guarantors: ['Fatuma Ali'],
    latePayments: 0,
    restructured: false,
    documents: {
      offerLetter: true,
      contract: false,
      collateralDocs: false,
      guarantorForms: true
    }
  },
  {
    id: 'L004',
    clientName: 'Kipchoge Kiprotich',
    businessName: 'Tech Solutions Kenya',
    loanType: 'Working Capital',
    amount: 300000,
    interestRate: 15,
    disbursementDate: '2023-08-15',
    dueDate: '2024-02-15',
    status: 'Defaulted',
    repaymentFrequency: 'Monthly',
    totalRepaid: 100000,
    remainingBalance: 200000,
    nextPaymentDate: '2024-02-15',
    nextPaymentAmount: 60000,
    guarantors: ['William Ruto', 'David Kimani'],
    latePayments: 3,
    restructured: true,
    documents: {
      offerLetter: true,
      contract: true,
      collateralDocs: false,
      guarantorForms: true
    }
  },
  {
    id: 'L005',
    clientName: 'Njeri Muthoni',
    businessName: 'Njeri Cereals & Supplies',
    loanType: 'Invoice Discounting',
    amount: 450000,
    interestRate: 12,
    disbursementDate: '2023-06-20',
    dueDate: '2023-12-20',
    status: 'Completed',
    repaymentFrequency: 'Monthly',
    totalRepaid: 450000,
    remainingBalance: 0,
    nextPaymentDate: '2023-12-20',
    nextPaymentAmount: 0,
    collateral: {
      type: 'Commercial Property',
      value: 2000000,
      description: 'Shop Space in Nakuru CBD'
    },
    guarantors: ['James Kariuki', 'Mary Wangari'],
    latePayments: 0,
    restructured: false,
    documents: {
      offerLetter: true,
      contract: true,
      collateralDocs: true,
      guarantorForms: true
    }
  }
]

const statusColors: Record<LoanStatus, string> = {
  'Active': 'bg-green-100 text-green-800',
  'Pending Approval': 'bg-yellow-100 text-yellow-800',
  'Overdue': 'bg-orange-100 text-orange-800',
  'Completed': 'bg-blue-100 text-blue-800',
  'Defaulted': 'bg-red-100 text-red-800',
  'Restructured': 'bg-purple-100 text-purple-800'
}

export default function LoansPage() {
  const { data: session, status } = useSession()
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedStatus, setSelectedStatus] = useState<'all' | LoanStatus>('all')
  const [selectedLoanType, setSelectedLoanType] = useState<'all' | LoanType>('all')

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

  if (!session) {
    return null
  }

  const filteredLoans = sampleLoans.filter(loan => {
    const matchesSearch = 
      loan.clientName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      loan.businessName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      loan.id.toLowerCase().includes(searchTerm.toLowerCase())
    
    const matchesStatus = selectedStatus === 'all' || loan.status === selectedStatus
    const matchesType = selectedLoanType === 'all' || loan.loanType === selectedLoanType

    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">Loan Management</h1>
            <p className="mt-2 text-sm text-gray-700">
              Monitor active loans, process applications, and manage repayments.
            </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"
            >
              New Loan Application
            </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 client, business, or loan ID..."
              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' | LoanStatus)}
                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="Pending Approval">Pending Approval</option>
                <option value="Overdue">Overdue</option>
                <option value="Completed">Completed</option>
                <option value="Defaulted">Defaulted</option>
                <option value="Restructured">Restructured</option>
              </select>
            </div>
            <div className="flex items-center gap-2">
              <BanknotesIcon className="h-5 w-5 text-gray-400" />
              <select
                value={selectedLoanType}
                onChange={(e) => setSelectedLoanType(e.target.value as 'all' | LoanType)}
                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 Loan Types</option>
                <option value="Business Expansion">Business Expansion</option>
                <option value="Working Capital">Working Capital</option>
                <option value="Asset Financing">Asset Financing</option>
                <option value="Invoice Discounting">Invoice Discounting</option>
                <option value="Emergency Loan">Emergency Loan</option>
              </select>
            </div>
          </div>
        </div>

        {/* Loans 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">
                        Loan Details
                      </th>
                      <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                        Client Information
                      </th>
                      <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                        Payment Status
                      </th>
                      <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                        Documents
                      </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">
                    {filteredLoans.map((loan) => (
                      <tr key={loan.id}>
                        <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">
                              {loan.id} - {loan.loanType}
                            </div>
                            <div className="text-gray-500">
                              KES {loan.amount.toLocaleString()} @ {loan.interestRate}%
                            </div>
                            <div className="flex items-center gap-2 text-gray-500">
                              <CalendarIcon className="h-4 w-4" />
                              Disbursed: {loan.disbursementDate}
                            </div>
                            <div className="flex items-center gap-2 text-gray-500">
                              <ClockIcon className="h-4 w-4" />
                              Due: {loan.dueDate}
                            </div>
                          </div>
                        </td>
                        <td className="whitespace-nowrap px-3 py-4">
                          <div className="flex flex-col">
                            <div className="font-medium text-gray-900">{loan.clientName}</div>
                            <div className="text-gray-500">{loan.businessName}</div>
                            <div className="text-gray-500">
                              {loan.guarantors.length} Guarantor{loan.guarantors.length !== 1 ? 's' : ''}
                            </div>
                            {loan.collateral && (
                              <div className="text-gray-500">
                                Collateral: {loan.collateral.type}
                              </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[loan.status]}`}>
                              {loan.status}
                            </span>
                            <div className="text-sm">
                              <div className="font-medium text-gray-900">
                                Repaid: KES {loan.totalRepaid.toLocaleString()}
                              </div>
                              <div className="text-gray-500">
                                Balance: KES {loan.remainingBalance.toLocaleString()}
                              </div>
                              <div className="text-gray-500">
                                Next: KES {loan.nextPaymentAmount.toLocaleString()}
                              </div>
                              <div className="text-gray-500">
                                Due: {loan.nextPaymentDate}
                              </div>
                            </div>
                            {loan.latePayments > 0 && (
                              <div className="flex items-center gap-1 text-red-600">
                                <ExclamationTriangleIcon className="h-4 w-4" />
                                <span>{loan.latePayments} late payment{loan.latePayments !== 1 ? 's' : ''}</span>
                              </div>
                            )}
                            {loan.restructured && (
                              <div className="text-purple-600 text-sm">
                                Restructured
                              </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 ${loan.documents.offerLetter ? 'text-green-600' : 'text-gray-400'}`}>
                              <DocumentTextIcon className="h-4 w-4" />
                              <span>Offer Letter</span>
                            </div>
                            <div className={`flex items-center gap-1 ${loan.documents.contract ? 'text-green-600' : 'text-gray-400'}`}>
                              <DocumentTextIcon className="h-4 w-4" />
                              <span>Contract</span>
                            </div>
                            <div className={`flex items-center gap-1 ${loan.documents.collateralDocs ? 'text-green-600' : 'text-gray-400'}`}>
                              <DocumentTextIcon className="h-4 w-4" />
                              <span>Collateral Docs</span>
                            </div>
                            <div className={`flex items-center gap-1 ${loan.documents.guarantorForms ? 'text-green-600' : 'text-gray-400'}`}>
                              <DocumentTextIcon className="h-4 w-4" />
                              <span>Guarantor Forms</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 Details
                                      </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 Schedule
                                      </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`}
                                      >
                                        Generate Statement
                                      </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`}
                                      >
                                        Download Documents
                                      </a>
                                    )}
                                  </Menu.Item>
                                  {loan.status === 'Active' && (
                                    <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>
    </DashboardLayout>
  )
} 