'use client';

import { useState, use, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  ArrowLeft, TrendingUp, Plus, X, Edit, Trash2, Bike, DollarSign, Calendar,
  CreditCard, FileText, Users, TrendingDown, ArrowRight, Download, Check,
  Printer, BarChart3, Wallet, Clock, Shield, Percent, Activity, AlertTriangle,
  Receipt, CreditCardIcon, Battery, Zap
} from 'lucide-react';
import toast from 'react-hot-toast';
import { investors as initialInvestors, bikes as initialBikes, transactions as initialTransactions } from '@/data/mockData';

import AssignBikeModal from '../../../components/AssignBikeModal';
import AssignBatteryModal from '../../../components/AssignBatteryModal';
import UnassignConfirmModal from '../../../components/UnassignConfirmModal';

export default function InvestmentDetailPage({ params }: { params: Promise<{ id: string; investmentId: string }> }) {
  const resolvedParams = use(params);
  const { id: investorId, investmentId } = resolvedParams;
  const router = useRouter();

  const [investors, setInvestors] = useState<any[]>(() => {
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem('jaiben_investors');
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch (e) {
          console.error(e);
        }
      }
    }
    return initialInvestors;
  });

  const [batteries, setBatteries] = useState<any[]>(() => {
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem('jaiben_batteries');
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch (e) {
          console.error(e);
        }
      }
    }
    return [
      {
        id: 'BAT-001',
        serialNumber: 'SN-2024-00001',
        brand: 'EVE Energy',
        model: 'Li-Ion 60V50Ah',
        type: 'lithium-ion',
        capacity: 50,
        voltage: 60,
        purchaseDate: '2024-01-15',
        purchasePrice: 45000,
        deposit: 5000,
        rentPrice: 150,
        investorId: investorId,
        investorName: 'Md. Hasan Mahmud',
        investorSharePercentage: 100,
        investedAmount: 45000,
        investmentId: 'ip3',
        status: 'in-use',
        currentSoc: 78,
        health: 95,
        cycleCount: 156
      },
      {
        id: 'BAT-002',
        serialNumber: 'SN-2024-00002',
        brand: 'CATL',
        model: 'LiFePO4 48V40Ah',
        type: 'lifepo4',
        capacity: 40,
        voltage: 48,
        purchaseDate: '2024-02-10',
        purchasePrice: 38000,
        deposit: 4000,
        rentPrice: 120,
        investorId: investorId,
        investorName: 'Md. Hasan Mahmud',
        investorSharePercentage: 100,
        investedAmount: 38000,
        investmentId: 'ip3',
        status: 'available',
        currentSoc: 92,
        health: 98,
        cycleCount: 45
      },
      {
        id: 'BAT-005',
        serialNumber: 'SN-2024-00005',
        brand: 'BYD',
        model: 'Li-Ion 60V50Ah',
        type: 'lithium-ion',
        capacity: 50,
        voltage: 60,
        purchaseDate: '2024-02-15',
        purchasePrice: 45000,
        deposit: 5000,
        rentPrice: 150,
        investorId: investorId,
        investorName: 'Md. Hasan Mahmud',
        investorSharePercentage: 100,
        investedAmount: 45000,
        investmentId: 'ip3',
        status: 'in-use',
        currentSoc: 82,
        health: 97,
        cycleCount: 18
      }
    ];
  });

  const investor = investors.find(i => i.id === investorId);
  const investment = investor?.investments?.find((inv: any) => inv.id === investmentId);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('jaiben_investors', JSON.stringify(investors));
    }
  }, [investors]);

  // Patch local storage state to make sure inv1 has the Standard Battery Plan (ip3) and correct assigned batteries
  useEffect(() => {
    if (!investor) return;
    const hasIp3 = investor.investments?.some((inv: any) => inv.id === 'ip3');
    if (!hasIp3) {
      const updated = investors.map(i => {
        if (i.id === investorId) {
          const investments = i.investments || [];
          return {
            ...i,
            totalInvested: 300000,
            investments: [
              ...investments.filter((inv: any) => inv.id !== 'ip3'),
              {
                id: 'ip3',
                investorId: investorId,
                planName: 'Standard Battery Plan',
                planType: 'silver' as const,
                assetType: 'battery' as const,
                batteryIds: ['BAT-001', 'BAT-002', 'BAT-005'],
                totalInvestment: 150000,
                monthlyReturn: 4500,
                expectedRoi: 16,
                actualEarnings: 9000,
                startDate: '2024-02-01',
                endDate: '2025-02-01',
                status: 'active' as const,
                paymentMethod: 'bank' as const,
                transactionId: 'invt3',
                createdAt: '2024-02-01'
              }
            ]
          };
        }
        return i;
      });
      setInvestors(updated);
    }
  }, [investors, investorId, investor]);

  useEffect(() => {
    const hasBat5 = batteries.some(b => b.id === 'BAT-005');
    const hasIp3Assignment = batteries.some(b => b.id === 'BAT-001' && b.investmentId === 'ip3');
    if (!hasBat5 || !hasIp3Assignment) {
      const updated = [
        {
          id: 'BAT-001',
          serialNumber: 'SN-2024-00001',
          brand: 'EVE Energy',
          model: 'Li-Ion 60V50Ah',
          type: 'lithium-ion',
          capacity: 50,
          voltage: 60,
          purchaseDate: '2024-01-15',
          purchasePrice: 45000,
          deposit: 5000,
          rentPrice: 150,
          investorId: investorId,
          investorName: 'Md. Hasan Mahmud',
          investorSharePercentage: 100,
          investedAmount: 45000,
          investmentId: 'ip3',
          status: 'in-use',
          currentSoc: 78,
          health: 95,
          cycleCount: 156
        },
        {
          id: 'BAT-002',
          serialNumber: 'SN-2024-00002',
          brand: 'CATL',
          model: 'LiFePO4 48V40Ah',
          type: 'lifepo4',
          capacity: 40,
          voltage: 48,
          purchaseDate: '2024-02-10',
          purchasePrice: 38000,
          deposit: 4000,
          rentPrice: 120,
          investorId: investorId,
          investorName: 'Md. Hasan Mahmud',
          investorSharePercentage: 100,
          investedAmount: 38000,
          investmentId: 'ip3',
          status: 'available',
          currentSoc: 92,
          health: 98,
          cycleCount: 45
        },
        {
          id: 'BAT-005',
          serialNumber: 'SN-2024-00005',
          brand: 'BYD',
          model: 'Li-Ion 60V50Ah',
          type: 'lithium-ion',
          capacity: 50,
          voltage: 60,
          purchaseDate: '2024-02-15',
          purchasePrice: 45000,
          deposit: 5000,
          rentPrice: 150,
          investorId: investorId,
          investorName: 'Md. Hasan Mahmud',
          investorSharePercentage: 100,
          investedAmount: 45000,
          investmentId: 'ip3',
          status: 'in-use',
          currentSoc: 82,
          health: 97,
          cycleCount: 18
        },
        ...batteries.filter(b => b.id !== 'BAT-001' && b.id !== 'BAT-002' && b.id !== 'BAT-005')
      ];
      setBatteries(updated);
    }
  }, [batteries, investorId]);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('jaiben_batteries', JSON.stringify(batteries));
    }
  }, [batteries]);

  const [bikes, setBikes] = useState<any[]>(() => {
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem('jaiben_bikes');
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch (e) {
          console.error(e);
        }
      }
    }
    return initialBikes;
  });

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('jaiben_bikes', JSON.stringify(bikes));
    }
  }, [bikes]);

  const [unassignedBatteries, setUnassignedBatteries] = useState<any[]>(() => {
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem('jaiben_unassigned_batteries');
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch (e) {
          console.error(e);
        }
      }
    }
    return [
      { id: 'BAT-003', serialNumber: 'SN-2024-00003', brand: 'BYD', model: 'Li-Ion 72V60Ah', type: 'lithium-ion', capacity: 60, voltage: 72, purchasePrice: 52000, deposit: 6000, rentPrice: 180, status: 'available', currentSoc: 85, health: 97, cycleCount: 12 },
      { id: 'BAT-004', serialNumber: 'SN-2024-00004', brand: 'Panasonic', model: 'Li-Ion 60V40Ah', type: 'lithium-ion', capacity: 40, voltage: 60, purchasePrice: 41000, deposit: 4500, rentPrice: 130, status: 'available', currentSoc: 90, health: 99, cycleCount: 8 }
    ];
  });

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('jaiben_unassigned_batteries', JSON.stringify(unassignedBatteries));
    }
  }, [unassignedBatteries]);

  const [activeTab, setActiveTab] = useState('overview');
  const [showAddBikeModal, setShowAddBikeModal] = useState(false);
  const [showRegisterBikeModal, setShowRegisterBikeModal] = useState(false);
  const [showAssignBatteryModal, setShowAssignBatteryModal] = useState(false);
  const [unassignConfirmModal, setUnassignConfirmModal] = useState<{
    show: boolean;
    type: 'bike' | 'battery';
    id: string;
    name: string;
    details: string;
  }>({
    show: false,
    type: 'bike',
    id: '',
    name: '',
    details: ''
  });
  const [showRegisterBatteryModal, setShowRegisterBatteryModal] = useState(false);

  const [selectedBikeId, setSelectedBikeId] = useState('');
  const [registerBikeForm, setRegisterBikeForm] = useState({
    plateNumber: '',
    brand: 'Etron',
    model: 'ET50',
    currentRent: 150,
    location: 'Banani',
    purchasePrice: 200000,
    rentalType: 'single_rent'
  });

  const [selectedBatteryId, setSelectedBatteryId] = useState('');
  const [assignBatteryForm, setAssignBatteryForm] = useState({
    investorShare: 100,
    investedAmount: 45000,
    deposit: 5000,
    rentPrice: 150
  });

  const [registerBatteryForm, setRegisterBatteryForm] = useState({
    serialNumber: '',
    brand: 'BYD',
    model: 'Li-Ion 60V50Ah',
    type: 'lithium-ion',
    capacity: 50,
    voltage: 60,
    purchasePrice: 45000,
    deposit: 5000,
    rentPrice: 150,
    investorShare: 100,
    investedAmount: 45000
  });

  const [showDeleteBikeModal, setShowDeleteBikeModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showStatementHistory, setShowStatementHistory] = useState(false);
  const [showPartialPaymentModal, setShowPartialPaymentModal] = useState(false);
  const [bikeToDelete, setBikeToDelete] = useState<any>(null);
  const [editForm, setEditForm] = useState<any>({});
  const [statementHistory, setStatementHistory] = useState<any[]>([
    { id: 'stmt1', date: '2024-03-25', type: 'Monthly Statement', period: 'March 2024', downloadedBy: 'Admin', downloadedAt: '2024-03-25 10:30' },
    { id: 'stmt2', date: '2024-02-28', type: 'Monthly Statement', period: 'February 2024', downloadedBy: 'Admin', downloadedAt: '2024-02-28 14:15' },
    { id: 'stmt3', date: '2024-01-31', type: 'Monthly Statement', period: 'January 2024', downloadedBy: 'Admin', downloadedAt: '2024-01-31 09:00' },
  ]);
  const [partialPayment, setPartialPayment] = useState({
    amount: 0,
    paymentMethod: 'bank',
    transactionRef: '',
    date: new Date().toISOString().split('T')[0],
    notes: ''
  });
  const [investmentPayments, setInvestmentPayments] = useState<any[]>(() => {
    if (!investment) return [];
    const isBatteryPlan = investment.assetType === 'battery' || investment.planName?.toLowerCase().includes('battery');

    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem(`jaiben_payments_${investmentId}`);
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch (e) {
          console.error(e);
        }
      }
    }

    if (isBatteryPlan) {
      return [
        {
          id: `pay_${investmentId}`,
          date: investment.startDate || '2024-02-01',
          amount: investment.totalInvestment,
          paymentMethod: investment.paymentMethod || 'bank',
          transactionRef: investment.transactionId || 'TXN-BAT-001',
          status: 'completed',
          notes: 'Full Payment'
        }
      ];
    }

    if (investmentId === 'ip2') {
      return [
        {
          id: 'pay1_ip2',
          date: '2024-01-20',
          amount: investment.totalInvestment,
          paymentMethod: 'mobile',
          transactionRef: 'TXN-002',
          status: 'completed',
          notes: 'Full Payment'
        }
      ];
    }

    // Default for ip1 or others
    return [
      { id: 'pay1', date: '2024-01-15', amount: 50000, paymentMethod: 'bank', transactionRef: 'TXN-001', status: 'completed', notes: 'First installment' },
      { id: 'pay2', date: '2024-01-20', amount: 35000, paymentMethod: 'mobile', transactionRef: 'TXN-002', status: 'completed', notes: 'Second installment' },
    ];
  });

  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem(`jaiben_payments_${investmentId}`, JSON.stringify(investmentPayments));
    }
  }, [investmentPayments, investmentId]);

  if (!investor || !investment) {
    return (
      <div className="p-4 lg:p-6">
        <div className="text-center py-12">
          <h2 className="text-xl font-bold text-slate-800">Investment Not Found</h2>
          <p className="text-slate-500 mt-2">The investment you're looking for doesn't exist.</p>
          <Link href={`/admin/investors/${investorId}`} className="mt-4 inline-flex items-center gap-2 text-investor hover:underline">
            <ArrowLeft className="w-4 h-4" /> Back to Investor
          </Link>
        </div>
      </div>
    );
  }

  const isBattery = investment.assetType === 'battery' || investment.planName?.toLowerCase().includes('battery');

  const planConfig: Record<string, { bg: string; border: string; text: string }> = {
    silver: { bg: 'bg-slate-100', border: 'border-slate-300', text: 'text-slate-600' },
    gold: { bg: 'bg-amber-100', border: 'border-amber-300', text: 'text-amber-700' },
    platinum: { bg: 'bg-purple-100', border: 'border-purple-300', text: 'text-purple-700' },
    diamond: { bg: 'bg-blue-100', border: 'border-blue-300', text: 'text-blue-700' },
  };
  const style = planConfig[investment.planType] || planConfig.gold;

  const assignedBikes = bikes.filter((b: any) => b.investorId === investorId && b.investmentId === investmentId);
  const assignedBatteries = batteries.filter((b: any) => b.investorId === investorId && b.investmentId === investmentId);
  const investmentTransactions = initialTransactions.filter((t: any) => t.investorId === investorId && t.type === 'investment_return');

  // Handlers
  const handleAssignBike = () => {
    if (!selectedBikeId) {
      toast.error('Please select a bike');
      return;
    }
    const bike = bikes.find(b => b.id === selectedBikeId);
    if (!bike) return;

    setBikes(prev => prev.map(b => {
      if (b.id === selectedBikeId) {
        return {
          ...b,
          investorId,
          investorName: investor.name,
          investmentId,
          status: 'rented',
          totalEarnings: b.totalEarnings || 0
        };
      }
      return b;
    }));
    toast.success(`Bike ${bike.model} (${bike.plateNumber}) assigned to this investment!`);
    setShowAddBikeModal(false);
    setSelectedBikeId('');
  };

  const handleRegisterAndAssignBike = () => {
    if (!registerBikeForm.plateNumber) {
      toast.error('Please enter a plate number');
      return;
    }
    const newBike = {
      id: `BIKE-${Date.now()}`,
      plateNumber: registerBikeForm.plateNumber,
      brand: registerBikeForm.brand,
      model: registerBikeForm.model,
      currentRent: Number(registerBikeForm.currentRent),
      location: registerBikeForm.location,
      purchasePrice: Number(registerBikeForm.purchasePrice),
      rentalType: registerBikeForm.rentalType,
      investorId,
      investorName: investor.name,
      investmentId,
      status: 'rented',
      batteryLevel: 100,
      totalEarnings: 0
    };
    setBikes(prev => [...prev, newBike]);
    toast.success(`New bike registered and assigned to this investment!`);
    setShowRegisterBikeModal(false);
  };

  const handleUnassignBike = (bikeId: string) => {
    setBikes(prev => prev.map(b => {
      if (b.id === bikeId) {
        return {
          ...b,
          investorId: null,
          investorName: null,
          investmentId: null,
          status: 'available'
        };
      }
      return b;
    }));
    toast.success('Bike unassigned successfully!');
  };

  const handleAssignBattery = () => {
    if (!selectedBatteryId) {
      toast.error('Please select a battery');
      return;
    }
    const bat = unassignedBatteries.find(b => b.id === selectedBatteryId);
    if (!bat) return;

    const assigned = {
      ...bat,
      investorId,
      investorName: investor.name,
      investorSharePercentage: Number(assignBatteryForm.investorShare),
      investedAmount: Number(assignBatteryForm.investedAmount),
      investmentId,
      deposit: Number(assignBatteryForm.deposit),
      rentPrice: Number(assignBatteryForm.rentPrice),
      status: 'in-use'
    };

    setBatteries(prev => [...prev, assigned]);
    setUnassignedBatteries(prev => prev.filter(b => b.id !== selectedBatteryId));
    toast.success(`Battery SN: ${bat.serialNumber} assigned to this investment!`);
    setShowAssignBatteryModal(false);
    setSelectedBatteryId('');
  };

  const handleRegisterAndAssignBattery = () => {
    if (!registerBatteryForm.serialNumber) {
      toast.error('Please enter serial number');
      return;
    }
    const newBat = {
      id: `BAT-${Date.now()}`,
      serialNumber: registerBatteryForm.serialNumber,
      brand: registerBatteryForm.brand,
      model: registerBatteryForm.model,
      type: registerBatteryForm.type,
      capacity: Number(registerBatteryForm.capacity),
      voltage: Number(registerBatteryForm.voltage),
      purchaseDate: new Date().toISOString().split('T')[0],
      purchasePrice: Number(registerBatteryForm.purchasePrice),
      deposit: Number(registerBatteryForm.deposit),
      rentPrice: Number(registerBatteryForm.rentPrice),
      investorId,
      investorName: investor.name,
      investorSharePercentage: Number(registerBatteryForm.investorShare),
      investedAmount: Number(registerBatteryForm.investedAmount),
      investmentId,
      status: 'in-use',
      currentSoc: 100,
      health: 100,
      cycleCount: 0
    };

    setBatteries(prev => [...prev, newBat]);
    toast.success('New battery registered and assigned!');
    setShowRegisterBatteryModal(false);
  };

  const handleUnassignBattery = (batteryId: string) => {
    const bat = batteries.find(b => b.id === batteryId);
    if (!bat) return;

    setBatteries(prev => prev.filter(b => b.id !== batteryId));
    setUnassignedBatteries(prev => [
      ...prev,
      {
        ...bat,
        investorId: null,
        investorName: null,
        investorSharePercentage: null,
        investedAmount: null,
        investmentId: null,
        status: 'available'
      }
    ]);
    toast.success('Battery unassigned successfully!');
  };

  return (
    <div className="p-4 lg:p-6 bg-slate-50 min-h-screen">
      <div className="max-w-8xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <button onClick={() => router.push(`/admin/investors/${investorId}`)} className="p-2 hover:bg-slate-200 rounded-lg transition-colors">
              <ArrowLeft className="w-5 h-5 text-slate-600" />
            </button>
            <div>
              <div className="flex items-center gap-3">
                <h1 className="text-2xl font-bold text-slate-800">{investment.planName}</h1>
                <span className={`px-3 py-1 rounded-full text-sm font-medium ${style.bg} ${style.text}`}>
                  {investment.planType} Plan
                </span>
                <span className={`px-3 py-1 rounded-full text-sm font-medium ${investment.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-slate-100 text-slate-600'}`}>
                  {investment.status}
                </span>
              </div>
              <p className="text-slate-500 text-sm mt-1">
                ID: #{investment.id?.slice(-8)} • Investor: {investor.name}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <button className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm font-medium hover:bg-white flex items-center gap-2">
              <Download className="w-4 h-4" /> Statement
            </button>
            {/* <button onClick={() => {
              setEditForm({
                planName: investment.planName,
                planType: investment.planType,
                totalInvestment: investment.totalInvestment,
                status: investment.status,
              });
              setShowEditModal(true);
            }} className="px-4 py-2 bg-investor text-white rounded-lg text-sm font-medium hover:bg-investor-dark flex items-center gap-2">
              <Edit className="w-4 h-4" /> Edit
            </button> */}
          </div>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
          <div className="bg-white rounded-xl p-5 border border-slate-200">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                <Wallet className="w-5 h-5 text-purple-600" />
              </div>
              <p className="text-sm text-slate-500">Investment</p>
            </div>
            <p className="text-2xl font-bold text-slate-800">৳{investment.totalInvestment.toLocaleString()}</p>
          </div>
          <div className="bg-white rounded-xl p-5 border border-slate-200">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                <TrendingUp className="w-5 h-5 text-green-600" />
              </div>
              <p className="text-sm text-slate-500">Total Return</p>
            </div>
            <p className="text-2xl font-bold text-green-600">৳{investment.actualEarnings.toLocaleString()}</p>
          </div>
          <div className="bg-white rounded-xl p-5 border border-slate-200">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center">
                <Clock className="w-5 h-5 text-amber-600" />
              </div>
              <p className="text-sm text-slate-500">Pending</p>
            </div>
            <p className="text-2xl font-bold text-amber-600">৳{Math.round(investment.totalInvestment * 0.24 - investment.actualEarnings).toLocaleString()}</p>
          </div>
          <div className="bg-white rounded-xl p-5 border border-slate-200">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                <Percent className="w-5 h-5 text-blue-600" />
              </div>
              <p className="text-sm text-slate-500">Expected ROI</p>
            </div>
            <p className="text-2xl font-bold text-blue-600">24%</p>
          </div>
        </div>

        <div className="grid lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2 space-y-6">
            <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
              <div className="flex gap-2 border-b border-slate-200 p-4">
                <button
                  onClick={() => setActiveTab('overview')}
                  className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${activeTab === 'overview' ? 'bg-investor text-white' : 'text-slate-600 hover:bg-slate-100'}`}
                >
                  Overview
                </button>
                <button
                  onClick={() => setActiveTab('transactions')}
                  className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${activeTab === 'transactions' ? 'bg-investor text-white' : 'text-slate-600 hover:bg-slate-100'}`}
                >
                  Transactions
                </button>

                <button
                  onClick={() => setActiveTab('pnl')}
                  className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${activeTab === 'pnl' ? 'bg-investor text-white' : 'text-slate-600 hover:bg-slate-100'}`}
                >
                  P&L Statement
                </button>
                {/* <button
                  onClick={() => setActiveTab('journals')}
                  className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${activeTab === 'journals' ? 'bg-investor text-white' : 'text-slate-600 hover:bg-slate-100'}`}
                >
                  Journals
                </button> */}
              </div>

              <div className="p-5">
                {activeTab === 'overview' && (
                  <div className="space-y-6">
                    <div className="grid md:grid-cols-2 gap-4">
                      <div className="bg-slate-50 rounded-xl p-4">
                        <h4 className="font-semibold text-slate-800 mb-3 flex items-center gap-2">
                          <FileText className="w-4 h-4 text-slate-500" />
                          Investment Details
                        </h4>
                        <div className="space-y-2 text-sm">
                          <div className="flex justify-between">
                            <span className="text-slate-500">Plan Name</span>
                            <span className="font-medium">{investment.planName}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Plan Type</span>
                            <span className="font-medium capitalize">{investment.planType}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Period</span>
                            <span className="font-medium">{investment.startDate} - {investment.endDate || 'Ongoing'}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Payment</span>
                            <span className="font-medium capitalize">{investment.paymentMethod}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Transaction ID</span>
                            <span className="font-medium">#{investment.id?.slice(-8)}</span>
                          </div>
                        </div>
                      </div>

                      <div className="bg-slate-50 rounded-xl p-4">
                        <h4 className="font-semibold text-slate-800 mb-3 flex items-center gap-2">
                          <Shield className="w-4 h-4 text-slate-500" />
                          Plan Configuration
                        </h4>
                        <div className="space-y-2 text-sm">
                          <div className="flex justify-between">
                            <span className="text-slate-500">{isBattery ? 'Battery Base Price' : 'EV Base Price'}</span>
                            <span className="font-medium">৳{isBattery ? (investment.batteryBasePrice || 15000).toLocaleString() : (investment.evBasePrice || 200000).toLocaleString()}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Min Quantity</span>
                            <span className="font-medium">{investment.minimumQuantity || (isBattery ? 10 : 1)} {isBattery ? 'packs' : 'bike'}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Duration</span>
                            <span className="font-medium">{investment.duration || 12} months</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Lock-in</span>
                            <span className="font-medium">{investment.lockInPeriod || 3} months</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Exit Penalty</span>
                            <span className="font-medium text-red-500">{investment.earlyExitPenalty || 10}%</span>
                          </div>
                        </div>
                      </div>
                    </div>

                    {isBattery ? (
                      <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-4">
                        <h4 className="font-semibold text-emerald-800 mb-3 flex items-center gap-2">
                          <Percent className="w-4 h-4" />
                          Partner Yield Sharing Percentage
                        </h4>
                        <p className="text-xs text-emerald-600 mb-3">Profit sharing ratio when batteries are utilized</p>
                        <div className="bg-white rounded-lg p-3 text-center border border-emerald-200 inline-block min-w-[120px]">
                          <p className="text-xs text-slate-500 mb-1">Profit Share</p>
                          <p className="text-lg font-bold text-slate-800">{investment.profitSharePercent || 40}%</p>
                        </div>
                      </div>
                    ) : (
                      <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
                        <h4 className="font-semibold text-amber-800 mb-3 flex items-center gap-2">
                          <Percent className="w-4 h-4" />
                          FICO Share - Jaiben's Profit per Ride
                        </h4>
                        <p className="text-xs text-amber-600 mb-3">Profit sharing when bikes are rented to end customers</p>
                        <div className="grid grid-cols-3 gap-3">
                          <div className="bg-white rounded-lg p-3 text-center border border-amber-200">
                            <p className="text-xs text-slate-500 mb-1">Single Rent</p>
                            <p className="text-lg font-bold text-slate-800">45%</p>
                          </div>
                          <div className="bg-white rounded-lg p-3 text-center border border-amber-200">
                            <p className="text-xs text-slate-500 mb-1">Rent to Own</p>
                            <p className="text-lg font-bold text-slate-800">55%</p>
                          </div>
                          <div className="bg-white rounded-lg p-3 text-center border border-amber-200">
                            <p className="text-xs text-slate-500 mb-1">Share EV</p>
                            <p className="text-lg font-bold text-slate-800">60%</p>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {activeTab === 'transactions' && (
                  <div>
                    <div className="flex items-center justify-between mb-4">
                      <h4 className="font-semibold text-slate-800">Transaction History</h4>
                      <button className="px-3 py-1.5 text-xs bg-investor text-white rounded-lg">Export</button>
                    </div>
                    <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-medium text-slate-500">Date</th>
                            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500">Description</th>
                            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500">Type</th>
                            <th className="px-4 py-3 text-right text-xs font-medium text-slate-500">Amount</th>
                            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500">Status</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                          <tr>
                            <td className="px-4 py-3 text-sm text-slate-500">{investment.startDate || '2024-01-15'}</td>
                            <td className="px-4 py-3 text-sm">Investment Funded</td>
                            <td className="px-4 py-3 text-sm"><span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">Credit</span></td>
                            <td className="px-4 py-3 text-sm text-right font-medium text-green-600">+৳{investment.totalInvestment.toLocaleString()}</td>
                            <td className="px-4 py-3 text-sm"><span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">Completed</span></td>
                          </tr>
                          {investment.status === 'active' && (
                            <>
                              <tr>
                                <td className="px-4 py-3 text-sm text-slate-500">2024-02-15</td>
                                <td className="px-4 py-3 text-sm">Monthly Return</td>
                                <td className="px-4 py-3 text-sm"><span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">Return</span></td>
                                <td className="px-4 py-3 text-sm text-right font-medium text-blue-600">+৳{(investment.monthlyReturn || (isBattery ? 4500 : 1700)).toLocaleString()}</td>
                                <td className="px-4 py-3 text-sm"><span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">Completed</span></td>
                              </tr>
                              <tr>
                                <td className="px-4 py-3 text-sm text-slate-500">2024-03-15</td>
                                <td className="px-4 py-3 text-sm">Monthly Return</td>
                                <td className="px-4 py-3 text-sm"><span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">Return</span></td>
                                <td className="px-4 py-3 text-sm text-right font-medium text-blue-600">+৳{(investment.monthlyReturn || (isBattery ? 4500 : 1700)).toLocaleString()}</td>
                                <td className="px-4 py-3 text-sm"><span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">Completed</span></td>
                              </tr>
                              <tr>
                                <td className="px-4 py-3 text-sm text-slate-500">2024-04-15</td>
                                <td className="px-4 py-3 text-sm">Monthly Return</td>
                                <td className="px-4 py-3 text-sm"><span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">Return</span></td>
                                <td className="px-4 py-3 text-sm text-right font-medium text-blue-600">+৳{(investment.monthlyReturn || (isBattery ? 4500 : 1700)).toLocaleString()}</td>
                                <td className="px-4 py-3 text-sm"><span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">Completed</span></td>
                              </tr>
                            </>
                          )}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}

                {activeTab === 'pnl' && (
                  <div>
                    <h4 className="font-semibold text-slate-800 mb-4">Profit & Loss Statement</h4>
                    <div className="bg-slate-50 rounded-xl p-5 space-y-4">
                      <div className="flex justify-between items-center pb-3 border-b border-slate-200">
                        <span className="text-slate-500">Total Revenue (Ride Rentals)</span>
                        <span className="text-lg font-bold text-green-600">৳1,50,000</span>
                      </div>
                      <div className="space-y-2">
                        <div className="flex justify-between text-sm">
                          <span className="text-slate-500">Jaiben's Share (45%)</span>
                          <span className="text-red-500">-৳67,500</span>
                        </div>
                        <div className="flex justify-between text-sm">
                          <span className="text-slate-500">Operational Costs</span>
                          <span className="text-red-500">-৳0</span>
                        </div>
                      </div>
                      <div className="flex justify-between items-center pt-3 border-t border-slate-200">
                        <span className="font-semibold text-slate-800">Net Profit to Investor</span>
                        <span className="text-xl font-bold text-green-600">৳82,500</span>
                      </div>
                    </div>
                  </div>
                )}

                {activeTab === 'payments' && (
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <h4 className="font-semibold text-slate-800">Payment History</h4>
                      {!isBattery && (investment.totalInvestment - investmentPayments.reduce((sum, p) => sum + p.amount, 0)) > 0 && (
                        <button
                          onClick={() => setShowPartialPaymentModal(true)}
                          className="px-3 py-1.5 text-xs bg-investor text-white rounded-lg flex items-center gap-1 hover:bg-investor-dark"
                        >
                          <Plus className="w-3 h-3" /> Record Payment
                        </button>
                      )}
                    </div>

                    <div className="bg-slate-50 rounded-xl p-4">
                      <div className="grid grid-cols-3 gap-4 mb-4">
                        <div className="text-center">
                          <p className="text-xs text-slate-500">Total Investment</p>
                          <p className="text-lg font-bold text-slate-800">৳{investment.totalInvestment.toLocaleString()}</p>
                        </div>
                        <div className="text-center">
                          <p className="text-xs text-slate-500">Paid Amount</p>
                          <p className="text-lg font-bold text-green-600">৳{investmentPayments.reduce((sum, p) => sum + p.amount, 0).toLocaleString()}</p>
                        </div>
                        <div className="text-center">
                          <p className="text-xs text-slate-500">Remaining</p>
                          <p className="text-lg font-bold text-amber-600">৳{(investment.totalInvestment - investmentPayments.reduce((sum, p) => sum + p.amount, 0)).toLocaleString()}</p>
                        </div>
                      </div>

                      <div className="w-full bg-slate-200 rounded-full h-3 mb-4">
                        <div
                          className="bg-gradient-to-r from-green-500 to-green-600 h-3 rounded-full transition-all"
                          style={{ width: `${Math.min(100, (investmentPayments.reduce((sum, p) => sum + p.amount, 0) / investment.totalInvestment) * 100)}%` }}
                        />
                      </div>
                    </div>

                    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
                      <table className="w-full">
                        <thead className="bg-slate-50">
                          <tr>
                            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500">Date</th>
                            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500">Amount</th>
                            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500">Method</th>
                            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500">Reference</th>
                            <th className="px-4 py-3 text-left text-xs font-medium text-slate-500">Status</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                          {investmentPayments.map((payment: any) => (
                            <tr key={payment.id}>
                              <td className="px-4 py-3 text-sm text-slate-500">{payment.date}</td>
                              <td className="px-4 py-3 text-sm font-bold text-green-600">৳{payment.amount.toLocaleString()}</td>
                              <td className="px-4 py-3 text-sm capitalize">{payment.paymentMethod}</td>
                              <td className="px-4 py-3 text-sm text-slate-500">{payment.transactionRef}</td>
                              <td className="px-4 py-3">
                                <span className={`px-2 py-1 rounded text-xs font-medium ${payment.status === 'completed' ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700'}`}>
                                  {payment.status}
                                </span>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}

                {activeTab === 'journals' && (
                  <div>
                    <h4 className="font-semibold text-slate-800 mb-4">Accounting Journal Entries</h4>
                    <div className="space-y-4">
                      <div className="bg-green-50 border border-green-200 rounded-xl p-4">
                        <div className="flex items-center justify-between mb-3">
                          <span className="text-xs font-medium text-green-700">Entry #JE-001 • {investment.startDate}</span>
                          <span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">Posted</span>
                        </div>
                        <div className="space-y-2">
                          <div className="flex items-center justify-between p-2 bg-white rounded border border-green-200">
                            <div>
                              <p className="text-xs text-green-600 font-medium">Debit (Dr)</p>
                              <p className="text-sm font-medium">Bank - City Bank</p>
                              <p className="text-xs text-slate-400">1200</p>
                            </div>
                            <p className="font-bold text-green-700">৳{investment.totalInvestment.toLocaleString()}</p>
                          </div>
                          <div className="flex justify-center">
                            <div className="w-6 h-6 rounded-full bg-green-200 flex items-center justify-center">
                              <span className="text-green-600 text-xs">▼</span>
                            </div>
                          </div>
                          <div className="flex items-center justify-between p-2 bg-white rounded border border-blue-200">
                            <div>
                              <p className="text-xs text-blue-600 font-medium">Credit (Cr)</p>
                              <p className="text-sm font-medium">Investor Liabilities</p>
                              <p className="text-xs text-slate-400">2200</p>
                            </div>
                            <p className="font-bold text-blue-700">৳{investment.totalInvestment.toLocaleString()}</p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {isBattery ? (
              <div className="bg-white rounded-xl border border-slate-200 p-5">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4">
                  <h4 className="font-semibold text-slate-800 flex items-center gap-2">
                    <Battery className="w-4 h-4 text-emerald-600 animate-pulse" />
                    Assigned Batteries ({assignedBatteries.length})
                  </h4>
                  <div className="flex gap-2">
                    <button onClick={() => setShowAssignBatteryModal(true)} className="px-3 py-1.5 text-xs bg-emerald-50 text-emerald-700 border border-emerald-200 rounded-lg flex items-center gap-1 hover:bg-emerald-100 transition-colors">
                      <Plus className="w-3 h-3" /> Assign Existing
                    </button>
                  </div>
                </div>
                {assignedBatteries.length > 0 ? (
                  <div className="space-y-3">
                    {assignedBatteries.map((bat: any) => {
                      return (
                        <div
                          key={bat.id}
                          className="block p-4 rounded-xl border border-emerald-100 bg-emerald-50/30 hover:shadow-md transition-all group"
                        >
                          <div className="flex items-center gap-4">
                            <div className="w-14 h-14 bg-gradient-to-br from-emerald-400 to-emerald-600 rounded-xl flex items-center justify-center shadow-sm">
                              <Battery className="w-7 h-7 text-white" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-2 mb-1">
                                <h5 className="font-semibold text-slate-800 truncate">{bat.model}</h5>
                                <span className="px-2 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700 capitalize">
                                  {bat.type}
                                </span>
                              </div>
                              <p className="text-sm text-slate-500">{bat.serialNumber} • {bat.brand}</p>
                            </div>
                            <div className="text-right">
                              <div className="flex items-center gap-1 justify-end mb-1">
                                <TrendingUp className="w-3 h-3 text-green-600" />
                                <span className="text-sm font-bold text-green-600">৳{((bat.rentPrice || 150) * 30).toLocaleString()}</span>
                              </div>
                              <p className="text-xs text-slate-400">Est. Monthly Yield</p>
                            </div>
                            <button
                              onClick={(e) => {
                                e.preventDefault();
                                e.stopPropagation();
                                setUnassignConfirmModal({
                                  show: true,
                                  type: 'battery',
                                  id: bat.id,
                                  name: `${bat.brand} ${bat.model}`,
                                  details: bat.serialNumber
                                });
                              }}
                              className="p-2 hover:bg-red-50 rounded-lg text-slate-400 hover:text-red-600 transition-colors"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>

                          <div className="mt-3 pt-3 border-t border-slate-200/50 grid grid-cols-2 md:grid-cols-4 gap-3">
                            <div>
                              <p className="text-xs text-slate-400">Status</p>
                              <p className={`text-sm font-medium capitalize ${bat.status === 'in-use' ? 'text-green-600' : 'text-blue-600'}`}>
                                {bat.status}
                              </p>
                            </div>
                            <div>
                              <p className="text-xs text-slate-400">Co-ownership Share</p>
                              <p className="text-sm font-medium text-slate-700">{bat.investorSharePercentage}%</p>
                            </div>
                            <div>
                              <p className="text-xs text-slate-400">SoC / Health</p>
                              <p className="text-sm font-medium text-slate-700">{bat.currentSoc}% / {bat.health}%</p>
                            </div>
                            <div>
                              <p className="text-xs text-slate-400">Cycle Count</p>
                              <p className="text-sm font-medium text-slate-700">{bat.cycleCount} cycles</p>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  <div className="text-center py-10 border-2 border-dashed border-slate-200 rounded-xl">
                    <Battery className="w-10 h-10 mx-auto mb-3 text-slate-300" />
                    <p className="text-sm text-slate-500 mb-3">No battery packs assigned to this investment yet</p>
                    <div className="flex justify-center gap-2">
                      <button onClick={() => setShowAssignBatteryModal(true)} className="px-4 py-2 text-sm bg-emerald-50 text-emerald-700 border border-emerald-200 rounded-lg hover:bg-emerald-100 transition-colors">
                        Assign Existing
                      </button>
                      <button onClick={() => {
                        setRegisterBatteryForm({
                          serialNumber: `SN-${new Date().getFullYear()}-${Math.floor(10000 + Math.random() * 90000)}`,
                          brand: 'BYD',
                          model: 'Li-Ion 60V50Ah',
                          type: 'lithium-ion',
                          capacity: 50,
                          voltage: 60,
                          purchasePrice: 45000,
                          deposit: 5000,
                          rentPrice: 150,
                          investorShare: 100,
                          investedAmount: investment.totalInvestment / 10
                        });
                        setShowRegisterBatteryModal(true);
                      }} className="px-4 py-2 text-sm bg-investor text-white rounded-lg hover:bg-investor-dark transition-colors">
                        Register & Assign New
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <div className="bg-white rounded-xl border border-slate-200 p-5">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4">
                  <h4 className="font-semibold text-slate-800 flex items-center gap-2">
                    <Bike className="w-4 h-4 text-slate-500" />
                    Assigned Bikes ({assignedBikes.length})
                  </h4>
                  <div className="flex gap-2">
                    <button onClick={() => setShowAddBikeModal(true)} className="px-3 py-1.5 text-xs bg-blue-50 text-blue-700 border border-blue-200 rounded-lg flex items-center gap-1 hover:bg-blue-100 transition-colors">
                      <Plus className="w-3 h-3" /> Assign Existing
                    </button>
                  </div>
                </div>
                {assignedBikes.length > 0 ? (
                  <div className="space-y-3">
                    {assignedBikes.map((bike: any) => {
                      const bikeEarnings = initialTransactions.filter(
                        (t: any) => t.investorId === investorId && t.bikeId === bike.id
                      ).reduce((sum: number, t: any) => sum + t.amount, 0);
                      const planColors: Record<string, string> = {
                        silver: 'from-slate-400 to-slate-500',
                        gold: 'from-amber-400 to-amber-600',
                        platinum: 'from-purple-400 to-purple-600',
                        diamond: 'from-blue-400 to-blue-600',
                      };
                      const planBg: Record<string, string> = {
                        silver: 'bg-slate-50 border-slate-200',
                        gold: 'bg-amber-50 border-amber-200',
                        platinum: 'bg-purple-50 border-purple-200',
                        diamond: 'bg-blue-50 border-blue-200',
                      };
                      const planText: Record<string, string> = {
                        silver: 'text-slate-600',
                        gold: 'text-amber-700',
                        platinum: 'text-purple-700',
                        diamond: 'text-blue-700',
                      };
                      const planBadge: Record<string, string> = {
                        silver: 'bg-slate-100 text-slate-600',
                        gold: 'bg-amber-100 text-amber-700',
                        platinum: 'bg-purple-100 text-purple-700',
                        diamond: 'bg-blue-100 text-blue-700',
                      };
                      const rentalTypes: Record<string, { label: string; color: string; bg: string }> = {
                        single_rent: { label: 'Single Rent', color: 'text-green-600', bg: 'bg-green-100' },
                        rent_to_own: { label: 'Rent to Own', color: 'text-blue-600', bg: 'bg-blue-100' },
                        share_ev: { label: 'Share EV', color: 'text-purple-600', bg: 'bg-purple-100' },
                      };
                      const rentalInfo = rentalTypes[bike.rentalType || 'single_rent'] || rentalTypes.single_rent;
                      return (
                        <div
                          key={bike.id}
                          className={`block p-4 rounded-xl border ${planBg[investment.planType]} hover:shadow-md transition-all group`}
                        >
                          <div className="flex items-center gap-4">
                            <div className={`w-14 h-14 bg-gradient-to-br ${planColors[investment.planType]} rounded-xl flex items-center justify-center shadow-sm`}>
                              <Bike className="w-7 h-7 text-white" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-2 mb-1">
                                <h5 className="font-semibold text-slate-800 truncate">{bike.model}</h5>
                                <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${planBadge[investment.planType]} capitalize`}>
                                  {investment.planType}
                                </span>
                              </div>
                              <p className="text-sm text-slate-500">{bike.plateNumber} • {bike.brand}</p>
                            </div>
                            <div className="text-right">
                              <div className="flex items-center gap-1 justify-end mb-1">
                                <TrendingUp className="w-3 h-3 text-green-600" />
                                <span className="text-sm font-bold text-green-600">৳{bikeEarnings.toLocaleString()}</span>
                              </div>
                              <p className="text-xs text-slate-400">Total Earnings</p>
                            </div>
                            <Link href={`/admin/fleet/${bike.id}`} className="p-2 hover:bg-white/50 rounded-lg">
                              <ArrowRight className="w-4 h-4 text-slate-400 group-hover:text-investor transition-colors" />
                            </Link>
                            <button
                              onClick={(e) => {
                                e.preventDefault();
                                e.stopPropagation();
                                setUnassignConfirmModal({
                                  show: true,
                                  type: 'bike',
                                  id: bike.id,
                                  name: bike.model,
                                  details: bike.plateNumber
                                });
                              }}
                              className="p-2 hover:bg-red-50 rounded-lg text-slate-400 hover:text-red-600 transition-colors"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>

                          <div className="mt-3 pt-3 border-t border-slate-200/50 grid grid-cols-2 md:grid-cols-5 gap-3">
                            <div>
                              <p className="text-xs text-slate-400">Status</p>
                              <p className={`text-sm font-medium capitalize ${bike.status === 'rented' ? 'text-green-600' :
                                bike.status === 'available' ? 'text-blue-600' :
                                  bike.status === 'maintenance' ? 'text-amber-600' : 'text-slate-600'
                                }`}>
                                {bike.status}
                              </p>
                            </div>
                            <div>
                              <p className="text-xs text-slate-400">Daily Rent</p>
                              <p className="text-sm font-medium text-slate-700">৳{bike.currentRent}</p>
                            </div>
                            <div>
                              <p className="text-xs text-slate-400">Battery</p>
                              <p className="text-sm font-medium text-slate-700">{bike.batteryLevel}%</p>
                            </div>
                            <div>
                              <p className="text-xs text-slate-400">Location</p>
                              <p className="text-sm font-medium text-slate-700 truncate">{bike.location}</p>
                            </div>
                            <div>
                              <p className="text-xs text-slate-400">Rental Type</p>
                              <span className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${rentalInfo.bg} ${rentalInfo.color}`}>
                                {rentalInfo.label}
                              </span>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  <div className="text-center py-10 border-2 border-dashed border-slate-200 rounded-xl">
                    <Bike className="w-10 h-10 mx-auto mb-3 text-slate-300" />
                    <p className="text-sm text-slate-500 mb-3">No bikes assigned to this investment yet</p>
                    <div className="flex justify-center gap-2">
                      <button onClick={() => setShowAddBikeModal(true)} className="px-4 py-2 text-sm bg-blue-50 text-blue-700 border border-blue-200 rounded-lg hover:bg-blue-100 transition-colors">
                        Assign Existing
                      </button>
                      <button onClick={() => {
                        setRegisterBikeForm({
                          plateNumber: `DHAKA-METRO-HA-${Math.floor(1000 + Math.random() * 9000)}`,
                          brand: 'Etron',
                          model: 'ET50',
                          currentRent: 150,
                          location: 'Banani',
                          purchasePrice: 200000,
                          rentalType: 'single_rent'
                        });
                        setShowRegisterBikeModal(true);
                      }} className="px-4 py-2 text-sm bg-investor text-white rounded-lg hover:bg-investor-dark transition-colors">
                        Register & Assign New
                      </button>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>

          <div className="space-y-6">
            <div className="bg-white rounded-xl border border-slate-200 p-5">
              <h4 className="font-semibold text-slate-800 mb-4 flex items-center gap-2">
                <Users className="w-4 h-4 text-slate-500" />
                Investor Profile
              </h4>
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 rounded-full bg-gradient-to-br from-purple-500 to-blue-500 flex items-center justify-center">
                  <span className="text-lg font-bold text-white">{investor.name.charAt(0)}</span>
                </div>
                <div>
                  <p className="font-semibold text-slate-800">{investor.name}</p>
                  <p className="text-sm text-slate-500">{investor.email}</p>
                </div>
              </div>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-slate-500">Phone</span>
                  <span className="font-medium">{investor.phone}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500">ID</span>
                  <span className="font-medium">{investor.id}</span>
                </div>
                <Link href={`/admin/investors/${investorId}`} className="flex items-center justify-between text-sm text-investor hover:underline">
                  <span>View Full Profile</span>
                  <ArrowRight className="w-4 h-4" />
                </Link>
              </div>
            </div>



            <div className="bg-white rounded-xl border border-slate-200 p-5">
              <h4 className="font-semibold text-slate-800 mb-4">Quick Actions</h4>
              <div className="space-y-2">
                <button className="w-full px-4 py-2 text-left text-sm text-slate-600 hover:bg-slate-50 rounded-lg flex items-center gap-2">
                  <Download className="w-4 h-4" /> Download Statement
                </button>
                <button className="w-full px-4 py-2 text-left text-sm text-slate-600 hover:bg-slate-50 rounded-lg flex items-center gap-2">
                  <Printer className="w-4 h-4" /> Print Report
                </button>
                <button className="w-full px-4 py-2 text-left text-sm text-slate-600 hover:bg-slate-50 rounded-lg flex items-center gap-2">
                  <BarChart3 className="w-4 h-4" /> Export to Excel
                </button>
                <button className="w-full px-4 py-2 text-left text-sm text-red-600 hover:bg-red-50 rounded-lg flex items-center gap-2">
                  <X className="w-4 h-4" /> Close Investment
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <AssignBikeModal
        isOpen={showAddBikeModal}
        onClose={() => setShowAddBikeModal(false)}
        investor={investor}
        bikes={bikes}
        preselectedPlanId={investmentId}
        onAssign={(planId, bikeIds) => {
          const assignedBikesList: any[] = [];
          setBikes(prev => prev.map(b => {
            if (bikeIds.includes(b.id)) {
              assignedBikesList.push(b);
              return {
                ...b,
                investorId: investorId,
                investorName: investor.name,
                investmentId: planId,
                status: 'rented',
                totalEarnings: b.totalEarnings || 0
              };
            }
            return b;
          }));

          setInvestors(prev => prev.map(inv => {
            if (inv.id === investor.id) {
              return {
                ...inv,
                investments: inv.investments?.map((item: any) => {
                  if (item.id === planId) {
                    const currentBikeIds = item.bikeIds || [];
                    const uniqueNewBikeIds = Array.from(new Set([...currentBikeIds, ...bikeIds]));
                    return {
                      ...item,
                      bikeIds: uniqueNewBikeIds
                    };
                  }
                  return item;
                })
              };
            }
            return inv;
          }));

          const bikeNames = assignedBikesList.map(b => `${b.model} (${b.plateNumber})`).join(', ');
          toast.success(`Successfully assigned ${bikeIds.length} bike(s): ${bikeNames}`);
        }}
      />

      {showRegisterBikeModal && (
        <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-5 border-b border-slate-100 flex items-center justify-between">
              <h2 className="text-lg font-bold text-slate-800">Register & Assign New Bike</h2>
              <button onClick={() => setShowRegisterBikeModal(false)} className="p-2 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>

            <div className="p-5 space-y-4">
              <div>
                <label className="text-sm font-medium text-slate-600 mb-1 block">Plate Number</label>
                <input
                  type="text"
                  value={registerBikeForm.plateNumber}
                  onChange={(e) => setRegisterBikeForm({ ...registerBikeForm, plateNumber: e.target.value })}
                  placeholder="DHAKA-METRO-HA-1234"
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-sm font-medium text-slate-600 mb-1 block">Brand</label>
                  <input
                    type="text"
                    value={registerBikeForm.brand}
                    onChange={(e) => setRegisterBikeForm({ ...registerBikeForm, brand: 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">Model</label>
                  <input
                    type="text"
                    value={registerBikeForm.model}
                    onChange={(e) => setRegisterBikeForm({ ...registerBikeForm, model: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-sm font-medium text-slate-600 mb-1 block">Purchase Price (৳)</label>
                  <input
                    type="number"
                    value={registerBikeForm.purchasePrice}
                    onChange={(e) => setRegisterBikeForm({ ...registerBikeForm, purchasePrice: Number(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">Daily Rent (৳)</label>
                  <input
                    type="number"
                    value={registerBikeForm.currentRent}
                    onChange={(e) => setRegisterBikeForm({ ...registerBikeForm, currentRent: Number(e.target.value) })}
                    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">Location</label>
                <input
                  type="text"
                  value={registerBikeForm.location}
                  onChange={(e) => setRegisterBikeForm({ ...registerBikeForm, location: 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">Rental Type</label>
                <select
                  value={registerBikeForm.rentalType}
                  onChange={(e) => setRegisterBikeForm({ ...registerBikeForm, rentalType: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                >
                  <option value="single_rent">Single Rent</option>
                  <option value="rent_to_own">Rent to Own</option>
                  <option value="share_ev">Share EV</option>
                </select>
              </div>
            </div>

            <div className="p-5 border-t border-slate-100 flex justify-end gap-3">
              <button onClick={() => setShowRegisterBikeModal(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={handleRegisterAndAssignBike} className="px-4 py-2 bg-investor text-white rounded-lg text-sm hover:bg-investor-dark">Register & Assign</button>
            </div>
          </div>
        </div>
      )}

      <AssignBatteryModal
        isOpen={showAssignBatteryModal}
        onClose={() => setShowAssignBatteryModal(false)}
        investor={investor}
        batteries={batteries}
        unassignedBatteries={unassignedBatteries}
        preselectedPlanId={investmentId}
        onAssign={(planId, batteryIds) => {
          const assignedBatteriesList: any[] = [];
          setBatteries(prev => prev.map(b => {
            if (batteryIds.includes(b.id)) {
              assignedBatteriesList.push(b);
              return {
                ...b,
                investorId: investorId,
                investorName: investor.name,
                investmentId: planId,
                status: 'in-use',
                investedAmount: b.purchasePrice || 45000,
                investorSharePercentage: 100,
                deposit: b.deposit || 5000,
                rentPrice: b.rentPrice || 150
              };
            }
            return b;
          }));

          setUnassignedBatteries(prev => prev.filter(b => !batteryIds.includes(b.id)));

          setInvestors(prev => prev.map(inv => {
            if (inv.id === investor.id) {
              return {
                ...inv,
                investments: inv.investments?.map((item: any) => {
                  if (item.id === planId) {
                    const currentBatteryIds = item.batteryIds || [];
                    const uniqueNewBatteryIds = Array.from(new Set([...currentBatteryIds, ...batteryIds]));
                    return {
                      ...item,
                      batteryIds: uniqueNewBatteryIds
                    };
                  }
                  return item;
                })
              };
            }
            return inv;
          }));

          const batteryNames = assignedBatteriesList.map(b => `${b.brand} ${b.model}`).join(', ');
          toast.success(`Successfully assigned ${batteryIds.length} battery/ies: ${batteryNames}`);
        }}
      />

      <UnassignConfirmModal
        isOpen={unassignConfirmModal.show}
        onClose={() => setUnassignConfirmModal(prev => ({ ...prev, show: false }))}
        type={unassignConfirmModal.type}
        name={unassignConfirmModal.name}
        details={unassignConfirmModal.details}
        onConfirm={() => {
          if (unassignConfirmModal.type === 'bike') {
            handleUnassignBike(unassignConfirmModal.id);
          } else {
            handleUnassignBattery(unassignConfirmModal.id);
          }
        }}
      />

      {showRegisterBatteryModal && (
        <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-5 border-b border-slate-100 flex items-center justify-between">
              <h2 className="text-lg font-bold text-slate-800">Register & Assign New Battery</h2>
              <button onClick={() => setShowRegisterBatteryModal(false)} className="p-2 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>

            <div className="p-5 space-y-4">
              <div>
                <label className="text-sm font-medium text-slate-600 mb-1 block">Serial Number</label>
                <input
                  type="text"
                  value={registerBatteryForm.serialNumber}
                  onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, serialNumber: e.target.value })}
                  placeholder="SN-2024-XXXXX"
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-sm font-medium text-slate-600 mb-1 block">Brand</label>
                  <input
                    type="text"
                    value={registerBatteryForm.brand}
                    onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, brand: 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">Model</label>
                  <input
                    type="text"
                    value={registerBatteryForm.model}
                    onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, model: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-sm font-medium text-slate-600 mb-1 block">Capacity (Ah)</label>
                  <input
                    type="number"
                    value={registerBatteryForm.capacity}
                    onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, capacity: Number(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">Voltage (V)</label>
                  <input
                    type="number"
                    value={registerBatteryForm.voltage}
                    onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, voltage: Number(e.target.value) })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-sm font-medium text-slate-600 mb-1 block">Purchase Price (৳)</label>
                  <input
                    type="number"
                    value={registerBatteryForm.purchasePrice}
                    onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, purchasePrice: Number(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">Security Deposit (৳)</label>
                  <input
                    type="number"
                    value={registerBatteryForm.deposit}
                    onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, deposit: Number(e.target.value) })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-sm font-medium text-slate-600 mb-1 block">Daily Rent (৳)</label>
                  <input
                    type="number"
                    value={registerBatteryForm.rentPrice}
                    onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, rentPrice: Number(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">Co-ownership Share (%)</label>
                  <input
                    type="number"
                    value={registerBatteryForm.investorShare}
                    onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, investorShare: Number(e.target.value) })}
                    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">Invested Amount (৳)</label>
                <input
                  type="number"
                  value={registerBatteryForm.investedAmount}
                  onChange={(e) => setRegisterBatteryForm({ ...registerBatteryForm, investedAmount: Number(e.target.value) })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                />
              </div>
            </div>

            <div className="p-5 border-t border-slate-100 flex justify-end gap-3">
              <button onClick={() => setShowRegisterBatteryModal(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={handleRegisterAndAssignBattery} className="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm hover:bg-emerald-700">Register & Assign</button>
            </div>
          </div>
        </div>
      )}

      {showEditModal && (
        <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-5 border-b border-slate-100 flex items-center justify-between">
              <h3 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                <Edit className="w-5 h-5" /> Edit Investment
              </h3>
              <button onClick={() => setShowEditModal(false)} className="p-1 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5 text-slate-500" />
              </button>
            </div>
            <div className="p-5 space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Plan Name</label>
                <input
                  type="text"
                  value={editForm.planName || ''}
                  onChange={(e) => setEditForm({ ...editForm, planName: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-investor"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Plan Type</label>
                <select
                  value={editForm.planType || 'gold'}
                  onChange={(e) => setEditForm({ ...editForm, planType: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-investor"
                >
                  <option value="silver">Silver</option>
                  <option value="gold">Gold</option>
                  <option value="platinum">Platinum</option>
                  <option value="diamond">Diamond</option>
                </select>
              </div>
              {/* <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Investment Amount</label>
                <input
                  type="number"
                  value={editForm.totalInvestment || 0}
                  onChange={(e) => setEditForm({ ...editForm, totalInvestment: Number(e.target.value) })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-investor"
                />
              </div> */}
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Status</label>
                <select
                  value={editForm.status || 'active'}
                  onChange={(e) => setEditForm({ ...editForm, status: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-investor"
                >
                  <option value="active">Active</option>
                  <option value="completed">Completed</option>
                  <option value="closed">Closed</option>
                </select>
              </div>
            </div>
            <div className="p-5 border-t border-slate-100 flex justify-end gap-3">
              <button onClick={() => setShowEditModal(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={() => {
                  console.log('Saving investment:', editForm);
                  setShowEditModal(false);
                }}
                className="px-4 py-2 bg-investor text-white rounded-lg text-sm font-medium hover:bg-investor-dark"
              >
                Save Changes
              </button>
            </div>
          </div>
        </div>
      )}

      {showDeleteBikeModal && bikeToDelete && (
        <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-5 border-b border-slate-100 flex items-center justify-between">
              <h3 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                <Trash2 className="w-5 h-5 text-red-500" /> Remove Bike
              </h3>
              <button onClick={() => setShowDeleteBikeModal(false)} className="p-1 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5 text-slate-500" />
              </button>
            </div>
            <div className="p-5">
              <p className="text-slate-600 mb-4">Are you sure you want to remove this bike from this investment?</p>
              <div className="bg-slate-50 rounded-lg p-4 space-y-2">
                <div className="flex justify-between">
                  <span className="text-slate-500">Bike</span>
                  <span className="font-medium">{bikeToDelete.model}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500">Plate</span>
                  <span className="font-medium">{bikeToDelete.plateNumber}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500">Investment</span>
                  <span className="font-medium">{investment.planName}</span>
                </div>
              </div>
              <p className="text-sm text-amber-600 mt-3 flex items-center gap-2">
                <AlertTriangle className="w-4 h-4" />
                This action will unassign the bike from the investor.
              </p>
            </div>
            <div className="p-5 border-t border-slate-100 flex justify-end gap-3">
              <button onClick={() => setShowDeleteBikeModal(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={() => {
                  console.log('Removing bike:', bikeToDelete.id);
                  setShowDeleteBikeModal(false);
                }}
                className="px-4 py-2 bg-red-500 text-white rounded-lg text-sm font-medium hover:bg-red-600"
              >
                Remove Bike
              </button>
            </div>
          </div>
        </div>
      )}

      {showStatementHistory && (
        <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-5 border-b border-slate-100 flex items-center justify-between">
              <h3 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                <FileText className="w-5 h-5 text-investor" /> Statement History
              </h3>
              <button onClick={() => setShowStatementHistory(false)} className="p-1 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5 text-slate-500" />
              </button>
            </div>
            <div className="p-5">
              {statementHistory.length > 0 ? (
                <div className="space-y-3">
                  {statementHistory.map((stmt: any) => (
                    <div key={stmt.id} className="flex items-center gap-3 p-3 bg-slate-50 rounded-lg hover:bg-slate-100 transition-colors">
                      <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                        <FileText className="w-5 h-5 text-purple-600" />
                      </div>
                      <div className="flex-1">
                        <p className="text-sm font-medium text-slate-800">{stmt.type}</p>
                        <p className="text-xs text-slate-500">{stmt.period}</p>
                      </div>
                      <div className="text-right">
                        <p className="text-xs text-slate-400">{stmt.downloadedAt}</p>
                        <p className="text-xs text-slate-500">by {stmt.downloadedBy}</p>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8">
                  <FileText className="w-10 h-10 mx-auto mb-3 text-slate-300" />
                  <p className="text-slate-500">No statements generated yet</p>
                </div>
              )}
            </div>
            <div className="p-5 border-t border-slate-100 flex justify-end">
              <button onClick={() => setShowStatementHistory(false)} className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50">
                Close
              </button>
            </div>
          </div>
        </div>
      )}

      {showPartialPaymentModal && (
        <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-5 border-b border-slate-100 flex items-center justify-between">
              <h3 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                <CreditCardIcon className="w-5 h-5 text-investor" /> Record Partial Payment
              </h3>
              <button onClick={() => setShowPartialPaymentModal(false)} className="p-1 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5 text-slate-500" />
              </button>
            </div>
            <div className="p-5 space-y-4">
              <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
                <div className="flex justify-between items-center">
                  <span className="text-sm text-slate-600">Total Investment</span>
                  <span className="font-bold text-slate-800">৳{investment.totalInvestment.toLocaleString()}</span>
                </div>
                <div className="flex justify-between items-center mt-2">
                  <span className="text-sm text-slate-600">Already Paid</span>
                  <span className="font-bold text-green-600">৳{investmentPayments.reduce((sum, p) => sum + p.amount, 0).toLocaleString()}</span>
                </div>
                <div className="flex justify-between items-center mt-2 pt-2 border-t border-amber-200">
                  <span className="text-sm font-semibold text-slate-700">Remaining</span>
                  <span className="font-bold text-amber-600">৳{(investment.totalInvestment - investmentPayments.reduce((sum, p) => sum + p.amount, 0)).toLocaleString()}</span>
                </div>
              </div>

              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Amount (৳) <span className="text-red-500">*</span></label>
                <input
                  type="number"
                  value={partialPayment.amount || ''}
                  onChange={(e) => setPartialPayment({ ...partialPayment, amount: Number(e.target.value) })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-investor"
                  placeholder="Enter payment amount"
                />
                <p className="text-xs text-slate-400 mt-1">Minimum: ৳1,000</p>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-slate-700 mb-1 block">Date</label>
                  <input
                    type="date"
                    value={partialPayment.date}
                    onChange={(e) => setPartialPayment({ ...partialPayment, date: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-investor"
                  />
                </div>
                <div>
                  <label className="text-sm font-medium text-slate-700 mb-1 block">Payment Method</label>
                  <select
                    value={partialPayment.paymentMethod}
                    onChange={(e) => setPartialPayment({ ...partialPayment, paymentMethod: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-investor"
                  >
                    <option value="bank">Bank Transfer</option>
                    <option value="mobile">Mobile Banking</option>
                    <option value="cash">Cash</option>
                    <option value="cheque">Cheque</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Transaction Reference</label>
                <input
                  type="text"
                  value={partialPayment.transactionRef}
                  onChange={(e) => setPartialPayment({ ...partialPayment, transactionRef: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-investor"
                  placeholder="e.g., TXN-12345"
                />
              </div>

              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Notes</label>
                <textarea
                  value={partialPayment.notes}
                  onChange={(e) => setPartialPayment({ ...partialPayment, notes: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-investor"
                  rows={2}
                  placeholder="Optional notes for this payment"
                />
              </div>

              <div className="bg-green-50 border border-green-200 rounded-lg p-3">
                <h4 className="text-xs font-semibold text-green-800 mb-2">Journal Entry Preview</h4>
                <div className="space-y-1 text-xs">
                  <div className="flex justify-between">
                    <span className="text-green-600">Dr: Bank - City Bank (1200)</span>
                    <span className="font-medium">৳{partialPayment.amount?.toLocaleString() || 0}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-blue-600">Cr: Investor Liabilities (2200)</span>
                    <span className="font-medium">৳{partialPayment.amount?.toLocaleString() || 0}</span>
                  </div>
                </div>
              </div>
            </div>
            <div className="p-5 border-t border-slate-100 flex justify-end gap-3">
              <button onClick={() => setShowPartialPaymentModal(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={() => {
                  if (partialPayment.amount <= 0) {
                    alert('Please enter a valid amount');
                    return;
                  }
                  const newPayment = {
                    id: `pay${Date.now()}`,
                    date: partialPayment.date,
                    amount: partialPayment.amount,
                    paymentMethod: partialPayment.paymentMethod,
                    transactionRef: partialPayment.transactionRef || `AUTO-${Date.now()}`,
                    status: 'completed',
                    notes: partialPayment.notes
                  };
                  setInvestmentPayments([...investmentPayments, newPayment]);
                  setPartialPayment({
                    amount: 0,
                    paymentMethod: 'bank',
                    transactionRef: '',
                    date: new Date().toISOString().split('T')[0],
                    notes: ''
                  });
                  setShowPartialPaymentModal(false);
                  alert('Payment recorded successfully!');
                }}
                disabled={partialPayment.amount <= 0}
                className="px-4 py-2 bg-investor text-white rounded-lg text-sm font-medium hover:bg-investor-dark disabled:opacity-50"
              >
                Record Payment
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}