'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';

import { useState } from 'react';
import {
  AlertTriangle, Search, Plus, X, Check, Clock, Bike, User, Phone,
  MapPin, FileText, Image as ImageIcon, DollarSign, Wrench, Battery, Key,
  CheckCircle, XCircle, ChevronDown, ChevronUp, Download, Eye, Edit,
  MessageSquare, Filter, Calendar, Save, Printer, Send, Activity
} from 'lucide-react';

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

type MaintenanceType = 'damage' | 'repair' | 'service' | 'battery_swap' | 'inspection' | 'other';
type DamageSeverity = 'critical' | 'major' | 'minor' | 'cosmetic';
type MaintenanceStatus = 'reported' | 'in_progress' | 'parts_ordered' | 'completed' | 'cancelled';
type PaymentStatus = 'pending' | 'approved' | 'paid' | 'rejected';

interface MaintenanceRecord {
  id: string;
  date: string;
  type: MaintenanceType;
  severity: DamageSeverity;
  status: MaintenanceStatus;
  paymentStatus: PaymentStatus;

  bikeId: string;
  bikeModel: string;
  bikePlate: string;
  batteryId?: string;

  reporterId: string;
  reporterName: string;
  reporterPhone: string;
  reporterRole: 'biker' | 'staff' | 'hub';

  description: string;
  location: string;

  estimatedCost: number;
  actualCost?: number;
  partsUsed?: string[];

  images: { id: string; name: string; url: string; uploadedAt: string }[];
  bills?: { id: string; name: string; url: string }[];

  assignedTo?: string;
  notes: string[];
  resolvedAt?: string;

  createdAt: string;
  createdBy: string;
}

const mockMaintenance: MaintenanceRecord[] = [
  {
    id: 'MNT-001',
    date: '2024-03-21',
    type: 'damage',
    severity: 'major',
    status: 'in_progress',
    paymentStatus: 'approved',
    bikeId: 'EV-004',
    bikeModel: 'AIMA Lightning',
    bikePlate: 'Dhaka Metro Cha-5679',
    batteryId: 'BAT-044',
    reporterId: 'BIKER-004',
    reporterName: 'Sofiq Rahman',
    reporterPhone: '01712345681',
    reporterRole: 'biker',
    description: 'Front fender damaged in accident at Gulshan signal',
    location: 'Gulshan, Dhaka',
    estimatedCost: 3500,
    actualCost: 3200,
    partsUsed: ['Front fender', 'Mounting brackets'],
    images: [
      { id: 'img1', name: 'Damage Front', url: '', uploadedAt: '2024-03-21' },
      { id: 'img2', name: 'Damage Side', url: '', uploadedAt: '2024-03-21' },
    ],
    assignedTo: 'Service Center A',
    notes: ['Parts ordered from supplier'],
    createdAt: '2024-03-21T10:00:00',
    createdBy: 'Admin',
  },
  {
    id: 'MNT-002',
    date: '2024-03-20',
    type: 'service',
    severity: 'minor',
    status: 'completed',
    paymentStatus: 'paid',
    bikeId: 'EV-002',
    bikeModel: 'Yadea DT3',
    bikePlate: 'Dhaka Metro Ba-1234',
    batteryId: 'BAT-021',
    reporterId: 'BIKER-002',
    reporterName: 'Karim Hasan',
    reporterPhone: '01712345679',
    reporterRole: 'biker',
    description: 'Routine service - brake adjustment and chain lubrication',
    location: 'Banani Hub',
    estimatedCost: 500,
    actualCost: 450,
    images: [],
    notes: ['Service completed'],
    resolvedAt: '2024-03-20T14:00:00',
    createdAt: '2024-03-20T08:00:00',
    createdBy: 'Hub Staff',
  },
  {
    id: 'MNT-003',
    date: '2024-03-19',
    type: 'battery_swap',
    severity: 'minor',
    status: 'completed',
    paymentStatus: 'pending',
    bikeId: 'EV-007',
    bikeModel: 'Etron ET50',
    bikePlate: 'Dhaka Metro Ca-8901',
    reporterId: 'BIKER-007',
    reporterName: 'Jamal',
    reporterPhone: '01712345687',
    reporterRole: 'biker',
    description: 'Battery not holding charge properly - need replacement',
    location: 'Dhanmondi, Dhaka',
    estimatedCost: 0,
    images: [],
    notes: ['Battery replaced under warranty'],
    resolvedAt: '2024-03-19T16:00:00',
    createdAt: '2024-03-19T12:00:00',
    createdBy: 'Admin',
  },
  {
    id: 'MNT-004',
    date: '2024-03-18',
    type: 'repair',
    severity: 'critical',
    status: 'parts_ordered',
    paymentStatus: 'pending',
    bikeId: 'EV-010',
    bikeModel: 'TVS iQube',
    bikePlate: 'Dhaka Metro Da-4567',
    reporterId: 'BIKER-010',
    reporterName: 'Ripon',
    reporterPhone: '01712345690',
    reporterRole: 'biker',
    description: 'Motor issue - bike not moving properly',
    location: 'Mirpur, Dhaka',
    estimatedCost: 8000,
    images: [
      { id: 'img3', name: 'Motor Damage', url: '', uploadedAt: '2024-03-18' },
    ],
    assignedTo: 'Authorized Service Center',
    notes: ['Motor needs replacement - ordered', 'Waiting for parts'],
    createdAt: '2024-03-18T09:00:00',
    createdBy: 'Admin',
  },
  {
    id: 'MNT-005',
    date: '2024-03-17',
    type: 'inspection',
    severity: 'minor',
    status: 'completed',
    paymentStatus: 'paid',
    bikeId: 'EV-001',
    bikeModel: 'AIMA Lightning',
    bikePlate: 'Dhaka Metro Aa-1111',
    reporterId: 'Hub-01',
    reporterName: 'Gulshan Hub',
    reporterPhone: '02-1234567',
    reporterRole: 'hub',
    description: 'Monthly inspection completed',
    location: 'Gulshan Hub',
    estimatedCost: 300,
    actualCost: 250,
    images: [],
    notes: ['All checks passed'],
    resolvedAt: '2024-03-17T15:00:00',
    createdAt: '2024-03-17T10:00:00',
    createdBy: 'Hub Staff',
  },
  {
    id: 'MNT-006',
    date: '2024-03-15',
    type: 'damage',
    severity: 'cosmetic',
    status: 'completed',
    paymentStatus: 'rejected',
    bikeId: 'EV-005',
    bikeModel: 'Yadea DT3',
    bikePlate: 'Dhaka Metro Ba-5678',
    reporterId: 'BIKER-005',
    reporterName: 'Rahim',
    reporterPhone: '01712345685',
    reporterRole: 'biker',
    description: 'Minor scratch on mirror - customer dropped bike slowly',
    location: 'Uttara, Dhaka',
    estimatedCost: 500,
    images: [],
    notes: ['Denied - user responsibility'],
    createdAt: '2024-03-15T14:00:00',
    createdBy: 'Admin',
  },
];

