'use client';

import { useState, useMemo, useEffect, useRef } from 'react';
import {
  Plus, Search, Download, Eye, Edit, Trash2, X, TrendingUp, TrendingDown,
  DollarSign, Calendar, FileText, ArrowDownLeft, ArrowUpRight, Building,
  ChevronLeft, ChevronRight, Wallet, Receipt, BookOpen, PieChart, List,
  Banknote, Smartphone, Users, Home, Wrench, Printer, FileSpreadsheet,
  Filter, ShoppingCart, Tag, Move, Calculator, Save, CreditCard, Bike,
  Clock, Check, CheckCircle
} from 'lucide-react';

export type AccountType = 'asset' | 'liability' | 'equity' | 'income' | 'expense';

export type TransactionType =
  | 'deposit'
  | 'rent_income'
  | 'investor_funding'
  | 'investor_withdraw'
  | 'salary'
  | 'rent_expense'
  | 'utility'
  | 'maintenance'
  | 'bike_purchase'
  | 'bike_sale'
  | 'other_income'
  | 'other_expense';

export interface ChartOfAccount {
  id: string;
  code: string;
  name: string;
  type: AccountType;
  parentId?: string;
  isActive: boolean;
  balance: number;
}

export interface JournalEntry {
  id: string;
  date: string;
  reference: string;
  description: string;
  entries: {
    accountId: string;
    accountCode: string;
    accountName: string;
    debit: number;
    credit: number;
  }[];
  isPosted: boolean;
  isAuto: boolean;
  sourceType?: TransactionType;
  createdAt: string;
  createdBy: string;
}

export interface AccountingTransaction {
  id: string;
  date: string;
  type: TransactionType;
  amount: number;
  description: string;
  beneficiary?: string;
  beneficiaryPhone?: string;
  paymentMethod: 'cash' | 'bank' | 'mobile';
  reference?: string;
  notes?: string;
  bikeId?: string;
  bikeDetails?: string;
  createdAt: string;
  createdBy: string;
}

export interface WithdrawRequest {
  id: string;
  investorId: string;
  investorName: string;
  phone: string;
  amount: number;
  requestDate: string;
  status: 'pending' | 'approved' | 'completed' | 'rejected';
  bankName: string;
  accountNo: string;
  processedDate?: string;
  paymentMethod?: string;
}

const defaultAccounts: ChartOfAccount[] = [
  { id: 'ASSET-001', code: '1000', name: 'Assets', type: 'asset', isActive: true, balance: 0 },
  { id: 'ASSET-101', code: '1100', name: 'Cash in Hand', type: 'asset', parentId: 'ASSET-001', isActive: true, balance: 85000 },
  { id: 'ASSET-102', code: '1200', name: 'Bank - City Bank', type: 'asset', parentId: 'ASSET-001', isActive: true, balance: 125000 },
  { id: 'ASSET-103', code: '1300', name: 'bKash Business', type: 'asset', parentId: 'ASSET-001', isActive: true, balance: 28000 },
  { id: 'ASSET-104', code: '1400', name: 'Accounts Receivable', type: 'asset', parentId: 'ASSET-001', isActive: true, balance: 15000 },
  { id: 'ASSET-104A', code: '1410', name: 'Cheque Receivable', type: 'asset', parentId: 'ASSET-001', isActive: true, balance: 0 },
  { id: 'ASSET-105', code: '1500', name: 'Bikes & Equipment', type: 'asset', parentId: 'ASSET-001', isActive: true, balance: 2500000 },
  { id: 'ASSET-106', code: '1600', name: 'Bike Inventory', type: 'asset', parentId: 'ASSET-001', isActive: true, balance: 0 },

  { id: 'LIAB-001', code: '2000', name: 'Liabilities', type: 'liability', isActive: true, balance: 0 },
  { id: 'LIAB-201', code: '2100', name: 'Accounts Payable', type: 'liability', parentId: 'LIAB-001', isActive: true, balance: 5000 },
  { id: 'LIAB-202', code: '2200', name: 'Investor Liabilities', type: 'liability', parentId: 'LIAB-001', isActive: true, balance: 500000 },
  { id: 'LIAB-203', code: '2300', name: 'Bike Supplier Payable', type: 'liability', parentId: 'LIAB-001', isActive: true, balance: 0 },

  { id: 'EQUITY-001', code: '3000', name: 'Equity', type: 'equity', isActive: true, balance: 0 },
  { id: 'EQUITY-301', code: '3100', name: 'Owner Equity', type: 'equity', parentId: 'EQUITY-001', isActive: true, balance: 2000000 },
  { id: 'EQUITY-302', code: '3200', name: 'Retained Earnings', type: 'equity', parentId: 'EQUITY-001', isActive: true, balance: 198000 },

  { id: 'INC-001', code: '4000', name: 'Income', type: 'income', isActive: true, balance: 0 },
  { id: 'INC-401', code: '4100', name: 'Bike Deposit Income', type: 'income', parentId: 'INC-001', isActive: true, balance: 50000 },
  { id: 'INC-402', code: '4200', name: 'Rental Income', type: 'income', parentId: 'INC-001', isActive: true, balance: 185000 },
  { id: 'INC-403', code: '4300', name: 'Investor Funding', type: 'income', parentId: 'INC-001', isActive: true, balance: 500000 },
  { id: 'INC-404', code: '4400', name: 'Bike Sales Income', type: 'income', parentId: 'INC-001', isActive: true, balance: 0 },
  { id: 'INC-405', code: '4500', name: 'Other Income', type: 'income', parentId: 'INC-001', isActive: true, balance: 0 },

  { id: 'EXP-001', code: '5000', name: 'Expenses', type: 'expense', isActive: true, balance: 0 },
  { id: 'EXP-501', code: '5100', name: 'Salary Expense', type: 'expense', parentId: 'EXP-001', isActive: true, balance: 25000 },
  { id: 'EXP-502', code: '5200', name: 'Rent Expense', type: 'expense', parentId: 'EXP-001', isActive: true, balance: 35000 },
  { id: 'EXP-503', code: '5300', name: 'Utility Expense', type: 'expense', parentId: 'EXP-001', isActive: true, balance: 8500 },
  { id: 'EXP-504', code: '5400', name: 'Maintenance Expense', type: 'expense', parentId: 'EXP-001', isActive: true, balance: 2500 },
  { id: 'EXP-505', code: '5500', name: 'Investor Withdrawal', type: 'expense', parentId: 'EXP-001', isActive: true, balance: 15000 },
  { id: 'EXP-506', code: '5600', name: 'Bike Cost of Sales', type: 'expense', parentId: 'EXP-001', isActive: true, balance: 0 },
  { id: 'EXP-507', code: '5700', name: 'Other Expense', type: 'expense', parentId: 'EXP-001', isActive: true, balance: 0 },
];

const mockTransactions: AccountingTransaction[] = [
  { id: 'TXN-001', date: '2024-03-20', type: 'deposit', amount: 5000, description: 'Bike deposit from Rahim Ahmed', beneficiary: 'Rahim Ahmed', beneficiaryPhone: '01712345678', paymentMethod: 'cash', reference: 'DEP-001', createdAt: '2024-03-20T10:30:00', createdBy: 'Admin' },
  { id: 'TXN-002', date: '2024-03-20', type: 'rent_income', amount: 1200, description: 'Daily rental - Rahim Ahmed', beneficiary: 'Rahim Ahmed', paymentMethod: 'mobile', reference: 'REN-002', createdAt: '2024-03-20T14:00:00', createdBy: 'Admin' },
  { id: 'TXN-003', date: '2024-03-19', type: 'investor_funding', amount: 50000, description: 'Investment from Mohammad Islam', beneficiary: 'Mohammad Islam', beneficiaryPhone: '01987654321', paymentMethod: 'bank', reference: 'INV-001', createdAt: '2024-03-19T09:00:00', createdBy: 'Admin' },
  { id: 'TXN-004', date: '2024-03-19', type: 'salary', amount: 25000, description: 'Monthly salary - March 2024', beneficiary: 'Staff Team', paymentMethod: 'bank', reference: 'SAL-003', createdAt: '2024-03-19T16:00:00', createdBy: 'Admin' },
  { id: 'TXN-005', date: '2024-03-18', type: 'rent_expense', amount: 35000, description: 'Office rent - March 2024', beneficiary: 'Landlord', paymentMethod: 'bank', reference: 'RNT-001', createdAt: '2024-03-18T10:00:00', createdBy: 'Admin' },
  { id: 'TXN-006', date: '2024-03-18', type: 'utility', amount: 8500, description: 'Electricity bill - March 2024', beneficiary: 'DESCO', paymentMethod: 'mobile', reference: 'UTL-001', createdAt: '2024-03-18T11:30:00', createdBy: 'Admin' },
  { id: 'TXN-007', date: '2024-03-17', type: 'investor_withdraw', amount: 15000, description: 'Monthly profit withdrawal', beneficiary: 'Mohammad Islam', beneficiaryPhone: '01987654321', paymentMethod: 'bank', reference: 'WTH-002', createdAt: '2024-03-17T15:00:00', createdBy: 'Admin' },
  { id: 'TXN-008', date: '2024-03-17', type: 'maintenance', amount: 2500, description: 'Bike maintenance - Battery', beneficiary: 'Service Center', paymentMethod: 'cash', reference: 'MNT-001', createdAt: '2024-03-17T13:00:00', createdBy: 'Admin' },
  { id: 'TXN-009', date: '2024-03-15', type: 'bike_purchase', amount: 150000, description: 'Purchased 5 EVs from supplier', beneficiary: 'Green EV Bangladesh', beneficiaryPhone: '02-1234567', paymentMethod: 'bank', reference: 'PUR-001', bikeDetails: '5x Yadea DT3', createdAt: '2024-03-15T09:00:00', createdBy: 'Admin' },
  { id: 'TXN-010', date: '2024-03-10', type: 'bike_sale', amount: 45000, description: 'Sold EV to customer', beneficiary: 'John Doe', beneficiaryPhone: '01812345678', paymentMethod: 'bank', reference: 'SAL-001', bikeDetails: 'Dhaka Metro Cha-5679', createdAt: '2024-03-10T11:00:00', createdBy: 'Admin' },
];