const statusColors: Record<string, string> = {
  reported: 'bg-amber-100 text-amber-700',
  in_progress: 'bg-blue-100 text-blue-700',
  parts_ordered: 'bg-purple-100 text-purple-700',
  completed: 'bg-green-100 text-green-700',
  cancelled: 'bg-red-100 text-red-700',
};

const severityColors: Record<string, string> = {
  critical: 'bg-red-100 text-red-700',
  major: 'bg-orange-100 text-orange-700',
  minor: 'bg-amber-100 text-amber-700',
  cosmetic: 'bg-slate-100 text-slate-700',
};

const paymentColors: Record<string, string> = {
  pending: 'bg-amber-100 text-amber-700',
  approved: 'bg-blue-100 text-blue-700',
  paid: 'bg-green-100 text-green-700',
  rejected: 'bg-red-100 text-red-700',
};

const typeLabels: Record<string, string> = {
  damage: 'Damage',
  repair: 'Repair',
  service: 'Service',
  battery_swap: 'Battery Swap',
  inspection: 'Inspection',
  other: 'Other',
};

const typeIcons: Record<string, any> = {
  damage: AlertTriangle,
  repair: Wrench,
  service: Wrench,
  battery_swap: Battery,
  inspection: Search,
  other: FileText,
};

export default function MaintenancePage() {
  const router = useRouter();
  const [mainCategory, setMainCategory] = useState<'damage' | 'maintenance'>('damage');
  const [targetType, setTargetType] = useState<'all' | 'battery' | 'fleet'>('all');
  const [records, setRecords] = useState<MaintenanceRecord[]>(mockMaintenance);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [selectedRecord, setSelectedRecord] = useState<MaintenanceRecord | null>(null);
  const [showDetailsModal, setShowDetailsModal] = useState(false);
  const [showNewModal, setShowNewModal] = useState(false);
  const [showAddExpenseModal, setShowAddExpenseModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showAddNoteModal, setShowAddNoteModal] = useState(false);
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [expandedNotes, setExpandedNotes] = useState<string[]>([]);
  const [newNoteText, setNewNoteText] = useState('');
  const [editForm, setEditForm] = useState<Partial<MaintenanceRecord>>({});
  const [reportType, setReportType] = useState<'damage' | 'maintenance'>('damage');
  const [showSuccessModal, setShowSuccessModal] = useState(false);

  const filteredRecords = records.filter(r => {
    const isDamage = r.type === 'damage';
    const matchesCategory = mainCategory === 'damage' ? isDamage : !isDamage;
    const matchesTarget = targetType === 'all' ||
      (targetType === 'battery' && r.batteryId) ||
      (targetType === 'fleet' && r.bikeId && !r.batteryId);
    const matchesSearch = !searchQuery ||
      r.bikeId.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.bikeModel.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.bikePlate.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.reporterName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (r.batteryId && r.batteryId.toLowerCase().includes(searchQuery.toLowerCase()));
    const matchesStatus = statusFilter === 'all' || r.status === statusFilter;
    return matchesCategory && matchesTarget && matchesSearch && matchesStatus;
  });

  const damageRecords = records.filter(r => r.type === 'damage');
  const maintenanceRecords = records.filter(r => r.type !== 'damage');
  const currentMonth = new Date().toISOString().slice(0, 7);
  const stats = {
    damageCount: damageRecords.length,
    maintenanceCount: maintenanceRecords.length,
    damageThisMonth: damageRecords.filter(r => r.date?.slice(0, 7) === currentMonth).length,
    maintenanceThisMonth: maintenanceRecords.filter(r => r.date?.slice(0, 7) === currentMonth).length,
    completedThisMonth: records.filter(r => r.status === 'completed' && r.resolvedAt?.slice(0, 7) === currentMonth).length,
    batteryDamage: damageRecords.filter(r => r.batteryId).length,
    fleetDamage: damageRecords.filter(r => r.bikeId && !r.batteryId).length,
    batteryMaintenance: maintenanceRecords.filter(r => r.batteryId).length,
    fleetMaintenance: maintenanceRecords.filter(r => r.bikeId && !r.batteryId).length,
    upcomingBattery: maintenanceRecords.filter(r => r.batteryId && r.status === 'reported').length,
    upcomingFleet: maintenanceRecords.filter(r => r.bikeId && !r.batteryId && r.status === 'reported').length,
    ongoingBattery: maintenanceRecords.filter(r => r.batteryId && r.status === 'in_progress').length,
    ongoingFleet: maintenanceRecords.filter(r => r.bikeId && !r.batteryId && r.status === 'in_progress').length,
    pendingMaintenance: maintenanceRecords.filter(r => r.status === 'reported' || r.status === 'in_progress').length,
    completedMaintenance: maintenanceRecords.filter(r => r.status === 'completed').length,
    critical: records.filter(r => r.severity === 'critical' && r.status !== 'completed').length,
    inProgress: records.filter(r => r.status === 'in_progress' || r.status === 'parts_ordered').length,
    completed: records.filter(r => r.status === 'completed').length,
    pendingPayment: records.filter(r => r.paymentStatus === 'pending' && r.status === 'completed').length,
    totalCost: records.reduce((sum, r) => sum + (r.actualCost || r.estimatedCost), 0),
  };

  const toggleNotes = (id: string) => {
    setExpandedNotes(prev =>
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  };

  const handleAddNote = () => {
    if (!selectedRecord || !newNoteText.trim()) return;
    setRecords(prev => prev.map(r =>
      r.id === selectedRecord.id
        ? { ...r, notes: [...r.notes, newNoteText] }
        : r
    ));
    setNewNoteText('');
    setShowAddNoteModal(false);
  };

  const handleCompleteRecord = () => {
    if (!selectedRecord) return;
    setRecords(prev => prev.map(r =>
      r.id === selectedRecord.id
        ? { ...r, status: 'completed', resolvedAt: new Date().toISOString().split('T')[0] }
        : r
    ));
    alert(`Record ${selectedRecord.id} marked as completed!`);
    setShowDetailsModal(false);
  };

  const handlePayment = (source: 'biker' | 'company') => {
    if (!selectedRecord) return;
    const cost = selectedRecord.actualCost || selectedRecord.estimatedCost;

    setRecords(prev => prev.map(r =>
      r.id === selectedRecord.id
        ? { ...r, paymentStatus: 'paid' }
        : r
    ));

    const journalEntry = {
      id: `MNT-JE-${Date.now()}`,
      date: new Date().toISOString().split('T')[0],
      reference: selectedRecord.id,
      description: `${selectedRecord.type === 'damage' ? 'Damage' : 'Maintenance'} - ${selectedRecord.bikePlate} - ${source === 'biker' ? 'Biker' : 'Company'} paid`,
      entries: source === 'biker' ? [
        { accountId: 'ASSET-101', accountCode: '1100', accountName: 'Cash in Hand', debit: cost, credit: 0 },
        { accountId: 'EXP-504', accountCode: '5400', accountName: 'Maintenance Expense', debit: 0, credit: cost },
      ] : [
        { accountId: 'ASSET-102', accountCode: '1200', accountName: 'Bank - City Bank', debit: cost, credit: 0 },
        { accountId: 'EXP-504', accountCode: '5400', accountName: 'Maintenance Expense', debit: 0, credit: cost },
      ],
      isPosted: true,
      isAuto: true,
      sourceType: 'maintenance' as TransactionType,
      createdAt: new Date().toISOString(),
      createdBy: 'System',
    };

    alert(`Payment processed!\n\nAmount: ৳${cost}\nSource: ${source === 'biker' ? 'Biker Wallet' : 'Company Account'}\n\nAuto-journal entry created: ${journalEntry.reference}\n\nDebit: ${source === 'biker' ? 'Cash in Hand (1100)' : 'Bank - City Bank (1200)'}\nCredit: Maintenance Expense (5400)`);
    setShowPaymentModal(false);
    setShowDetailsModal(false);
  };

  const handleGenerateInvoice = () => {
    if (!selectedRecord) return;
    import('jspdf').then(jsPDF => {
      const doc = new jsPDF.default();
      const cost = selectedRecord.actualCost || selectedRecord.estimatedCost;

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

      doc.setFontSize(14);
      doc.setTextColor(0);
      doc.text('Maintenance Invoice', 20, 32);

      doc.setFontSize(10);
      doc.setTextColor(100);
      doc.text(`Invoice No: INV-${selectedRecord.id}`, 20, 42);
      doc.text(`Date: ${selectedRecord.date}`, 20, 48);
      doc.text(`Issue Type: ${selectedRecord.type}`, 20, 54);
      doc.text(`Severity: ${selectedRecord.severity}`, 20, 60);

      doc.setFontSize(11);
      doc.setTextColor(0);
      doc.text('Bike Details', 20, 72);
      doc.setFontSize(10);
      doc.text(`Bike ID: ${selectedRecord.bikeId}`, 20, 78);
      doc.text(`Model: ${selectedRecord.bikeModel}`, 20, 84);
      doc.text(`License Plate: ${selectedRecord.bikePlate}`, 20, 90);
      if (selectedRecord.batteryId) doc.text(`Battery ID: ${selectedRecord.batteryId}`, 20, 96);

      doc.setFontSize(11);
      doc.text('Description', 20, 108);
      doc.setFontSize(10);
      const descLines = doc.splitTextToSize(selectedRecord.description, 170);
      doc.text(descLines, 20, 114);

      doc.setFontSize(11);
      doc.text('Cost Breakdown', 20, 130);
      doc.setFontSize(10);
      doc.text(`Estimated Cost: ৳${selectedRecord.estimatedCost}`, 20, 136);
      if (selectedRecord.actualCost) doc.text(`Actual Cost: ৳${selectedRecord.actualCost}`, 20, 142);

      doc.setFontSize(12);
      doc.setTextColor(6, 95, 70);
      doc.text(`Total: ৳${cost}`, 20, 152);

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

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

  return (
    <div className="p-4 lg:p-6 mb-6 lg:mb-0">
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl lg:text-3xl font-extrabold text-slate-800">Damage & Maintenance</h1>
          <p className="text-sm text-slate-500 mt-1">Track bike damage, repairs, and service records</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowNewModal(true)}
            className="py-2 px-4 bg-accent text-white rounded-lg text-sm font-medium hover:bg-accent-dark flex items-center gap-2"
          >
            <Plus className="w-4 h-4" /> Report Issue
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div className="bg-white rounded-xl p-5 shadow-sm border border-red-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-red-50 flex items-center justify-center">
              <AlertTriangle className="w-6 h-6 text-red-600" />
            </div>
            <div className="flex-1">
              <div className="flex items-baseline justify-between gap-2">
                <p className="text-2xl font-extrabold text-slate-800">{stats.damageCount}</p>
                <span className="text-xs text-red-600 font-medium bg-red-50 px-2 py-0.5 rounded">{stats.damageThisMonth} this month</span>
              </div>
              <p className="text-sm text-slate-500">Total Damage</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-blue-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-blue-50 flex items-center justify-center">
              <Wrench className="w-6 h-6 text-blue-600" />
            </div>
            <div className="flex-1">
              <div className="flex items-baseline justify-between gap-2">
                <p className="text-2xl font-extrabold text-slate-800">{stats.maintenanceCount}</p>
                <span className="text-xs text-blue-600 font-medium bg-blue-50 px-2 py-0.5 rounded">{stats.maintenanceThisMonth} this month</span>
              </div>
              <p className="text-sm text-slate-500">Total Maintenance</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-green-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-green-50 flex items-center justify-center">
              <CheckCircle className="w-6 h-6 text-green-600" />
            </div>
            <div className="flex-1">
              <div className="flex items-baseline justify-between gap-2">
                <p className="text-2xl font-extrabold text-slate-800">{stats.completed}</p>
                <span className="text-xs text-green-600 font-medium bg-green-50 px-2 py-0.5 rounded">{stats.completedThisMonth} this month</span>
              </div>
              <p className="text-sm text-slate-500">Completed</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-amber-50 flex items-center justify-center">
              <DollarSign className="w-6 h-6 text-amber-600" />
            </div>
            <div>
              <p className="text-2xl font-extrabold text-slate-800">{stats.pendingPayment}</p>
              <p className="text-sm text-slate-500">Pending Payment</p>
            </div>
          </div>
        </div>
        {/* <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-purple-50 flex items-center justify-center">
              <DollarSign className="w-6 h-6 text-purple-600" />
            </div>
            <div>
              <p className="text-lg font-extrabold text-slate-800">৳{stats.totalCost.toLocaleString()}</p>
              <p className="text-sm text-slate-500">Total Cost</p>
            </div>
          </div>
        </div> */}
      </div>

      {mainCategory === 'damage' && (
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          <div className="bg-red-50 rounded-xl p-4 border border-red-100 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-red-100 flex items-center justify-center">
                <AlertTriangle className="w-5 h-5 text-red-600" />
              </div>
              <div>
                <p className="text-lg font-bold text-slate-800">{stats.damageCount}</p>
                <p className="text-sm text-slate-500">Total Damage</p>
              </div>
            </div>
          </div>
          <div className="bg-green-50 rounded-xl p-4 border border-green-100 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-green-100 flex items-center justify-center">
                <Battery className="w-5 h-5 text-green-600" />
              </div>
              <div>
                <p className="text-lg font-bold text-slate-800">{stats.batteryDamage}</p>
                <p className="text-sm text-slate-500">Battery Damage</p>
              </div>
            </div>
          </div>
          <div className="bg-purple-50 rounded-xl p-4 border border-purple-100 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-purple-100 flex items-center justify-center">
                <Bike className="w-5 h-5 text-purple-600" />
              </div>
              <div>
                <p className="text-lg font-bold text-slate-800">{stats.fleetDamage}</p>
                <p className="text-sm text-slate-500">Fleet Damage</p>
              </div>
            </div>
          </div>
          <div className="bg-orange-50 rounded-xl p-4 border border-orange-100 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-orange-100 flex items-center justify-center">
                <Clock className="w-5 h-5 text-orange-600" />
              </div>
              <div>
                <p className="text-lg font-bold text-slate-800">{stats.critical}</p>
                <p className="text-sm text-slate-500">Critical Damage</p>
              </div>
            </div>
          </div>
        </div>
      )}

      {mainCategory === 'maintenance' && (
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          <div className="bg-blue-50 rounded-xl p-4 border border-blue-100 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                <Wrench className="w-5 h-5 text-blue-600" />
              </div>
              <div>
                <p className="text-lg font-bold text-slate-800">{stats.maintenanceCount}</p>
                <p className="text-sm text-slate-500">Total Maintenance</p>
              </div>
            </div>
          </div>
          <div className="bg-purple-50 rounded-xl p-4 border border-purple-100 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-purple-100 flex items-center justify-center">
                <Bike className="w-5 h-5 text-purple-600" />
              </div>
              <div>
                <p className="text-lg font-bold text-slate-800">{stats.upcomingFleet}</p>
                <p className="text-sm text-slate-500">Upcoming Fleet</p>
              </div>
            </div>
          </div>
          <div className="bg-green-50 rounded-xl p-4 border border-green-100 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-green-100 flex items-center justify-center">
                <Battery className="w-5 h-5 text-green-600" />
              </div>
              <div>
                <p className="text-lg font-bold text-slate-800">{stats.upcomingBattery}</p>
                <p className="text-sm text-slate-500">Upcoming Battery</p>
              </div>
            </div>
          </div>
          <div className="bg-orange-50 rounded-xl p-4 border border-orange-100 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-orange-100 flex items-center justify-center">
                <Activity className="w-5 h-5 text-orange-600" />
              </div>
              <div>
                <p className="text-lg font-bold text-slate-800">{stats.ongoingBattery + stats.ongoingFleet}</p>
                <p className="text-sm text-slate-500">Ongoing Maintenance</p>
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="bg-white rounded-xl shadow-sm border border-slate-100 mb-6">
        <div className="p-4 border-b border-slate-100">
          <div className="flex flex-col lg:flex-row lg:items-center gap-4">
            <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3">
              <div className="flex items-center gap-1 bg-slate-100 p-1 rounded-lg">
                <button
                  onClick={() => setMainCategory('damage')}
                  className={`px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 ${mainCategory === 'damage' ? 'bg-red-600 text-white shadow-sm' : 'text-slate-600 hover:bg-white hover:shadow-sm'}`}
                >
                  <AlertTriangle className="w-4 h-4" /> Damage
                </button>
                <button
                  onClick={() => setMainCategory('maintenance')}
                  className={`px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 ${mainCategory === 'maintenance' ? 'bg-blue-600 text-white shadow-sm' : 'text-slate-600 hover:bg-white hover:shadow-sm'}`}
                >
                  <Wrench className="w-4 h-4" /> Maintenance
                </button>
              </div>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => setTargetType('all')}
                  className={`px-3 py-1.5 rounded-lg text-sm font-medium ${targetType === 'all' ? 'bg-slate-800 text-white' : 'border border-slate-200 text-slate-600 hover:bg-slate-50'}`}
                >
                  All
                </button>
                <button
                  onClick={() => setTargetType('battery')}
                  className={`px-3 py-1.5 rounded-lg text-sm font-medium flex items-center gap-1 ${targetType === 'battery' ? 'bg-green-600 text-white' : 'border border-slate-200 text-slate-600 hover:bg-slate-50'}`}
                >
                  <Battery className="w-4 h-4" /> Battery
                </button>
                <button
                  onClick={() => setTargetType('fleet')}
                  className={`px-3 py-1.5 rounded-lg text-sm font-medium flex items-center gap-1 ${targetType === 'fleet' ? 'bg-purple-600 text-white' : 'border border-slate-200 text-slate-600 hover:bg-slate-50'}`}
                >
                  <Bike className="w-4 h-4" /> Fleet
                </button>
              </div>
            </div>
            <div className="flex-1">
              <div className="relative">
                <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                <input
                  type="text"
                  placeholder="Search by bike ID, plate, reporter..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full lg:w-64 pl-9 pr-4 py-2 border border-slate-200 rounded-lg text-sm"
                />
              </div>
            </div>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="py-2 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600"
            >
              <option value="all">All Status</option>
              <option value="reported">Reported</option>
              <option value="in_progress">In Progress</option>
              <option value="parts_ordered">Parts Ordered</option>
              <option value="completed">Completed</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </div>
        </div>

        <div className="divide-y divide-slate-50">
          {filteredRecords.map(record => {
            const TypeIcon = typeIcons[record.type];
            return (
              <Link key={record.id} href={`/admin/maintenance/${record.id}`} className="block p-4 lg:p-5 hover:bg-slate-50 transition-colors">
                <div className="flex flex-col lg:flex-row lg:items-start gap-3 lg:gap-4">
                  <div className="flex items-start gap-3">
                    <div className="w-10 h-10 lg:w-12 lg:h-12 rounded-lg lg:rounded-xl bg-slate-100 flex items-center justify-center flex-shrink-0">
                      <TypeIcon className="w-5 h-5 lg:w-6 lg:h-6 text-slate-600" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className="flex flex-wrap items-center gap-1.5 lg:gap-2">
                        <p className="font-semibold text-slate-800 text-sm lg:text-base">{record.id}</p>
                        {record.batteryId && (
                          <span className="inline-flex items-center gap-1 text-xs font-medium px-1.5 py-0.5 rounded-full bg-green-100 text-green-700">
                            <Battery className="w-3 h-3" /> Battery
                          </span>
                        )}
                        {!record.batteryId && record.bikeId && (
                          <span className="inline-flex items-center gap-1 text-xs font-medium px-1.5 py-0.5 rounded-full bg-purple-100 text-purple-700">
                            <Bike className="w-3 h-3" /> Fleet
                          </span>
                        )}
                        <span className={`inline-flex items-center gap-1 text-xs font-medium px-1.5 py-0.5 rounded-full ${severityColors[record.severity]}`}>
                          {record.severity}
                        </span>
                      </div>
                      <p className="text-xs lg:text-sm text-slate-500 flex flex-wrap items-center gap-x-1 lg:gap-x-2">
                        <span className="flex items-center gap-1"><Bike className="w-3 h-3" /> {record.bikeModel}</span>
                        <span className="hidden sm:inline text-slate-300">|</span>
                        <span className="text-xs">{record.bikePlate}</span>
                        <span className="hidden lg:inline text-slate-300">|</span>
                        <span className="flex items-center gap-1"><User className="w-3 h-3" /> {record.reporterName}</span>
                      </p>
                    </div>
                  </div>

                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-slate-700 line-clamp-2">{record.description}</p>
                    <div className="flex flex-wrap gap-2 lg:gap-4 text-xs lg:text-sm text-slate-500 mt-1.5">
                      <p className="flex items-center gap-1">
                        <Clock className="w-3 h-3" /> {record.date}
                      </p>
                      <p className="flex items-center gap-1 truncate max-w-[100px] lg:max-w-none">
                        <MapPin className="w-3 h-3 flex-shrink-0" /> <span className="truncate">{record.location}</span>
                      </p>
                      {record.images.length > 0 && (
                        <p className="flex items-center gap-1 text-blue-600">
                          <ImageIcon className="w-3 h-3" /> {record.images.length}
                        </p>
                      )}
                      {record.notes.length > 0 && (
                        <button
                          onClick={(e) => { e.preventDefault(); toggleNotes(record.id); }}
                          className="flex items-center gap-1 text-purple-600"
                        >
                          <MessageSquare className="w-3 h-3" /> {record.notes.length}
                          {expandedNotes.includes(record.id) ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
                        </button>
                      )}
                    </div>

                    {expandedNotes.includes(record.id) && record.notes.length > 0 && (
                      <div className="mt-2 p-3 bg-purple-50 rounded-lg space-y-1">
                        {record.notes.map((note, idx) => (
                          <p key={idx} className="text-xs text-slate-700">• {note}</p>
                        ))}
                      </div>
                    )}
                  </div>

                  <div className="flex items-center justify-between lg:justify-end gap-2 lg:gap-3 mt-2 lg:mt-0">
                    <div className="text-left lg:text-right">
                      <p className="text-sm font-medium text-slate-700">৳{record.actualCost || record.estimatedCost}</p>
                      <p className="text-xs text-slate-500">{record.paymentStatus === 'paid' ? 'Paid' : record.paymentStatus === 'approved' ? 'Approved' : 'Payment ' + record.paymentStatus}</p>
                    </div>
                    <div className="flex items-center gap-1.5 lg:gap-2">
                      <span className={`inline-flex items-center gap-1 text-xs font-medium px-2 py-1 rounded-full ${statusColors[record.status]}`}>
                        {record.status === 'reported' && <Clock className="w-3 h-3" />}
                        {record.status === 'in_progress' && <Wrench className="w-3 h-3" />}
                        {record.status === 'parts_ordered' && <AlertTriangle className="w-3 h-3" />}
                        {record.status === 'completed' && <CheckCircle className="w-3 h-3" />}
                        {record.status === 'cancelled' && <XCircle className="w-3 h-3" />}
                        <span className="hidden sm:inline">{record.status.replace('_', ' ')}</span>
                      </span>

                      <button
                        onClick={(e) => { e.preventDefault(); router.push(`/admin/maintenance/${record.id}`); }}
                        className="p-1.5 lg:p-2 hover:bg-slate-100 rounded-lg text-slate-500"
                        title="View Details"
                      >
                        <Eye className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                </div>
              </Link>
            );
          })}

          {filteredRecords.length === 0 && (
            <div className="p-12 text-center">
              <Wrench className="w-12 h-12 text-slate-300 mx-auto mb-4" />
              <p className="text-slate-500">No records found</p>
            </div>
          )}
        </div>
      </div>

      {showDetailsModal && selectedRecord && (
        <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-2xl max-h-[90vh] overflow-hidden">
            <div className="p-4 border-b border-slate-100 flex items-center justify-between">
              <div>
                <h3 className="font-semibold text-slate-800">Maintenance Details - {selectedRecord.id}</h3>
                <p className="text-xs text-slate-500">{selectedRecord.date}</p>
              </div>
              <button onClick={() => setShowDetailsModal(false)} className="p-1 hover:bg-slate-100 rounded">
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>
            <div className="p-4 overflow-y-auto max-h-[70vh]">
              <div className="grid grid-cols-2 gap-4 mb-6">
                <div className="bg-slate-50 p-4 rounded-lg">
                  <p className="text-xs text-slate-500">Type / Severity</p>
                  <p className="font-semibold text-slate-800 capitalize">{selectedRecord.type} / {selectedRecord.severity}</p>
                </div>
                <div className="bg-slate-50 p-4 rounded-lg">
                  <p className="text-xs text-slate-500">Status</p>
                  <span className={`inline-flex items-center gap-1 text-sm font-medium px-2 py-1 rounded-full ${statusColors[selectedRecord.status]}`}>
                    {selectedRecord.status.replace('_', ' ')}
                  </span>
                </div>
                <div className="bg-slate-50 p-4 rounded-lg">
                  <p className="text-xs text-slate-500">Bike</p>
                  <p className="font-semibold text-slate-800">{selectedRecord.bikeModel}</p>
                  <p className="text-sm text-slate-600">{selectedRecord.bikePlate} (ID: {selectedRecord.bikeId})</p>
                </div>
                <div className="bg-slate-50 p-4 rounded-lg">
                  <p className="text-xs text-slate-500">Battery</p>
                  <p className="font-semibold text-slate-800">{selectedRecord.batteryId || 'N/A'}</p>
                </div>
              </div>

              <div className="mb-6">
                <h4 className="font-semibold text-slate-700 mb-3">Reported By</h4>
                <div className="bg-slate-50 p-4 rounded-lg">
                  <p className="font-medium text-slate-800">{selectedRecord.reporterName}</p>
                  <p className="text-sm text-slate-600">{selectedRecord.reporterPhone}</p>
                  <p className="text-xs text-slate-500 capitalize">{selectedRecord.reporterRole}</p>
                </div>
              </div>

              <div className="mb-6">
                <h4 className="font-semibold text-slate-700 mb-3">Description</h4>
                <div className="bg-slate-50 p-4 rounded-lg">
                  <p className="text-slate-700">{selectedRecord.description}</p>
                  <p className="text-sm text-slate-500 mt-2 flex items-center gap-1">
                    <MapPin className="w-3 h-3" /> {selectedRecord.location}
                  </p>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4 mb-6">
                <div className="bg-green-50 p-4 rounded-lg border border-green-200">
                  <p className="text-xs text-green-700">Estimated Cost</p>
                  <p className="text-xl font-bold text-green-700">৳{selectedRecord.estimatedCost}</p>
                </div>
                <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
                  <p className="text-xs text-blue-700">Actual Cost</p>
                  <p className="text-xl font-bold text-blue-700">৳{selectedRecord.actualCost || 0}</p>
                </div>
              </div>

              {selectedRecord.partsUsed && selectedRecord.partsUsed.length > 0 && (
                <div className="mb-6">
                  <h4 className="font-semibold text-slate-700 mb-3">Parts Used</h4>
                  <div className="flex flex-wrap gap-2">
                    {selectedRecord.partsUsed.map((part, idx) => (
                      <span key={idx} className="px-3 py-1 bg-slate-100 rounded-full text-sm text-slate-600">
                        {part}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {selectedRecord.images.length > 0 && (
                <div className="mb-6">
                  <h4 className="font-semibold text-slate-700 mb-3">Images ({selectedRecord.images.length})</h4>
                  <div className="grid grid-cols-4 gap-2">
                    {selectedRecord.images.map((img) => (
                      <div key={img.id} className="aspect-square bg-slate-100 rounded-lg flex flex-col items-center justify-center">
                        <ImageIcon className="w-8 h-8 text-slate-400" />
                        <span className="text-xs text-slate-500 mt-1">{img.name}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {selectedRecord.notes.length > 0 && (
                <div className="mb-6">
                  <h4 className="font-semibold text-slate-700 mb-3">Notes</h4>
                  <div className="space-y-2">
                    {selectedRecord.notes.map((note, idx) => (
                      <div key={idx} className="p-3 bg-purple-50 rounded-lg">
                        <p className="text-sm text-slate-700">{note}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-between">
              <div className="flex gap-2">
                <button
                  onClick={() => { setShowDetailsModal(false); setShowEditModal(true); }}
                  className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50 flex items-center gap-2"
                >
                  <Edit className="w-4 h-4" /> Edit Record
                </button>
                <button
                  onClick={() => { setShowDetailsModal(false); setShowAddNoteModal(true); }}
                  className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50 flex items-center gap-2"
                >
                  <MessageSquare className="w-4 h-4" /> Add Note
                </button>
              </div>
              <div className="flex gap-2">
                {selectedRecord.status !== 'completed' && (
                  <button
                    onClick={handleCompleteRecord}
                    className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm hover:bg-green-700 flex items-center gap-2"
                  >
                    <Check className="w-4 h-4" /> Mark Complete
                  </button>
                )}
                {selectedRecord.status === 'completed' && selectedRecord.paymentStatus !== 'paid' && (
                  <button
                    onClick={() => { setShowDetailsModal(false); setShowPaymentModal(true); }}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700 flex items-center gap-2"
                  >
                    <DollarSign className="w-4 h-4" /> Process Payment
                  </button>
                )}
                {selectedRecord.paymentStatus === 'paid' && (
                  <button
                    onClick={handleGenerateInvoice}
                    className="px-4 py-2 bg-purple-600 text-white rounded-lg text-sm hover:bg-purple-700 flex items-center gap-2"
                  >
                    <Printer className="w-4 h-4" /> Generate Invoice
                  </button>
                )}
                <button onClick={() => setShowDetailsModal(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>
        </div>
      )}

      {showNewModal && (
        <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-2xl max-h-[90vh] overflow-hidden">
            <div className="p-4 border-b border-slate-100 flex items-center justify-between">
              <h3 className="font-semibold text-slate-800">Report New Issue</h3>
              <button onClick={() => setShowNewModal(false)} className="p-1 hover:bg-slate-100 rounded">
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>
            <div className="p-4 overflow-y-auto max-h-[70vh] space-y-4">
              <div>
                <label className="text-sm font-semibold text-slate-700 mb-2 block">Report Type *</label>
                <div className="flex gap-2 mb-4">
                  <button
                    type="button"
                    onClick={() => setReportType('damage')}
                    className={`flex-1 py-3 px-4 rounded-xl border-2 flex items-center justify-center gap-2 font-medium transition-colors ${reportType === 'damage' ? 'border-red-500 bg-red-50 text-red-700' : 'border-slate-200 text-slate-600 hover:border-red-300'}`}
                  >
                    <AlertTriangle className="w-5 h-5" /> Damage
                  </button>
                  <button
                    type="button"
                    onClick={() => setReportType('maintenance')}
                    className={`flex-1 py-3 px-4 rounded-xl border-2 flex items-center justify-center gap-2 font-medium transition-colors ${reportType === 'maintenance' ? 'border-blue-500 bg-blue-50 text-blue-700' : 'border-slate-200 text-slate-600 hover:border-blue-300'}`}
                  >
                    <Wrench className="w-5 h-5" /> Maintenance
                  </button>
                </div>
              </div>
              <div>
                <label className="text-sm font-semibold text-slate-700 mb-2 block">Select Target *</label>
                <div className="grid grid-cols-2 gap-3 mb-4">
                  <button
                    type="button"
                    className="p-4 border-2 rounded-xl flex flex-col items-center gap-2 hover:border-green-500 hover:bg-green-50 transition-colors"
                  >
                    <Battery className="w-8 h-8 text-green-600" />
                    <span className="font-medium text-slate-700">Battery</span>
                    <span className="text-xs text-slate-500">For battery issues</span>
                  </button>
                  <button
                    type="button"
                    className="p-4 border-2 rounded-xl flex flex-col items-center gap-2 hover:border-purple-500 hover:bg-purple-50 transition-colors"
                  >
                    <Bike className="w-8 h-8 text-purple-600" />
                    <span className="font-medium text-slate-700">Fleet (Bike)</span>
                    <span className="text-xs text-slate-500">For bike issues</span>
                  </button>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-xs font-medium text-slate-600 mb-1 block">Category *</label>
                  <select className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm">
                    <option value="">Select Category</option>
                    {reportType === 'damage' ? (
                      <>
                        <option value="damage">Damage</option>
                        <option value="repair">Repair</option>
                        <option value="accident">Accident</option>
                        <option value="theft">Theft</option>
                        <option value="vandalism">Vandalism</option>
                      </>
                    ) : (
                      <>
                        <option value="service">Service</option>
                        <option value="routine_service">Routine Service</option>
                        <option value="repair">Repair</option>
                        <option value="battery_swap">Battery Swap</option>
                        <option value="inspection">Inspection</option>
                      </>
                    )}
                  </select>
                </div>
                {reportType === 'damage' ? (
                  <div>
                    <label className="text-xs font-medium text-slate-600 mb-1 block">Severity *</label>
                    <select className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm">
                      <option value="critical">Critical</option>
                      <option value="major">Major</option>
                      <option value="minor">Minor</option>
                      <option value="cosmetic">Cosmetic</option>
                    </select>
                  </div>
                ) : (
                  <div>
                    <label className="text-xs font-medium text-slate-600 mb-1 block">Status</label>
                    <select className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm">
                      <option value="pending">Pending</option>
                      <option value="in_progress">In Progress</option>
                      <option value="completed">Completed</option>
                    </select>
                  </div>
                )}
                <div>
                  <label className="text-xs font-medium text-slate-600 mb-1 block">Battery ID</label>
                  <input type="text" placeholder="BAT-XXX" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                </div>
                <div>
                  <label className="text-xs font-medium text-slate-600 mb-1 block">Bike ID</label>
                  <input type="text" placeholder="EV-XXX" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                {reportType === 'damage' ? (
                  <>
                    <div>
                      <label className="text-xs font-medium text-slate-600 mb-1 block">Reporter Name *</label>
                      <input type="text" placeholder="Enter name" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                    </div>
                    <div>
                      <label className="text-xs font-medium text-slate-600 mb-1 block">Reporter Phone *</label>
                      <input type="tel" placeholder="01XXXXXXXXX" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                    </div>
                  </>
                ) : (
                  <>
                    <div>
                      <label className="text-xs font-medium text-slate-600 mb-1 block">Performed By</label>
                      <input type="text" placeholder="Technician name" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                    </div>
                    <div>
                      <label className="text-xs font-medium text-slate-600 mb-1 block">Next Due Date</label>
                      <input type="date" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                    </div>
                  </>
                )}
              </div>
              <div>
                <label className="text-xs font-medium text-slate-600 mb-1 block">Description *</label>
                <textarea rows={3} className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" placeholder="Describe the issue in detail..." />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-xs font-medium text-slate-600 mb-1 block">Location / Hub *</label>
                  <input type="text" placeholder="e.g., Gulshan Hub" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                </div>
                <div>
                  <label className="text-xs font-medium text-slate-600 mb-1 block">
                    {reportType === 'damage' ? 'Estimated Cost (৳)' : 'Service Cost (৳)'}
                  </label>
                  <input type="number" placeholder="0" className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm" />
                </div>
              </div>
              <div>
                <label className="text-xs font-medium text-slate-600 mb-1 block">Upload Images</label>
                <div className="border-2 border-dashed border-slate-200 rounded-lg p-6 text-center hover:border-accent cursor-pointer">
                  <ImageIcon className="w-8 h-8 text-slate-300 mx-auto mb-2" />
                  <p className="text-sm text-slate-500">Click to upload images</p>
                  <p className="text-xs text-slate-400">JPG, PNG up to 5MB</p>
                </div>
              </div>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2">
              <button onClick={() => setShowNewModal(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={() => { setShowNewModal(false); setShowSuccessModal(true); }} className="px-4 py-2 bg-accent text-white rounded-lg text-sm hover:bg-accent-dark">
                Submit Report
              </button>
            </div>
          </div>
        </div>
      )}

      {showAddNoteModal && selectedRecord && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div className="p-4 border-b border-slate-100 flex items-center justify-between">
              <h3 className="font-semibold text-slate-800">Add Note - {selectedRecord.id}</h3>
              <button onClick={() => setShowAddNoteModal(false)} className="p-1 hover:bg-slate-100 rounded">
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="text-sm font-medium text-slate-600 mb-2 block">New Note</label>
                <textarea
                  value={newNoteText}
                  onChange={(e) => setNewNoteText(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                  rows={4}
                  placeholder="Enter note..."
                />
              </div>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2">
              <button onClick={() => setShowAddNoteModal(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={handleAddNote}
                disabled={!newNoteText.trim()}
                className="px-4 py-2 bg-accent text-white rounded-lg text-sm hover:bg-accent-dark disabled:opacity-50"
              >
                <Save className="w-4 h-4 inline mr-1" /> Save Note
              </button>
            </div>
          </div>
        </div>
      )}

      {showPaymentModal && selectedRecord && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div className="p-4 border-b border-slate-100 flex items-center justify-between">
              <h3 className="font-semibold text-slate-800">Process Payment - {selectedRecord.id}</h3>
              <button onClick={() => setShowPaymentModal(false)} className="p-1 hover:bg-slate-100 rounded">
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div className="bg-slate-50 p-4 rounded-lg">
                <p className="text-sm text-slate-600">Amount to Pay</p>
                <p className="text-2xl font-bold text-slate-800">৳{selectedRecord.actualCost || selectedRecord.estimatedCost}</p>
              </div>
              <div className="bg-slate-50 p-4 rounded-lg">
                <p className="text-sm text-slate-600">Bike</p>
                <p className="font-medium text-slate-800">{selectedRecord.bikeModel} ({selectedRecord.bikePlate})</p>
              </div>
              <div>
                <label className="text-sm font-medium text-slate-600 mb-2 block">Payment Source</label>
                <div className="space-y-2">
                  <button
                    onClick={() => handlePayment('company')}
                    className="w-full p-4 border-2 border-slate-200 rounded-lg text-left hover:border-accent hover:bg-accent-light/30 transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                        <DollarSign className="w-5 h-5 text-blue-600" />
                      </div>
                      <div>
                        <p className="font-medium text-slate-800">Company Account</p>
                        <p className="text-sm text-slate-500">Pay from company bank/cash</p>
                      </div>
                    </div>
                  </button>
                  <button
                    onClick={() => handlePayment('biker')}
                    className="w-full p-4 border-2 border-slate-200 rounded-lg text-left hover:border-accent hover:bg-accent-light/30 transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-lg bg-green-100 flex items-center justify-center">
                        <User className="w-5 h-5 text-green-600" />
                      </div>
                      <div>
                        <p className="font-medium text-slate-800">Biker Wallet</p>
                        <p className="text-sm text-slate-500">Deduct from rider's wallet</p>
                      </div>
                    </div>
                  </button>
                </div>
              </div>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2">
              <button onClick={() => setShowPaymentModal(false)} className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50">
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}

      {showSuccessModal && (
        <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 p-6 text-center">
            <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
              <CheckCircle className="w-8 h-8 text-green-600" />
            </div>
            <h3 className="text-xl font-bold text-slate-800 mb-2">Issue Reported Successfully!</h3>
            <p className="text-slate-500 mb-6">Your issue has been submitted and will be reviewed shortly.</p>
            <button
              onClick={() => setShowSuccessModal(false)}
              className="px-6 py-2 bg-accent text-white rounded-lg hover:bg-accent-dark"
            >
              OK
            </button>
          </div>
        </div>
      )}
    </div>
  );
}