const mockJournalEntries: JournalEntry[] = [
  {
    id: 'JE-001', date: '2024-03-20', reference: 'DEP-001', description: 'Bike deposit from Rahim Ahmed',
    entries: [
      { accountId: 'ASSET-101', accountCode: '1100', accountName: 'Cash in Hand', debit: 5000, credit: 0 },
      { accountId: 'INC-401', accountCode: '4100', accountName: 'Bike Deposit Income', debit: 0, credit: 5000 },
    ],
    isPosted: true, isAuto: false, sourceType: 'deposit', createdAt: '2024-03-20T10:30:00', createdBy: 'Admin',
  },
  {
    id: 'JE-002', date: '2024-03-20', reference: 'REN-002', description: 'Daily rental income',
    entries: [
      { accountId: 'ASSET-103', accountCode: '1300', accountName: 'bKash Business', debit: 1200, credit: 0 },
      { accountId: 'INC-402', accountCode: '4200', accountName: 'Rental Income', debit: 0, credit: 1200 },
    ],
    isPosted: true, isAuto: true, sourceType: 'rent_income', createdAt: '2024-03-20T14:00:00', createdBy: 'System',
  },
  {
    id: 'JE-003', date: '2024-03-19', reference: 'INV-001', description: 'Investment received',
    entries: [
      { accountId: 'ASSET-102', accountCode: '1200', accountName: 'Bank - City Bank', debit: 50000, credit: 0 },
      { accountId: 'LIAB-202', accountCode: '2200', accountName: 'Investor Liabilities', debit: 0, credit: 50000 },
    ],
    isPosted: true, isAuto: true, sourceType: 'investor_funding', createdAt: '2024-03-19T09:00:00', createdBy: 'System',
  },
  {
    id: 'JE-004', date: '2024-03-19', reference: 'SAL-003', description: 'Monthly salary payment',
    entries: [
      { accountId: 'EXP-501', accountCode: '5100', accountName: 'Salary Expense', debit: 25000, credit: 0 },
      { accountId: 'ASSET-102', accountCode: '1200', accountName: 'Bank - City Bank', debit: 0, credit: 25000 },
    ],
    isPosted: true, isAuto: false, sourceType: 'salary', createdAt: '2024-03-19T16:00:00', createdBy: 'Admin',
  },
  {
    id: 'JE-005', date: '2024-03-15', reference: 'PUR-001', description: 'Purchased 5 EVs',
    entries: [
      { accountId: 'ASSET-105', accountCode: '1500', accountName: 'Bikes & Equipment', debit: 150000, credit: 0 },
      { accountId: 'ASSET-102', accountCode: '1200', accountName: 'Bank - City Bank', debit: 0, credit: 150000 },
    ],
    isPosted: true, isAuto: true, sourceType: 'bike_purchase', createdAt: '2024-03-15T09:00:00', createdBy: 'System',
  },
  {
    id: 'JE-006', date: '2024-03-10', reference: 'SAL-001', description: 'Sold EV to customer',
    entries: [
      { accountId: 'ASSET-102', accountCode: '1200', accountName: 'Bank - City Bank', debit: 45000, credit: 0 },
      { accountId: 'INC-404', accountCode: '4400', accountName: 'Bike Sales Income', debit: 0, credit: 45000 },
    ],
    isPosted: true, isAuto: true, sourceType: 'bike_sale', createdAt: '2024-03-10T11:00:00', createdBy: 'System',
  },
  {
    id: 'JE-007', date: '2024-03-17', reference: 'WTH-002', description: 'Investor profit withdrawal',
    entries: [
      { accountId: 'LIAB-202', accountCode: '2200', accountName: 'Investor Liabilities', debit: 15000, credit: 0 },
      { accountId: 'ASSET-102', accountCode: '1200', accountName: 'Bank - City Bank', debit: 0, credit: 15000 },
    ],
    isPosted: true, isAuto: true, sourceType: 'investor_withdraw', createdAt: '2024-03-17T15:00:00', createdBy: 'System',
  },
];

const accountTypeConfig: Record<AccountType, { label: string; color: string; bg: string }> = {
  asset: { label: 'Asset', color: 'text-blue-600', bg: 'bg-blue-50' },
  liability: { label: 'Liability', color: 'text-red-600', bg: 'bg-red-50' },
  equity: { label: 'Equity', color: 'text-purple-600', bg: 'bg-purple-50' },
  income: { label: 'Income', color: 'text-green-600', bg: 'bg-green-50' },
  expense: { label: 'Expense', color: 'text-amber-600', bg: 'bg-amber-50' },
};

const transactionTypeConfig: Record<TransactionType, { label: string; category: 'income' | 'expense' | 'asset'; icon: React.ElementType }> = {
  deposit: { label: 'Bike Deposit', category: 'income', icon: Banknote },
  rent_income: { label: 'Rental Income', category: 'income', icon: Tag },
  investor_funding: { label: 'Investor Funding', category: 'income', icon: Users },
  investor_withdraw: { label: 'Investor Withdraw', category: 'expense', icon: Users },
  salary: { label: 'Salary Payment', category: 'expense', icon: Users },
  rent_expense: { label: 'Office Rent', category: 'expense', icon: Home },
  utility: { label: 'Utility Bills', category: 'expense', icon: Building },
  maintenance: { label: 'Maintenance', category: 'expense', icon: Wrench },
  bike_purchase: { label: 'Buy Bike', category: 'asset', icon: ShoppingCart },
  bike_sale: { label: 'Sell Bike', category: 'income', icon: Bike },
  other_income: { label: 'Other Income', category: 'income', icon: DollarSign },
  other_expense: { label: 'Other Expense', category: 'expense', icon: DollarSign },
};

function generateAutoJournalEntries(type: TransactionType, amount: number, description: string, isManualEntry: boolean = false): JournalEntry['entries'] {
  if (isManualEntry) return [];

  const config: Partial<Record<TransactionType, { debitAccount: string; debitCode: string; creditAccount: string; creditCode: string }>> = {
    rent_income: { debitAccount: 'ASSET-103', debitCode: '1300', creditAccount: 'INC-402', creditCode: '4200' },
    investor_funding: { debitAccount: 'ASSET-102', debitCode: '1200', creditAccount: 'LIAB-202', creditCode: '2200' },
    investor_withdraw: { debitAccount: 'LIAB-202', debitCode: '2200', creditAccount: 'ASSET-102', creditCode: '1200' },
    bike_purchase: { debitAccount: 'ASSET-105', debitCode: '1500', creditAccount: 'ASSET-102', creditCode: '1200' },
    bike_sale: { debitAccount: 'ASSET-102', debitCode: '1200', creditAccount: 'INC-404', creditCode: '4400' },
  };

  const c = config[type];
  if (!c) return [];

  return [
    { accountId: c.debitAccount, accountCode: c.debitCode, accountName: '', debit: amount, credit: 0 },
    { accountId: c.creditAccount, accountCode: c.creditCode, accountName: '', debit: 0, credit: amount },
  ];
}

export default function AccountingPage() {
  const [activeTab, setActiveTab] = useState<'dashboard' | 'transactions' | 'journal' | 'ledger' | 'accounts' | 'withdraw'>('dashboard');
  const [transactions, setTransactions] = useState(mockTransactions);
  const [accounts] = useState(defaultAccounts);
  const [journalEntries, setJournalEntries] = useState(mockJournalEntries);
  const [searchQuery, setSearchQuery] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [timePeriod, setTimePeriod] = useState<'this_month' | 'last_month' | 'last_3_months'>('this_month');
  const [showModal, setShowModal] = useState(false);
  const [editingTransaction, setEditingTransaction] = useState<AccountingTransaction | null>(null);
  const [viewingTransaction, setViewingTransaction] = useState<AccountingTransaction | null>(null);
  const [showWithdrawModal, setShowWithdrawModal] = useState(false);
  const [payNowModal, setPayNowModal] = useState<WithdrawRequest | null>(null);
  const [paymentForm, setPaymentForm] = useState({ method: 'bank', reference: '', notes: '', date: new Date().toISOString().split('T')[0] });
  const [withdrawRequests, setWithdrawRequests] = useState<WithdrawRequest[]>([
    { id: 'WDR-001', investorId: 'INV-001', investorName: 'Mohammad Islam', phone: '01987654321', amount: 15000, requestDate: '2024-03-20', status: 'pending', bankName: 'City Bank', accountNo: '1234567890' },
    { id: 'WDR-002', investorId: 'INV-002', investorName: 'Rahima Begum', phone: '01876543210', amount: 25000, requestDate: '2024-03-18', status: 'approved', bankName: 'DBBL', accountNo: '9876543210', processedDate: '2024-03-19', paymentMethod: 'bank' },
    { id: 'WDR-003', investorId: 'INV-003', investorName: 'Ahmed Hassan', phone: '01765432109', amount: 8000, requestDate: '2024-03-15', status: 'completed', bankName: 'bKash', accountNo: '01765432109', processedDate: '2024-03-16', paymentMethod: 'mobile' },
  ]);
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  const getDateRange = (period: 'this_month' | 'last_month' | 'last_3_months') => {
    const now = new Date();
    let from: Date, to: Date = new Date(now);
    let label: string;

    if (period === 'this_month') {
      from = new Date(now.getFullYear(), now.getMonth(), 1);
      to = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      label = now.toLocaleString('en-US', { month: 'long', year: 'numeric' });
    } else if (period === 'last_month') {
      from = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      to = new Date(now.getFullYear(), now.getMonth(), 0);
      label = from.toLocaleString('en-US', { month: 'long', year: 'numeric' });
    } else {
      from = new Date(now.getFullYear(), now.getMonth() - 2, 1);
      to = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      const startLabel = from.toLocaleString('en-US', { month: 'short', year: 'numeric' });
      const endLabel = to.toLocaleString('en-US', { month: 'short', year: 'numeric' });
      label = `${startLabel} - ${endLabel}`;
    }

    return {
      from: from.toISOString().split('T')[0],
      to: to.toISOString().split('T')[0],
      label: label
    };
  };

  const periodInfo = getDateRange(timePeriod);

  const filteredTransactions = useMemo(() => {
    return transactions.filter(t => {
      const matchesSearch = !searchQuery ||
        t.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
        t.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
        t.beneficiary?.toLowerCase().includes(searchQuery.toLowerCase());
      const matchesDate = (!dateFrom || t.date >= dateFrom) && (!dateTo || t.date <= dateTo);
      return matchesSearch && matchesDate;
    }).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [transactions, searchQuery, dateFrom, dateTo]);

  const paginatedTransactions = useMemo(() => {
    const start = (currentPage - 1) * itemsPerPage;
    return filteredTransactions.slice(start, start + itemsPerPage);
  }, [filteredTransactions, currentPage]);

  const totalPages = Math.ceil(filteredTransactions.length / itemsPerPage);

  const stats = useMemo(() => {
    const periodRange = getDateRange(timePeriod);
    const transactionData = transactions.filter(t => t.date >= periodRange.from && t.date <= periodRange.to);
    const income = transactionData.filter(t => ['deposit', 'rent_income', 'investor_funding', 'bike_sale', 'other_income'].includes(t.type)).reduce((sum, t) => sum + t.amount, 0);
    const expense = transactionData.filter(t => ['investor_withdraw', 'salary', 'rent_expense', 'utility', 'maintenance', 'bike_purchase', 'other_expense'].includes(t.type)).reduce((sum, t) => sum + t.amount, 0);
    const assets = accounts.filter(a => a.type === 'asset').reduce((sum, a) => sum + a.balance, 0);
    const liabilities = accounts.filter(a => a.type === 'liability').reduce((sum, a) => sum + a.balance, 0);
    const equity = accounts.filter(a => a.type === 'equity').reduce((sum, a) => sum + a.balance, 0);
    return { income, expense, netProfit: income - expense, assets, liabilities, equity: equity + (income - expense), transactionCount: transactionData.length };
  }, [accounts, transactions, timePeriod]);

  const handleSaveTransaction = (data: Partial<AccountingTransaction>, isManual: boolean = false) => {
    const isAuto = !isManual && ['rent_income', 'investor_funding', 'investor_withdraw', 'bike_purchase', 'bike_sale'].includes(data.type || '');
    const autoEntries = isAuto ? generateAutoJournalEntries(data.type!, data.amount!, data.description!, isManual) : [];

    const accMap = Object.fromEntries(accounts.map(a => [a.id, a.name]));
    autoEntries.forEach(e => { e.accountName = accMap[e.accountId] || e.accountName; });

    const newEntry: JournalEntry = {
      id: `JE-${String(Date.now()).slice(-6)}`,
      date: data.date || new Date().toISOString().split('T')[0],
      reference: data.reference || `${data.type?.toUpperCase()}-${Date.now()}`,
      description: data.description || '',
      entries: autoEntries.length > 0 ? autoEntries : [
        { accountId: 'ASSET-101', accountCode: '1100', accountName: 'Cash in Hand', debit: data.amount || 0, credit: 0 },
        { accountId: 'EXP-507', accountCode: '5700', accountName: 'Other Expense', debit: 0, credit: data.amount || 0 },
      ],
      isPosted: true,
      isAuto: isAuto,
      sourceType: data.type,
      createdAt: new Date().toISOString(),
      createdBy: isAuto ? 'System' : 'Admin',
    };

    if (editingTransaction) {
      setTransactions(prev => prev.map(t => t.id === editingTransaction.id ? { ...t, ...data } as AccountingTransaction : t));
    } else {
      const newTransaction: AccountingTransaction = {
        id: `TXN-${String(Date.now()).slice(-6)}`,
        date: data.date || new Date().toISOString().split('T')[0],
        type: data.type || 'other_expense',
        amount: data.amount || 0,
        description: data.description || '',
        beneficiary: data.beneficiary,
        beneficiaryPhone: data.beneficiaryPhone,
        paymentMethod: data.paymentMethod || 'cash',
        reference: data.reference,
        notes: data.notes,
        bikeDetails: data.bikeDetails,
        createdAt: new Date().toISOString(),
        createdBy: 'Admin',
      };
      setTransactions(prev => [newTransaction, ...prev]);
      setJournalEntries(prev => [...prev, newEntry]);
    }
    setShowModal(false);
    setEditingTransaction(null);
  };

  const handleDeleteTransaction = (id: string) => {
    if (confirm('Are you sure you want to delete this transaction?')) {
      const txn = transactions.find(t => t.id === id);
      if (txn) {
        setTransactions(prev => prev.filter(t => t.id !== id));
        setJournalEntries(prev => prev.filter(j => j.reference !== txn.reference));
      }
    }
  };

  const handleExportPDF = () => {
    import('jspdf').then(jsPDF => {
      const doc = new jsPDF.default();

      doc.setFontSize(18);
      doc.setTextColor(6, 95, 70);
      doc.text('JAIBEN Mobility Ltd', 20, 20);

      doc.setFontSize(12);
      doc.setTextColor(0);
      const title = activeTab === 'transactions' ? 'Transactions Report' :
        activeTab === 'journal' ? 'Journal Entries Report' :
          activeTab === 'ledger' ? 'General Ledger Report' : 'Accounting Report';
      doc.text(title, 20, 30);

      doc.setFontSize(9);
      doc.setTextColor(100);
      doc.text(`Date: ${new Date().toLocaleDateString()}`, 20, 38);
      if (dateFrom || dateTo) {
        doc.text(`Period: ${dateFrom || 'Start'} to ${dateTo || 'Now'}`, 20, 45);
      }

      doc.setFontSize(9);
      doc.setTextColor(150);
      doc.text('Generated from JAIBEN Accounting System', 20, 280);

      doc.save(`accounting-${activeTab}-${new Date().toISOString().split('T')[0]}.pdf`);
    });
  };

  const handleExportExcel = () => {
    let csv = '';
    if (activeTab === 'transactions') {
      csv = 'ID,Date,Type,Amount,Beneficiary,Payment Method,Description\n';
      filteredTransactions.forEach(t => {
        csv += `${t.id},${t.type},${t.amount},${t.beneficiary || ''},${t.paymentMethod},${t.description}\n`;
      });
    } else if (activeTab === 'journal') {
      csv = 'Date,Reference,Account,Debit,Credit\n';
      journalEntries.forEach(j => {
        j.entries.forEach(e => {
          csv += `${j.date},${j.reference},${e.accountName},${e.debit},${e.credit}\n`;
        });
      });
    }

    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `accounting-${activeTab}-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
  };

  const handlePrint = () => {
    window.print();
  };

  const tabs = [
    { id: 'dashboard', label: 'Dashboard', icon: PieChart },
    { id: 'transactions', label: 'Transactions', icon: Receipt },
    { id: 'journal', label: 'Journal', icon: BookOpen },
    { id: 'ledger', label: 'Ledger', icon: List },
    { id: 'accounts', label: 'Accounts', icon: Calculator },
    { id: 'withdraw', label: 'Withdraw', icon: ArrowDownLeft },
  ];

  return (
    <div className="p-4 lg:p-6">
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl lg:text-3xl font-extrabold text-slate-800">Accounting</h1>
          <p className="text-sm text-slate-500 mt-1">Double-entry bookkeeping with auto-journals</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => { setEditingTransaction(null); setShowModal(true); }}
            className="inline-flex items-center gap-2 px-4 py-2.5 bg-accent text-white rounded-lg font-semibold hover:bg-accent-dark transition-colors"
          >
            <Plus className="w-5 h-5" />
            <span>New Transaction</span>
          </button>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-slate-200 mb-6">
        <div className="flex overflow-x-auto">
          {tabs.map(tab => {
            const Icon = tab.icon;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as typeof activeTab)}
                className={`flex items-center gap-2 px-5 py-3 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${activeTab === tab.id
                    ? 'border-accent text-accent bg-accent-light/30'
                    : 'border-transparent text-slate-500 hover:text-slate-700 hover:bg-slate-50'
                  }`}
              >
                <Icon className="w-4 h-4" />
                {tab.label}
                {tab.id === 'withdraw' && withdrawRequests.filter(w => w.status === 'pending').length > 0 && (
                  <span className="ml-1 px-1.5 py-0.5 text-xs font-medium bg-orange-100 text-orange-700 rounded-full">
                    {withdrawRequests.filter(w => w.status === 'pending').length}
                  </span>
                )}
              </button>
            );
          })}
        </div>
      </div>

      {(activeTab === 'transactions' || activeTab === 'journal' || activeTab === 'ledger') && (
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-4 mb-6 flex flex-wrap gap-3 items-center">
          <div className="relative flex-1 min-w-[200px]">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
            <input
              type="text"
              placeholder="Search..."
              value={searchQuery}
              onChange={(e) => { setSearchQuery(e.target.value); setCurrentPage(1); }}
              className="w-full pl-10 pr-4 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent/20"
            />
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm text-slate-500">From:</span>
            <input
              type="date"
              value={dateFrom}
              onChange={(e) => { setDateFrom(e.target.value); setCurrentPage(1); }}
              className="px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent/20"
            />
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm text-slate-500">To:</span>
            <input
              type="date"
              value={dateTo}
              onChange={(e) => { setDateTo(e.target.value); setCurrentPage(1); }}
              className="px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent/20"
            />
          </div>
          <div className="flex items-center gap-2">
            <button onClick={handleExportPDF} className="p-2 hover:bg-slate-100 rounded-lg text-slate-600" title="Export PDF">
              <FileText className="w-5 h-5" />
            </button>
            <button onClick={handleExportExcel} className="p-2 hover:bg-slate-100 rounded-lg text-slate-600" title="Export Excel">
              <FileSpreadsheet className="w-5 h-5" />
            </button>
            <button onClick={handlePrint} className="p-2 hover:bg-slate-100 rounded-lg text-slate-600" title="Print">
              <Printer className="w-5 h-5" />
            </button>
          </div>
        </div>
      )}

      {activeTab === 'dashboard' && (
        <>
          <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
            <div>
              <h2 className="text-lg font-bold text-slate-800">Financial Overview</h2>
              <p className="text-sm text-slate-500">{periodInfo.label}</p>
            </div>
            <div className="flex rounded-lg overflow-hidden border border-slate-200 shadow-sm">
              {[
                { id: 'this_month', label: 'This Month' },
                { id: 'last_month', label: 'Last Month' },
                { id: 'last_3_months', label: '3 Months' },
              ].map((period) => (
                <button
                  key={period.id}
                  onClick={() => setTimePeriod(period.id as typeof timePeriod)}
                  className={`px-4 py-2 text-sm font-medium transition-colors ${timePeriod === period.id
                      ? 'bg-accent text-white'
                      : 'bg-white text-slate-600 hover:bg-slate-50'
                    }`}
                >
                  {period.label}
                </button>
              ))}
            </div>
          </div>
          <DashboardView stats={stats} accounts={accounts} monthLabel={periodInfo.label} />
        </>
      )}
      {activeTab === 'transactions' && (
        <TransactionsView
          transactions={paginatedTransactions}
          totalPages={totalPages}
          currentPage={currentPage}
          onPageChange={setCurrentPage}
          onView={setViewingTransaction}
          onEdit={(t: AccountingTransaction) => { setEditingTransaction(t); setShowModal(true); }}
          onDelete={handleDeleteTransaction}
        />
      )}
      {activeTab === 'journal' && <JournalView entries={journalEntries} dateFrom={dateFrom} dateTo={dateTo} />}
      {activeTab === 'ledger' && <LedgerView accounts={accounts} journalEntries={journalEntries} dateFrom={dateFrom} dateTo={dateTo} />}
      {activeTab === 'accounts' && <AccountsView accounts={accounts} />}
      
      {activeTab === 'withdraw' && (
        <div className="space-y-6">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
              <h2 className="text-xl font-bold text-slate-800">Withdraw Management</h2>
              <p className="text-sm text-slate-500">Process investor withdrawal requests</p>
            </div>
            <button
              onClick={() => setShowWithdrawModal(true)}
              className="inline-flex items-center gap-2 px-4 py-2.5 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors"
            >
              <Plus className="w-5 h-5" />
              <span>New Withdraw Request</span>
            </button>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
            <div className="bg-orange-50 rounded-xl p-4 border border-orange-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-orange-100 flex items-center justify-center">
                  <Clock className="w-5 h-5 text-orange-600" />
                </div>
                <div>
                  <p className="text-xl font-bold text-slate-800">{withdrawRequests.filter(w => w.status === 'pending').length}</p>
                  <p className="text-sm text-slate-500">Pending</p>
                </div>
              </div>
            </div>
            <div className="bg-blue-50 rounded-xl p-4 border border-blue-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                  <Check className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <p className="text-xl font-bold text-slate-800">{withdrawRequests.filter(w => w.status === 'approved').length}</p>
                  <p className="text-sm text-slate-500">Approved</p>
                </div>
              </div>
            </div>
            <div className="bg-green-50 rounded-xl p-4 border border-green-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-green-100 flex items-center justify-center">
                  <DollarSign className="w-5 h-5 text-green-600" />
                </div>
                <div>
                  <p className="text-xl font-bold text-slate-800">{withdrawRequests.filter(w => w.status === 'completed').length}</p>
                  <p className="text-sm text-slate-500">Completed</p>
                </div>
              </div>
            </div>
            <div className="bg-purple-50 rounded-xl p-4 border border-purple-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-purple-100 flex items-center justify-center">
                  <TrendingDown className="w-5 h-5 text-purple-600" />
                </div>
                <div>
                  <p className="text-xl font-bold text-slate-800">৳{withdrawRequests.reduce((sum, w) => sum + w.amount, 0).toLocaleString()}</p>
                  <p className="text-sm text-slate-500">Total Amount</p>
                </div>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-slate-50 border-b border-slate-100">
                  <tr>
                    <th className="px-4 py-3 text-left font-semibold text-slate-600">ID</th>
                    <th className="px-4 py-3 text-left font-semibold text-slate-600">Investor</th>
                    <th className="px-4 py-3 text-left font-semibold text-slate-600">Phone</th>
                    <th className="px-4 py-3 text-right font-semibold text-slate-600">Amount</th>
                    <th className="px-4 py-3 text-left font-semibold text-slate-600">Bank/Method</th>
                    <th className="px-4 py-3 text-left font-semibold text-slate-600">Request Date</th>
                    <th className="px-4 py-3 text-left font-semibold text-slate-600">Status</th>
                    <th className="px-4 py-3 text-center font-semibold text-slate-600">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {withdrawRequests.map((req) => (
                    <tr key={req.id} className="border-b border-slate-50 hover:bg-slate-50">
                      <td className="px-4 py-3 font-medium text-slate-800">{req.id}</td>
                      <td className="px-4 py-3">
                        <div>
                          <p className="font-medium text-slate-800">{req.investorName}</p>
                          <p className="text-xs text-slate-500">{req.investorId}</p>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-slate-600">{req.phone}</td>
                      <td className="px-4 py-3 text-right font-bold text-slate-800">৳{req.amount.toLocaleString()}</td>
                      <td className="px-4 py-3">
                        <p className="text-slate-600">{req.bankName}</p>
                        <p className="text-xs text-slate-400">{req.accountNo}</p>
                      </td>
                      <td className="px-4 py-3 text-slate-600">{req.requestDate}</td>
                      <td className="px-4 py-3">
                        <span className={`inline-flex items-center gap-1 text-xs font-medium px-2 py-1 rounded-full ${
                          req.status === 'pending' ? 'bg-orange-100 text-orange-700' :
                          req.status === 'approved' ? 'bg-blue-100 text-blue-700' :
                          req.status === 'completed' ? 'bg-green-100 text-green-700' :
                          'bg-red-100 text-red-700'
                        }`}>
                          {req.status === 'pending' && <Clock className="w-3 h-3" />}
                          {req.status === 'approved' && <Check className="w-3 h-3" />}
                          {req.status === 'completed' && <CheckCircle className="w-3 h-3" />}
                          {req.status}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex items-center justify-center gap-1">
                          {req.status === 'pending' && (
                            <>
                              <button
                                onClick={() => setWithdrawRequests(prev => prev.map(w => w.id === req.id ? { ...w, status: 'approved', processedDate: new Date().toISOString().split('T')[0] } : w))}
                                className="p-1.5 bg-blue-100 text-blue-600 rounded-lg hover:bg-blue-200"
                                title="Approve"
                              >
                                <Check className="w-4 h-4" />
                              </button>
                              <button
                                onClick={() => setWithdrawRequests(prev => prev.map(w => w.id === req.id ? { ...w, status: 'rejected' } : w))}
                                className="p-1.5 bg-red-100 text-red-600 rounded-lg hover:bg-red-200"
                                title="Reject"
                              >
                                <X className="w-4 h-4" />
                              </button>
                            </>
                          )}
                          {req.status === 'approved' && (
                            <button
                              onClick={() => { setPayNowModal(req); setPaymentForm({ method: 'bank', reference: `PAY-${req.id}`, notes: '', date: new Date().toISOString().split('T')[0] }); }}
                              className="px-3 py-1.5 bg-green-600 text-white text-xs rounded-lg hover:bg-green-700 flex items-center gap-1"
                            >
                              <DollarSign className="w-3 h-3" /> Pay Now
                            </button>
                          )}
                          {req.status === 'completed' && (
                            <div className="flex items-center gap-1">
                              <span className="text-xs text-green-600 font-medium">Paid</span>
                              <button onClick={() => window.print()} className="p-1 text-slate-400 hover:text-blue-600" title="Print Invoice">
                                <Printer className="w-4 h-4" />
                              </button>
                            </div>
                          )}
                          {req.status === 'rejected' && (
                            <span className="text-xs text-red-600 font-medium">Rejected</span>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {showWithdrawModal && (
            <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
              <div className="bg-white rounded-xl shadow-xl w-full max-w-lg">
                <div className="p-4 border-b border-slate-100 flex justify-between items-center">
                  <h3 className="font-semibold text-slate-800">New Withdraw Request</h3>
                  <button onClick={() => setShowWithdrawModal(false)} className="text-slate-400 hover:text-slate-600">
                    <X className="w-5 h-5" />
                  </button>
                </div>
                <div className="p-4 space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-600 mb-1 block">Investor ID</label>
                      <input type="text" placeholder="INV-XXX" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-600 mb-1 block">Phone</label>
                      <input type="tel" placeholder="01XXXXXXXXX" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-slate-600 mb-1 block">Investor Name</label>
                    <input type="text" placeholder="Enter name" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-600 mb-1 block">Amount (৳)</label>
                      <input type="number" placeholder="0" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-600 mb-1 block">Payment Method</label>
                      <select className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm">
                        <option value="bank">Bank Transfer</option>
                        <option value="mobile">Mobile Banking</option>
                        <option value="cash">Cash</option>
                      </select>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-slate-600 mb-1 block">Bank Name</label>
                      <input type="text" placeholder="Bank name" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                    </div>
                    <div>
                      <label className="text-sm font-medium text-slate-600 mb-1 block">Account Number</label>
                      <input type="text" placeholder="Account number" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                    </div>
                  </div>
                </div>
                <div className="p-4 border-t border-slate-100 flex justify-end gap-2">
                  <button onClick={() => setShowWithdrawModal(false)} className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50">Cancel</button>
                  <button onClick={() => setShowWithdrawModal(false)} className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700">Submit Request</button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {payNowModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div className="p-4 border-b border-slate-100 flex justify-between items-center">
              <h3 className="font-semibold text-slate-800">Process Payment</h3>
              <button onClick={() => setPayNowModal(null)} className="text-slate-400 hover:text-slate-600">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div className="bg-slate-50 p-3 rounded-lg">
                <p className="text-sm text-slate-500">Paying to</p>
                <p className="font-medium text-slate-800">{payNowModal.investorName}</p>
                <p className="text-sm text-slate-600">{payNowModal.bankName} - {payNowModal.accountNo}</p>
              </div>
              <div className="bg-blue-50 p-3 rounded-lg">
                <p className="text-sm text-slate-500">Amount</p>
                <p className="text-xl font-bold text-blue-600">৳{payNowModal.amount.toLocaleString()}</p>
              </div>
              <div>
                <label className="text-sm font-medium text-slate-600 mb-1 block">Payment Date</label>
                <input type="date" value={paymentForm.date} onChange={(e) => setPaymentForm(p => ({ ...p, date: e.target.value }))} className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
              </div>
              <div>
                <label className="text-sm font-medium text-slate-600 mb-1 block">Payment Method</label>
                <select value={paymentForm.method} onChange={(e) => setPaymentForm(p => ({ ...p, method: e.target.value }))} className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm">
                  <option value="bank">Bank Transfer</option>
                  <option value="mobile">Mobile Banking</option>
                  <option value="cash">Cash</option>
                </select>
              </div>
              <div>
                <label className="text-sm font-medium text-slate-600 mb-1 block">Reference No.</label>
                <input type="text" value={paymentForm.reference} onChange={(e) => setPaymentForm(p => ({ ...p, reference: e.target.value }))} placeholder="e.g. TRX-123456" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
              </div>
              <div>
                <label className="text-sm font-medium text-slate-600 mb-1 block">Notes (Optional)</label>
                <textarea value={paymentForm.notes} onChange={(e) => setPaymentForm(p => ({ ...p, notes: e.target.value }))} placeholder="Add any notes..." className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" rows={2} />
              </div>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2">
              <button onClick={() => setPayNowModal(null)} className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50">Cancel</button>
              <button onClick={() => {
                const newTransaction: AccountingTransaction = {
                  id: `TXN-${Date.now()}`,
                  date: paymentForm.date,
                  type: 'investor_withdraw',
                  amount: payNowModal.amount,
                  description: `Investor Withdrawal - ${payNowModal.investorName}`,
                  beneficiary: payNowModal.investorName,
                  beneficiaryPhone: payNowModal.phone,
                  paymentMethod: paymentForm.method as 'cash' | 'bank' | 'mobile',
                  reference: paymentForm.reference,
                  notes: paymentForm.notes,
                  createdAt: new Date().toISOString(),
                  createdBy: 'Admin'
                };
                setTransactions(prev => [newTransaction, ...prev]);
                setWithdrawRequests(prev => prev.map(w => w.id === payNowModal.id ? { ...w, status: 'completed' as const, processedDate: paymentForm.date, paymentMethod: paymentForm.method } : w));
                setPayNowModal(null);
              }} className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm hover:bg-green-700 flex items-center gap-2">
                <Banknote className="w-4 h-4" /> Complete Payment
              </button>
            </div>
          </div>
        </div>
      )}

      <TransactionModal
        isOpen={showModal}
        onClose={() => { setShowModal(false); setEditingTransaction(null); }}
        onSave={handleSaveTransaction}
        transaction={editingTransaction}
        accounts={accounts}
      />

      <ViewTransactionModal
        isOpen={!!viewingTransaction}
        onClose={() => setViewingTransaction(null)}
        transaction={viewingTransaction}
        accounts={accounts}
      />
    </div>
  );
}

function DashboardView({ stats, accounts, monthLabel = 'This Month' }: { stats: any; accounts: ChartOfAccount[]; monthLabel?: string }) {
  const currentMonth = new Date().toLocaleString('en-US', { month: 'long', year: 'numeric' });

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-5 gap-4">
        <StatCard label="Total Income" value={stats.income} icon={TrendingUp} color="green" />
        <StatCard label="Total Expenses" value={stats.expense} icon={TrendingDown} color="red" />
        <StatCard label="Net Profit" value={stats.netProfit} icon={Wallet} color="blue" />
        <StatCard label="Transactions" value={stats.transactionCount} icon={Receipt} color="slate" />
        <StatCard label="Total Assets" value={stats.assets} icon={Building} color="purple" />
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        <div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
          <div className="px-5 py-4 border-b border-slate-100 bg-gradient-to-r from-blue-50 to-blue-100/50">
            <div className="flex items-center gap-2">
              <div className="w-2 h-2 rounded-full bg-blue-500" />
              <h3 className="font-bold text-slate-800">Accounting Equation</h3>
            </div>
            <p className="text-xs text-slate-500 mt-1">A = L + E</p>
          </div>
          <div className="p-5 space-y-4">
            <div className="flex items-center justify-between p-4 bg-blue-50 rounded-xl border border-blue-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-blue-500 flex items-center justify-center">
                  <Building className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="text-sm font-medium text-blue-700">Assets</p>
                  <p className="text-xs text-blue-500">&lt;1000&gt; Code Series</p>
                </div>
              </div>
              <p className="text-xl font-bold text-blue-700">৳{stats.assets.toLocaleString()}</p>
            </div>

            <div className="flex items-center justify-center">
              <div className="w-8 h-8 rounded-full bg-slate-200 flex items-center justify-center">
                <span className="text-slate-500">=</span>
              </div>
            </div>

            <div className="flex items-center justify-between p-4 bg-red-50 rounded-xl border border-red-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-red-500 flex items-center justify-center">
                  <CreditCard className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="text-sm font-medium text-red-700">Liabilities</p>
                  <p className="text-xs text-red-500">&lt;2000&gt; Code Series</p>
                </div>
              </div>
              <p className="text-xl font-bold text-red-700">৳{stats.liabilities.toLocaleString()}</p>
            </div>

            <div className="flex items-center justify-center">
              <div className="w-8 h-8 rounded-full bg-slate-200 flex items-center justify-center">
                <span className="text-slate-500">+</span>
              </div>
            </div>

            <div className="flex items-center justify-between p-4 bg-purple-50 rounded-xl border border-purple-100">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-purple-500 flex items-center justify-center">
                  <Wallet className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="text-sm font-medium text-purple-700">Equity</p>
                  <p className="text-xs text-purple-500">&lt;3000&gt; Code Series</p>
                </div>
              </div>
              <p className="text-xl font-bold text-purple-700">৳{stats.equity.toLocaleString()}</p>
            </div>

            <div className="flex items-center justify-between pt-3 border-t border-slate-100">
              <p className="text-sm text-slate-500">Balance Check:</p>
              <span className={`text-sm font-medium ${stats.assets === stats.liabilities + stats.equity ? 'text-green-600' : 'text-amber-600'}`}>
                {stats.assets === stats.liabilities + stats.equity ? '✓ Balanced' : '⚠ Check Required'}
              </span>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
          <div className="px-5 py-4 border-b border-slate-100 bg-gradient-to-r from-green-50 to-green-100/50">
            <div className="flex items-center gap-2">
              <div className="w-2 h-2 rounded-full bg-green-500" />
              <h3 className="font-bold text-slate-800">Auto-Journal Sources</h3>
            </div>
            <p className="text-xs text-slate-500 mt-1">System-generated entries</p>
          </div>
          <div className="p-4 space-y-2  overflow-y-auto">
            {[
              { label: 'Rental Income', desc: 'When bike is rented via payment', auto: true },
              { label: 'Investor Funding', desc: 'When investor adds money', auto: true },
              { label: 'Investor Withdraw', desc: 'When investor withdraws profit', auto: true },
              { label: 'Bike Purchase', desc: 'When bikes are purchased', auto: true },
              { label: 'Bike Sales', desc: 'When bikes are sold', auto: true },
              { label: 'Maintenance Expense', desc: 'When damage/repair is paid', auto: true },
              { label: 'Manual Entry', desc: 'User creates manually', auto: false },
            ].map((item, i) => (
              <div key={i} className="flex items-center justify-between p-3 bg-slate-50 rounded-lg hover:bg-slate-100 transition-colors">
                <div className="flex items-center gap-2">
                  {item.auto ? <Tag className="w-4 h-4 text-green-500" /> : <Edit className="w-4 h-4 text-amber-500" />}
                  <div>
                    <p className="text-sm font-medium text-slate-700">{item.label}</p>
                    <p className="text-xs text-slate-500">{item.desc}</p>
                  </div>
                </div>
                <span className={`text-xs px-2 py-1 rounded-full font-medium ${item.auto ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700'}`}>
                  {item.auto ? 'Auto' : 'Manual'}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({ label, value, icon: Icon, color }: { label: string; value: number; icon: any; color: string }) {
  const colors: Record<string, string> = { green: 'bg-green-50 text-green-600', red: 'bg-red-50 text-red-600', blue: 'bg-blue-50 text-blue-600', purple: 'bg-purple-50 text-purple-600', slate: 'bg-slate-100 text-slate-600' };
  const showCurrency = label !== 'Transactions';
  return (
    <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
      <div className="flex items-start justify-between mb-3">
        <div className={`w-12 h-12 rounded-xl ${colors[color]} flex items-center justify-center`}>
          <Icon className="w-6 h-6" />
        </div>
      </div>
      <p className="text-2xl font-extrabold text-slate-800">{showCurrency ? `৳${value.toLocaleString()}` : value.toLocaleString()}</p>
      <p className="text-sm text-slate-500 mt-1">{label}</p>
    </div>
  );
}

function TransactionsView({ transactions, totalPages, currentPage, onPageChange, onView, onEdit, onDelete }: any) {
  return (
    <div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead className="bg-slate-50">
            <tr>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">ID</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Date</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Type</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Beneficiary</th>
              <th className="px-4 py-3 text-right text-xs font-semibold text-slate-500 uppercase">Amount</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50">
            {transactions.map((txn: AccountingTransaction) => (
              <tr key={txn.id} className="hover:bg-slate-50 transition-colors">
                <td className="px-4 py-3"><span className="text-sm font-medium text-slate-700">{txn.id}</span></td>
                <td className="px-4 py-3"><span className="text-sm text-slate-600">{txn.date}</span></td>
                <td className="px-4 py-3">
                  <span className="text-sm text-slate-600 capitalize">{txn.type.replace('_', ' ')}</span>
                </td>
                <td className="px-4 py-3"><span className="text-sm text-slate-600">{txn.beneficiary || '-'}</span></td>
                <td className="px-4 py-3 text-right">
                  <span className="text-sm font-semibold text-slate-700">৳{txn.amount.toLocaleString()}</span>
                </td>
                <td className="px-4 py-3">
                  <div className="flex items-center gap-1">
                    <button onClick={() => onView(txn)} className="p-1.5 hover:bg-slate-100 rounded-lg text-slate-500">
                      <Eye className="w-4 h-4" />
                    </button>
                    <button onClick={() => onEdit(txn)} className="p-1.5 hover:bg-slate-100 rounded-lg text-slate-500">
                      <Edit className="w-4 h-4" />
                    </button>
                    <button onClick={() => onDelete(txn.id)} className="p-1.5 hover:bg-red-50 rounded-lg text-red-400">
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div className="px-4 py-3 border-t border-slate-100 flex items-center justify-between">
          <p className="text-sm text-slate-500">Page {currentPage} of {totalPages}</p>
          <div className="flex items-center gap-2">
            <button onClick={() => onPageChange(Math.max(1, currentPage - 1))} disabled={currentPage === 1} className="p-2 hover:bg-slate-100 rounded-lg disabled:opacity-50">
              <ChevronLeft className="w-4 h-4" />
            </button>
            <button onClick={() => onPageChange(Math.min(totalPages, currentPage + 1))} disabled={currentPage === totalPages} className="p-2 hover:bg-slate-100 rounded-lg disabled:opacity-50">
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function JournalView({ entries, dateFrom, dateTo }: { entries: JournalEntry[]; dateFrom: string; dateTo: string }) {
  const filtered = entries.filter(e => (!dateFrom || e.date >= dateFrom) && (!dateTo || e.date <= dateTo));

  return (
    <div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
      <div className="px-5 py-4 border-b border-slate-100">
        <h2 className="font-bold text-slate-800">Journal Entries</h2>
        <p className="text-sm text-slate-500">{filtered.length} entries found</p>
      </div>
      <div className="overflow-x-auto max-h-[600px] overflow-y-auto">
        <table className="w-full">
          <thead className="bg-slate-50 sticky top-0">
            <tr>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Date</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Ref</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Account</th>
              <th className="px-4 py-3 text-right text-xs font-semibold text-slate-500 uppercase">Debit</th>
              <th className="px-4 py-3 text-right text-xs font-semibold text-slate-500 uppercase">Credit</th>
              <th className="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase">Type</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50">
            {filtered.map((entry) => (
              <>
                {entry.entries.map((line, idx) => (
                  <tr key={`${entry.id}-${idx}`} className="hover:bg-slate-50">
                    {idx === 0 && (
                      <>
                        <td className="px-4 py-3" rowSpan={entry.entries.length}>
                          <span className="text-sm text-slate-600">{entry.date}</span>
                        </td>
                        <td className="px-4 py-3" rowSpan={entry.entries.length}>
                          <span className="text-sm font-medium text-slate-700">{entry.reference}</span>
                        </td>
                      </>
                    )}
                    <td className="px-4 py-3">
                      <span className="text-sm text-slate-600">{line.accountName}</span>
                      <span className="text-xs text-slate-400 ml-2">({line.accountCode})</span>
                    </td>
                    <td className="px-4 py-3 text-right">
                      {line.debit > 0 && <span className="text-sm text-slate-700">৳{line.debit.toLocaleString()}</span>}
                    </td>
                    <td className="px-4 py-3 text-right">
                      {line.credit > 0 && <span className="text-sm text-slate-700">৳{line.credit.toLocaleString()}</span>}
                    </td>
                    {idx === 0 && (
                      <td className="px-4 py-3 text-center" rowSpan={entry.entries.length}>
                        <span className={`text-xs px-2 py-1 rounded-full ${entry.isAuto ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700'}`}>
                          {entry.isAuto ? 'Auto' : 'Manual'}
                        </span>
                      </td>
                    )}
                  </tr>
                ))}
              </>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function LedgerView({ accounts, journalEntries, dateFrom, dateTo }: { accounts: ChartOfAccount[]; journalEntries: JournalEntry[]; dateFrom: string; dateTo: string }) {
  const filteredEntries = journalEntries.filter(e => (!dateFrom || e.date >= dateFrom) && (!dateTo || e.date <= dateTo));
  const ledgerAccounts = accounts.filter(a => a.isActive && a.parentId);

  return (
    <div className="space-y-4">
      {ledgerAccounts.map(account => {
        const entries = filteredEntries.flatMap(je =>
          je.entries.filter(e => e.accountId === account.id).map(e => ({
            date: je.date,
            reference: je.reference,
            debit: e.debit,
            credit: e.credit,
            isAuto: je.isAuto
          }))
        );

        let balance = 0;
        if (account.type === 'asset' || account.type === 'expense') {
          balance = entries.reduce((sum, e) => sum + e.debit - e.credit, 0);
        } else {
          balance = entries.reduce((sum, e) => sum + e.credit - e.debit, 0);
        }

        return (
          <div key={account.id} className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
            <div className="px-5 py-3 border-b border-slate-100 flex items-center justify-between bg-slate-50">
              <div className="flex items-center gap-3">
                <span className="text-sm font-mono text-slate-500">{account.code}</span>
                <span className="font-medium text-slate-800">{account.name}</span>
                <span className={`text-xs px-2 py-0.5 rounded-full ${accountTypeConfig[account.type].bg} ${accountTypeConfig[account.type].color}`}>
                  {accountTypeConfig[account.type].label}
                </span>
              </div>
              <span className="font-bold text-slate-700">৳{balance.toLocaleString()}</span>
            </div>
            {entries.length > 0 && (
              <table className="w-full">
                <thead className="bg-slate-25">
                  <tr>
                    <th className="px-4 py-2 text-left text-xs font-semibold text-slate-500">Date</th>
                    <th className="px-4 py-2 text-left text-xs font-semibold text-slate-500">Ref</th>
                    <th className="px-4 py-2 text-right text-xs font-semibold text-slate-500">Debit</th>
                    <th className="px-4 py-2 text-right text-xs font-semibold text-slate-500">Credit</th>
                    <th className="px-4 py-2 text-right text-xs font-semibold text-slate-500">Balance</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50">
                  {entries.slice(0, 10).map((entry, idx) => {
                    let runningBalance = 0;
                    if (account.type === 'asset' || account.type === 'expense') {
                      runningBalance = entries.slice(0, idx + 1).reduce((sum, e) => sum + e.debit - e.credit, 0);
                    } else {
                      runningBalance = entries.slice(0, idx + 1).reduce((sum, e) => sum + e.credit - e.debit, 0);
                    }
                    return (
                      <tr key={idx}>
                        <td className="px-4 py-2 text-sm text-slate-600">{entry.date}</td>
                        <td className="px-4 py-2 text-sm text-slate-600">{entry.reference}</td>
                        <td className="px-4 py-2 text-sm text-slate-600 text-right">{entry.debit > 0 ? `৳${entry.debit}` : '-'}</td>
                        <td className="px-4 py-2 text-sm text-slate-600 text-right">{entry.credit > 0 ? `৳${entry.credit}` : '-'}</td>
                        <td className="px-4 py-2 text-sm font-medium text-slate-700 text-right">৳{runningBalance}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        );
      })}
    </div>
  );
}

function AccountsView({ accounts }: { accounts: ChartOfAccount[] }) {
  const accountTypes: AccountType[] = ['asset', 'liability', 'equity', 'income', 'expense'];

  return (
    <div className="space-y-4">
      {accountTypes.map(type => {
        const typeAccounts = accounts.filter(a => a.type === type && a.isActive);
        const parentAccounts = typeAccounts.filter(a => !a.parentId);

        return (
          <div key={type} className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
            <div className="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
              <div className="flex items-center gap-3">
                <span className={`px-2 py-1 rounded-lg text-xs font-semibold ${accountTypeConfig[type].bg} ${accountTypeConfig[type].color}`}>
                  {accountTypeConfig[type].label}
                </span>
                <span className="font-bold text-slate-800">{typeAccounts.length} Accounts</span>
              </div>
              <span className="font-bold text-slate-700">৳{typeAccounts.reduce((sum, a) => sum + a.balance, 0).toLocaleString()}</span>
            </div>
            <div className="divide-y divide-slate-50">
              {parentAccounts.map(account => {
                const children = typeAccounts.filter(a => a.parentId === account.id);
                return (
                  <div key={account.id}>
                    <div className="px-5 py-3 flex items-center justify-between hover:bg-slate-50">
                      <div className="flex items-center gap-3">
                        <span className="text-sm font-mono text-slate-500 w-16">{account.code}</span>
                        <span className="font-medium text-slate-700">{account.name}</span>
                      </div>
                      <span className="font-semibold text-slate-600">৳{account.balance.toLocaleString()}</span>
                    </div>
                    {children.map(child => (
                      <div key={child.id} className="px-5 py-2 pl-12 flex items-center justify-between bg-slate-25">
                        <div className="flex items-center gap-3">
                          <span className="text-sm font-mono text-slate-400 w-16">{child.code}</span>
                          <span className="text-sm text-slate-600">{child.name}</span>
                        </div>
                        <span className="text-sm font-semibold text-slate-600">৳{child.balance.toLocaleString()}</span>
                      </div>
                    ))}
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function TransactionModal({ isOpen, onClose, onSave, transaction, accounts }: { isOpen: boolean; onClose: () => void; onSave: (data: Partial<AccountingTransaction>, isManual?: boolean) => void; transaction: AccountingTransaction | null; accounts: ChartOfAccount[] }) {
  const [formData, setFormData] = useState<Partial<AccountingTransaction>>({
    date: new Date().toISOString().split('T')[0],
    type: 'rent_income',
    amount: 0,
    description: '',
    beneficiary: '',
    beneficiaryPhone: '',
    paymentMethod: 'cash',
    reference: '',
    notes: '',
    bikeDetails: '',
  });

  useEffect(() => {
    if (transaction) {
      setFormData(transaction);
    } else {
      setFormData({
        date: new Date().toISOString().split('T')[0],
        type: 'rent_income',
        amount: 0,
        description: '',
        beneficiary: '',
        beneficiaryPhone: '',
        paymentMethod: 'cash',
        reference: '',
        notes: '',
        bikeDetails: '',
      });
    }
  }, [transaction, isOpen]);

  const getPaymentAccount = (method: string) => {
    switch (method) {
      case 'bank': return { code: '1200', name: 'Bank - City Bank' };
      case 'cash': return { code: '1100', name: 'Cash in Hand' };
      case 'mobile': return { code: '1300', name: 'bKash Business' };
      case 'cheque': return { code: '1410', name: 'Cheque Receivable' };
      default: return { code: '1100', name: 'Cash in Hand' };
    }
  };

  const getTransactionAccounts = (type: TransactionType, amount: number, method: string) => {
    const payment = getPaymentAccount(method);
    
    const journalMap: Record<string, { debit: { code: string; name: string }; credit: { code: string; name: string } }> = {
      deposit: { debit: payment, credit: { code: '4100', name: 'Bike Deposit Income' } },
      rent_income: { debit: payment, credit: { code: '4200', name: 'Rental Income' } },
      investor_funding: { debit: payment, credit: { code: '2200', name: 'Investor Liabilities' } },
      investor_withdraw: { debit: { code: '2200', name: 'Investor Liabilities' }, credit: payment },
      salary: { debit: { code: '5100', name: 'Salary Expense' }, credit: payment },
      rent_expense: { debit: { code: '5200', name: 'Rent Expense' }, credit: payment },
      utility: { debit: { code: '5300', name: 'Utility Expense' }, credit: payment },
      maintenance: { debit: { code: '5400', name: 'Maintenance Expense' }, credit: payment },
      bike_purchase: { debit: { code: '1500', name: 'Bikes & Equipment' }, credit: payment },
      bike_sale: { debit: payment, credit: { code: '4400', name: 'Bike Sales Income' } },
      other_income: { debit: payment, credit: { code: '4500', name: 'Other Income' } },
      other_expense: { debit: { code: '5700', name: 'Other Expense' }, credit: payment },
    };
    
    const entry = journalMap[type] || { debit: payment, credit: { code: '5700', name: 'Other Expense' } };
    return entry;
  };

  const typeConfig = transactionTypeConfig[formData.type || 'rent_income'];
  const journalEntry = getTransactionAccounts(formData.type || 'rent_income', formData.amount || 0, formData.paymentMethod || 'cash');

  return (
    <div className={`fixed inset-0 z-50 flex items-center justify-center ${isOpen ? '' : 'hidden'}`}>
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="absolute inset-4 lg:inset-auto lg:w-full lg:max-w-3xl bg-white rounded-xl shadow-xl overflow-hidden flex flex-col max-h-[90vh]">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-gradient-to-r from-accent-light to-white">
          <div>
            <h2 className="text-lg font-bold text-slate-800">
              {transaction ? 'Edit Transaction' : 'New Transaction'}
            </h2>
            <p className="text-xs text-slate-500">Create manual journal entry</p>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-slate-100 rounded-lg">
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={(e) => { e.preventDefault(); onSave(formData, true); }} className="flex-1 overflow-y-auto p-6 space-y-5">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-slate-50 p-4 rounded-xl border border-slate-200">
              <label className="block text-xs font-semibold text-slate-500 uppercase mb-2">Transaction Date</label>
              <input 
                type="date" 
                value={formData.date} 
                onChange={(e) => setFormData({ ...formData, date: e.target.value })} 
                className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm bg-white" 
                required 
              />
            </div>
            <div className="bg-slate-50 p-4 rounded-xl border border-slate-200">
              <label className="block text-xs font-semibold text-slate-500 uppercase mb-2">Transaction Type *</label>
              <select 
                value={formData.type} 
                onChange={(e) => setFormData({ ...formData, type: e.target.value as TransactionType })} 
                className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm bg-white"
              >
                <optgroup label="Income">
                  <option value="deposit">Bike Deposit</option>
                  <option value="rent_income">Rental Income</option>
                  <option value="investor_funding">Investor Funding</option>
                  <option value="bike_sale">Sell Bike</option>
                  <option value="other_income">Other Income</option>
                </optgroup>
                <optgroup label="Expense">
                  <option value="investor_withdraw">Investor Withdraw</option>
                  <option value="salary">Salary Payment</option>
                  <option value="rent_expense">Office/Shop Rent</option>
                  <option value="utility">Utility Bills</option>
                  <option value="maintenance">Maintenance</option>
                  <option value="bike_purchase">Buy Bike</option>
                  <option value="other_expense">Other Expense</option>
                </optgroup>
              </select>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-green-50 p-4 rounded-xl border border-green-200">
              <label className="block text-xs font-semibold text-green-700 uppercase mb-2">Amount (৳) *</label>
              <input 
                type="number" 
                value={formData.amount} 
                onChange={(e) => setFormData({ ...formData, amount: Number(e.target.value) })} 
                className="w-full px-3 py-2.5 border border-green-200 rounded-lg text-sm bg-white font-bold text-green-700" 
                required 
                min="0" 
                placeholder="0"
              />
            </div>
            <div className="bg-blue-50 p-4 rounded-xl border border-blue-200">
              <label className="block text-xs font-semibold text-blue-700 uppercase mb-2">Payment Method</label>
              <select 
                value={formData.paymentMethod} 
                onChange={(e) => setFormData({ ...formData, paymentMethod: e.target.value as 'cash' | 'bank' | 'mobile' })} 
                className="w-full px-3 py-2.5 border border-blue-200 rounded-lg text-sm bg-white"
              >
                <option value="cash">Cash</option>
                <option value="bank">Bank Transfer</option>
                <option value="mobile">Mobile Banking</option>
                <option value="cheque">Cheque</option>
              </select>
            </div>
          </div>

          <div className="bg-white p-4 rounded-xl border border-slate-200">
            <label className="block text-xs font-semibold text-slate-500 uppercase mb-2">Description *</label>
            <input 
              type="text" 
              value={formData.description} 
              onChange={(e) => setFormData({ ...formData, description: e.target.value })} 
              className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm" 
              required 
              placeholder="Enter transaction description"
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-white p-4 rounded-xl border border-slate-200">
              <label className="block text-xs font-semibold text-slate-500 uppercase mb-2">Beneficiary/Recipient</label>
              <input 
                type="text" 
                value={formData.beneficiary} 
                onChange={(e) => setFormData({ ...formData, beneficiary: e.target.value })} 
                className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm" 
                placeholder="Name of person or organization"
              />
            </div>
            <div className="bg-white p-4 rounded-xl border border-slate-200">
              <label className="block text-xs font-semibold text-slate-500 uppercase mb-2">Phone Number</label>
              <input 
                type="text" 
                value={formData.beneficiaryPhone} 
                onChange={(e) => setFormData({ ...formData, beneficiaryPhone: e.target.value })} 
                className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm" 
                placeholder="Contact number"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-white p-4 rounded-xl border border-slate-200">
              <label className="block text-xs font-semibold text-slate-500 uppercase mb-2">Reference No.</label>
              <input 
                type="text" 
                value={formData.reference} 
                onChange={(e) => setFormData({ ...formData, reference: e.target.value })} 
                className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm" 
                placeholder="Auto-generated if empty"
              />
            </div>
            <div className="bg-white p-4 rounded-xl border border-slate-200 md:col-span-2">
              <label className="block text-xs font-semibold text-slate-500 uppercase mb-2">Bike Details</label>
              <input 
                type="text" 
                value={formData.bikeDetails} 
                onChange={(e) => setFormData({ ...formData, bikeDetails: e.target.value })} 
                className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm" 
                placeholder="Bike model, plate number, etc."
              />
            </div>
          </div>

          <div className="bg-white p-4 rounded-xl border border-slate-200">
            <label className="block text-xs font-semibold text-slate-500 uppercase mb-2">Notes</label>
            <textarea 
              value={formData.notes} 
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })} 
              className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm" 
              rows={2}
              placeholder="Additional notes..."
            />
          </div>

          <div className="bg-gradient-to-r from-amber-50 to-yellow-50 p-5 rounded-xl border border-amber-200">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <BookOpen className="w-5 h-5 text-amber-600" />
                <h4 className="font-semibold text-amber-800">Journal Entry Preview</h4>
              </div>
              <span className="text-xs px-3 py-1 rounded-full bg-amber-200 text-amber-800 font-medium">
                Manual Entry
              </span>
            </div>
            
            <div className="space-y-3">
              <div className="flex items-center justify-between bg-white p-3 rounded-lg border border-amber-100">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-8 rounded-lg bg-green-100 flex items-center justify-center">
                    <ArrowDownLeft className="w-4 h-4 text-green-600" />
                  </div>
                  <div>
                    <p className="text-xs text-slate-500">Debit (Dr)</p>
                    <p className="text-sm font-medium text-slate-700">{journalEntry.debit.name}</p>
                    <p className="text-xs text-slate-400">({journalEntry.debit.code})</p>
                  </div>
                </div>
                <p className="text-lg font-bold text-green-600">৳{(formData.amount || 0).toLocaleString()}</p>
              </div>

              <div className="flex justify-center">
                <div className="w-8 h-8 rounded-full bg-amber-200 flex items-center justify-center">
                  <ArrowDownLeft className="w-4 h-4 text-amber-600 rotate-180" />
                </div>
              </div>

              <div className="flex items-center justify-between bg-white p-3 rounded-lg border border-amber-100">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-8 rounded-lg bg-red-100 flex items-center justify-center">
                    <ArrowUpRight className="w-4 h-4 text-red-600" />
                  </div>
                  <div>
                    <p className="text-xs text-slate-500">Credit (Cr)</p>
                    <p className="text-sm font-medium text-slate-700">{journalEntry.credit.name}</p>
                    <p className="text-xs text-slate-400">({journalEntry.credit.code})</p>
                  </div>
                </div>
                <p className="text-lg font-bold text-red-600">৳{(formData.amount || 0).toLocaleString()}</p>
              </div>
            </div>

            <div className="mt-3 pt-3 border-t border-amber-200 flex items-center justify-between">
              <p className="text-xs text-amber-600">Total Debit = Total Credit</p>
              <p className="text-sm font-bold text-amber-800">৳{(formData.amount || 0).toLocaleString()}</p>
            </div>
          </div>
        </form>

        <div className="px-6 py-4 border-t border-slate-100 flex items-center justify-between bg-slate-50">
          <button type="button" onClick={onClose} className="px-4 py-2.5 border border-slate-200 text-slate-600 rounded-lg text-sm font-medium hover:bg-slate-100">
            Cancel
          </button>
          <button onClick={() => onSave(formData, true)} className="px-6 py-2.5 bg-accent text-white rounded-lg text-sm font-medium hover:bg-accent-dark flex items-center gap-2">
            <Save className="w-4 h-4" />
            {transaction ? 'Update Transaction' : 'Create Transaction'}
          </button>
        </div>
      </div>
    </div>
  );
}

function ViewTransactionModal({ isOpen, onClose, transaction, accounts }: { isOpen: boolean; onClose: () => void; transaction: AccountingTransaction | null; accounts: ChartOfAccount[] }) {
  if (!transaction) return null;
  const typeConfig = transactionTypeConfig[transaction.type as TransactionType];

  const generatePDF = () => {
    import('jspdf').then(jsPDF => {
      const doc = new jsPDF.default();

      doc.setFontSize(20);
      doc.setTextColor(6, 95, 70);
      doc.text('JAIBEN Mobility Ltd', 20, 25);

      doc.setFontSize(14);
      doc.setTextColor(0);
      doc.text('Transaction Invoice / Voucher', 20, 35);

      doc.setFontSize(10);
      doc.setTextColor(100);
      doc.text(`Date: ${transaction.date}`, 20, 45);
      doc.text(`Invoice No: ${transaction.id}`, 20, 52);
      doc.text(`Type: ${typeConfig.label}`, 20, 59);
      doc.text(`Amount: ৳${transaction.amount.toLocaleString()}`, 20, 66);

      if (transaction.beneficiary) doc.text(`Beneficiary: ${transaction.beneficiary}`, 20, 76);
      if (transaction.bikeDetails) doc.text(`Bike: ${transaction.bikeDetails}`, 20, 83);
      doc.text(`Payment: ${transaction.paymentMethod}`, 20, 90);
      doc.text(`Description: ${transaction.description}`, 20, 100);

      doc.save(`invoice-${transaction.id}.pdf`);
    });
  };

  return (
    <div className={`fixed inset-0 z-50 flex items-center justify-center ${isOpen ? '' : 'hidden'}`}>
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="absolute inset-4 lg:inset-auto lg:w-full lg:max-w-lg bg-white rounded-xl shadow-xl overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
          <div>
            <h2 className="text-lg font-bold text-slate-800">Transaction Details</h2>
            <p className="text-sm text-slate-500">{transaction.id}</p>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-slate-100 rounded-lg">
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="p-6 space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div><p className="text-sm text-slate-500">Date</p><p className="font-medium text-slate-800">{transaction.date}</p></div>
            <div><p className="text-sm text-slate-500">Amount</p><p className="font-semibold text-slate-800">৳{transaction.amount.toLocaleString()}</p></div>
          </div>
          <div><p className="text-sm text-slate-500">Type</p><p className="font-medium text-slate-800">{typeConfig.label}</p></div>
          <div><p className="text-sm text-slate-500">Description</p><p className="font-medium text-slate-800">{transaction.description}</p></div>
          {transaction.beneficiary && <div><p className="text-sm text-slate-500">Beneficiary</p><p className="font-medium text-slate-800">{transaction.beneficiary}</p></div>}
          {transaction.bikeDetails && <div><p className="text-sm text-slate-500">Bike</p><p className="font-medium text-slate-800">{transaction.bikeDetails}</p></div>}
          <div className="grid grid-cols-2 gap-4">
            <div><p className="text-sm text-slate-500">Payment Method</p><p className="font-medium text-slate-800 capitalize">{transaction.paymentMethod}</p></div>
            <div><p className="text-sm text-slate-500">Reference</p><p className="font-medium text-slate-800">{transaction.reference || '-'}</p></div>
          </div>
        </div>

        <div className="px-6 py-4 border-t border-slate-100 flex items-center justify-between">
          <button onClick={generatePDF} className="inline-flex items-center gap-2 px-4 py-2.5 bg-accent text-white rounded-lg text-sm font-medium hover:bg-accent-dark">
            <Download className="w-4 h-4" /> Download PDF
          </button>
          <button onClick={onClose} className="px-4 py-2.5 border border-slate-200 text-slate-600 rounded-lg text-sm font-medium hover:bg-slate-50">
            Close
          </button>
        </div>
      </div>
    </div>
  );
}