'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
  AlertTriangle, Search, Plus, X, Check, Clock, Bike, User, Phone,
  MapPin, FileText, Image, DollarSign, Wrench, Battery, Key,
  CheckCircle, XCircle, ChevronLeft, Save, Printer, Send, QrCode,
  Wallet, Building, Edit, MessageSquare, Calendar, ArrowLeft, Trash2,
  Package, Settings, History, ArrowRight
} from 'lucide-react';
import Link from 'next/link';

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 PartUsed {
  id: string;
  partId: string;
  partName: string;
  quantity: number;
  unitPrice: number;
  totalPrice: number;
  addedAt: string;
}

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;
  serviceCost?: number;
  partsUsed?: PartUsed[];
  images: { id: string; name: string; url: string; uploadedAt: string }[];
  assignedTo?: string;
  notes: string[];
  resolvedAt?: string;
  createdAt: string;
  createdBy: string;
}

interface EVPart {
  id: string;
  name: string;
  buyingPrice: number;
  sellingPrice: number;
  category: string;
  inStock: boolean;
}

const mockParts: EVPart[] = [
  { id: 'PRT-001', name: 'Front fender', buyingPrice: 800, sellingPrice: 1500, category: 'Body Parts', inStock: true },
  { id: 'PRT-002', name: 'Rear fender', buyingPrice: 900, sellingPrice: 1600, category: 'Body Parts', inStock: true },
  { id: 'PRT-003', name: 'Mounting brackets', buyingPrice: 400, sellingPrice: 800, category: 'Hardware', inStock: true },
  { id: 'PRT-004', name: 'Brake pads', buyingPrice: 350, sellingPrice: 600, category: 'Brakes', inStock: true },
  { id: 'PRT-005', name: 'Front wheel', buyingPrice: 2500, sellingPrice: 4000, category: 'Wheels', inStock: true },
  { id: 'PRT-006', name: 'Rear wheel', buyingPrice: 2200, sellingPrice: 3500, category: 'Wheels', inStock: true },
  { id: 'PRT-007', name: 'Motor controller', buyingPrice: 3500, sellingPrice: 5500, category: 'Electrical', inStock: true },
  { id: 'PRT-008', name: 'Display unit', buyingPrice: 1200, sellingPrice: 2000, category: 'Electrical', inStock: true },
  { id: 'PRT-009', name: 'Throttle', buyingPrice: 450, sellingPrice: 750, category: 'Controls', inStock: true },
  { id: 'PRT-010', name: 'Handlebar', buyingPrice: 800, sellingPrice: 1400, category: 'Controls', inStock: true },
  { id: 'PRT-011', name: 'Seat', buyingPrice: 600, sellingPrice: 1000, category: 'Comfort', inStock: true },
  { id: 'PRT-012', name: 'Side stand', buyingPrice: 250, sellingPrice: 450, category: 'Hardware', inStock: true },
];

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: [
      { id: 'PU-001', partId: 'PRT-001', partName: 'Front fender', quantity: 1, unitPrice: 1500, totalPrice: 1500, addedAt: '2024-03-21' },
      { id: 'PU-002', partId: 'PRT-003', partName: 'Mounting brackets', quantity: 2, unitPrice: 800, totalPrice: 1600, addedAt: '2024-03-21' },
      { id: 'PU-003', partId: 'PRT-004', partName: 'Brake pads', quantity: 2, unitPrice: 600, totalPrice: 1200, addedAt: '2024-03-21' },
      { id: 'PU-004', partId: 'PRT-005', partName: 'Front wheel', quantity: 1, unitPrice: 4000, totalPrice: 4000, addedAt: '2024-03-21' },
      { id: 'PU-005', partId: 'PRT-009', partName: 'Throttle', quantity: 1, unitPrice: 750, totalPrice: 750, addedAt: '2024-03-21' },
      { id: 'PU-006', partId: 'PRT-011', partName: 'Seat', quantity: 1, unitPrice: 1000, totalPrice: 1000, addedAt: '2024-03-21' },
      { id: 'PU-007', partId: 'PRT-010', partName: 'Handlebar', quantity: 1, unitPrice: 1250, totalPrice: 1250, addedAt: '2024-03-21' },
    ],
    serviceCost: 3200,
    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: 'in_progress',
    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',
};

export default function MaintenanceDetailPage() {
  const params = useParams();
  const router = useRouter();
  const id = params.id as string;

  const [record, setRecord] = useState<MaintenanceRecord | null>(null);
  const [editMode, setEditMode] = useState(false);
  const [showCompleteModal, setShowCompleteModal] = useState(false);
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [showInvoiceModal, setShowInvoiceModal] = useState(false);

  // AI OCR Simulation States
  const [isOcrProcessing, setIsOcrProcessing] = useState(false);
  const [ocrComplete, setOcrComplete] = useState(false);
  const [ocrFileName, setOcrFileName] = useState('');
  const [ocrStep, setOcrStep] = useState('');
  const [showAddNoteModal, setShowAddNoteModal] = useState(false);
  const [showAddPartModal, setShowAddPartModal] = useState(false);
  const [partSearch, setPartSearch] = useState('');
  const [invoiceData, setInvoiceData] = useState({ tips: 0, discount: 0 });
  const [invoiceCreated, setInvoiceCreated] = useState(false);
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<'online' | 'offline' | 'later' | null>(null);
  const [showPaymentSuccess, setShowPaymentSuccess] = useState(false);
  const [editForm, setEditForm] = useState<Partial<MaintenanceRecord>>({});
  const [newNoteText, setNewNoteText] = useState('');
  const [actualCost, setActualCost] = useState('');
  const [selectedPart, setSelectedPart] = useState<EVPart | null>(null);
  const [partQuantity, setPartQuantity] = useState(1);

  useEffect(() => {
    const found = mockMaintenance.find(r => r.id === id);
    if (found) {
      setRecord(found);
      setEditForm(found);
      setActualCost(found.actualCost?.toString() || '');
    }
  }, [id]);

  if (!record) {
    return (
      <div className="p-6 flex items-center justify-center min-h-[50vh]">
        <div className="text-center">
          <Wrench className="w-16 h-16 text-slate-300 mx-auto mb-4" />
          <p className="text-slate-500">Record not found</p>
          <button
            onClick={() => router.push('/admin/maintenance')}
            className="mt-4 px-4 py-2 bg-accent text-white rounded-lg text-sm"
          >
            Back to Maintenance
          </button>
        </div>
      </div>
    );
  }

  const handleSaveEdit = () => {
    setRecord(prev => prev ? { ...prev, ...editForm } : null);
    setEditMode(false);
  };

  const handleComplete = () => {
    if (!record) return;
    const cost = parseInt(actualCost) || record.estimatedCost;
    setRecord(prev => prev ? {
      ...prev,
      status: 'completed',
      resolvedAt: new Date().toISOString().split('T')[0],
      actualCost: cost
    } : null);
    setShowCompleteModal(false);
  };

  const handlePayment = (source: 'bank' | 'cash' | 'biker') => {
    if (!record) return;
    const cost = ((record.partsUsed?.reduce((s, p) => s + p.totalPrice, 0) || 0) + (record.serviceCost || 0)) + invoiceData.tips - invoiceData.discount;

    setRecord(prev => prev ? { ...prev, paymentStatus: 'paid', actualCost: cost, status: 'completed', resolvedAt: new Date().toISOString().split('T')[0] } : null);
    setShowPaymentModal(false);
    setShowPaymentSuccess(true);
  };

  const handleGenerateInvoice = () => {
    if (!record) return;
    import('jspdf').then(jsPDF => {
      const doc = new jsPDF.default();
      const partsTotal = record.partsUsed?.reduce((s, p) => s + p.totalPrice, 0) || 0;
      const serviceCost = record.serviceCost || 0;
      const subtotal = partsTotal + serviceCost;
      const total = subtotal + invoiceData.tips - invoiceData.discount;
      const cost = total || record.estimatedCost;
      const qrData = `INV-${record.id}|${record.bikePlate}|${record.type}|${cost}|${new Date().toISOString().split('T')[0]}`;

      doc.setFontSize(20);
      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-${record.id}`, 20, 42);
      doc.text(`Date: ${record.date}`, 20, 48);
      doc.text(`Issue Type: ${typeLabels[record.type]}`, 20, 54);
      doc.text(`Severity: ${record.severity}`, 20, 60);
      doc.text(`Status: ${record.status}`, 20, 66);

      doc.setFontSize(11);
      doc.setTextColor(0);
      doc.text('Bike Details', 20, 80);
      doc.setFontSize(10);
      doc.text(`Bike ID: ${record.bikeId}`, 20, 86);
      doc.text(`Model: ${record.bikeModel}`, 20, 92);
      doc.text(`License Plate: ${record.bikePlate}`, 20, 98);
      if (record.batteryId) doc.text(`Battery ID: ${record.batteryId}`, 20, 104);

      doc.setFontSize(11);
      doc.text('Reporter', 20, 118);
      doc.setFontSize(10);
      doc.text(`Name: ${record.reporterName}`, 20, 124);
      doc.text(`Phone: ${record.reporterPhone}`, 20, 130);
      doc.text(`Role: ${record.reporterRole}`, 20, 136);

      doc.setFontSize(11);
      doc.text('Description', 20, 150);
      doc.setFontSize(10);
      const descLines = doc.splitTextToSize(record.description, 170);
      doc.text(descLines, 20, 156);

      doc.setFontSize(11);
      doc.text('Service Details', 120, 80);
      doc.setFontSize(10);
      doc.text(`Location: ${record.location}`, 120, 86);
      if (record.assignedTo) doc.text(`Assigned: ${record.assignedTo}`, 120, 92);
      if (record.resolvedAt) doc.text(`Resolved: ${record.resolvedAt}`, 120, 98);

      doc.setFontSize(11);
      doc.text('Cost Breakdown', 20, 175);
      doc.setFontSize(10);
      doc.text(`Parts Total: ৳${partsTotal.toLocaleString()}`, 20, 181);
      doc.text(`Service Cost (Labor): ৳${serviceCost.toLocaleString()}`, 20, 187);
      doc.text(`Subtotal: ৳${subtotal.toLocaleString()}`, 20, 193);
      if (invoiceData.tips > 0) {
        doc.setTextColor(22, 163, 74);
        doc.text(`Tips: +৳${invoiceData.tips.toLocaleString()}`, 20, 199);
        doc.setTextColor(100);
      }
      if (invoiceData.discount > 0) {
        doc.setTextColor(220, 38, 38);
        doc.text(`Discount: -৳${invoiceData.discount.toLocaleString()}`, 20, 205);
        doc.setTextColor(100);
      }
      doc.setFontSize(12);
      doc.setTextColor(0);
      doc.text(`Total: ৳${total.toLocaleString()}`, 20, 215);

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

      doc.setFontSize(9);
      doc.setTextColor(150);
      doc.text('Generated from JAIBEN Maintenance System', 20, 280);
      doc.text(`QR: ${qrData}`, 20, 286);

      doc.save(`maintenance-invoice-${record.id}.pdf`);
    });
    setShowInvoiceModal(false);
  };

  const handleAddNote = () => {
    if (!record || !newNoteText.trim()) return;
    setRecord(prev => prev ? { ...prev, notes: [...prev.notes, newNoteText] } : null);
    setNewNoteText('');
    setShowAddNoteModal(false);
  };

  const invoiceTotal = record ? ((record.partsUsed?.reduce((s, p) => s + p.totalPrice, 0) || 0) + (record.serviceCost || 0)) + invoiceData.tips - invoiceData.discount : 0;

  return (
    <div className="p-4 lg:p-6 max-w-8xl mx-auto">
      <button
        onClick={() => router.push('/admin/maintenance')}
        className="flex items-center gap-2 text-slate-600 hover:text-slate-800 mb-4"
      >
        <ArrowLeft className="w-4 h-4" /> Back to Maintenance
      </button>

      <div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden mb-12 lg:mb-0">
        <div className="p-6 border-b border-slate-100">
          <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4">
            <div className="min-w-0">
              <div className="flex flex-wrap items-center gap-2">
                <h1 className="text-xl lg:text-2xl font-extrabold text-slate-800">{record.id}</h1>
                <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full ${severityColors[record.severity]}`}>
                  {record.severity}
                </span>
                <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full ${statusColors[record.status]}`}>
                  {record.status.replace('_', ' ')}
                </span>
                <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full ${paymentColors[record.paymentStatus]}`}>
                  {record.paymentStatus}
                </span>
              </div>
              <p className="text-slate-500 mt-1">{typeLabels[record.type]} • {record.date}</p>
            </div>
            <div className="flex flex-wrap items-center gap-2 relative">
              {ocrComplete && (
                <div className="flex items-center gap-1.5 px-3 py-1.5 bg-emerald-500/10 border border-emerald-500/20 text-emerald-600 text-xs font-bold rounded-lg mr-2 animate-fadeIn">
                  <CheckCircle className="w-3.5 h-3.5 text-emerald-500" /> Invoice Locked (OCR Synced)
                </div>
              )}
              <div className={`flex flex-wrap gap-2`}>
                {editMode ? (
                  <>
                    <button onClick={handleSaveEdit} className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm hover:bg-green-700 flex items-center gap-2">
                      <Save className="w-4 h-4" /> Save
                    </button>
                    <button onClick={() => setEditMode(false)} className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50">
                      Cancel
                    </button>
                  </>
                ) : (
                  <>
                    {!invoiceCreated && (
                      <button onClick={() => setEditMode(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
                      </button>
                    )}
                    {!invoiceCreated && (
                      <button onClick={() => 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" /> Note
                      </button>
                    )}
                    <div className={`flex flex-wrap gap-2 filter blur-[1.5px] opacity-50 pointer-events-none`}>
                      {record.status !== 'completed' && !invoiceCreated && (
                        <button
                          onClick={() => setShowCompleteModal(true)}
                          className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm hover:bg-green-700 flex items-center gap-2"
                        >
                          <FileText className="w-4 h-4" /> Create Invoice
                        </button>
                      )}
                      {record.status !== 'completed' && invoiceCreated && (
                        <>
                          <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" /> Print Invoice
                          </button>
                          <button
                            onClick={() => 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" /> Proceed to Payment
                          </button>
                          <button
                            onClick={() => setShowCompleteModal(true)}
                            className="px-3 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50"
                            title="Edit Invoice"
                          >
                            <Edit className="w-4 h-4" />
                          </button>
                        </>
                      )}
                      {record.status === 'completed' && record.paymentStatus !== 'paid' && (
                        <button
                          onClick={() => 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" /> Payment
                        </button>
                      )}
                      {record.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" /> Print Invoice
                        </button>
                      )}
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="p-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div className="space-y-4">
            <div className="bg-blue-50 p-4 rounded-xl border border-blue-100">
              <h3 className="font-semibold text-blue-800 mb-3 flex items-center gap-2">
                <Bike className="w-5 h-5" /> Bike Information
              </h3>
              {editMode ? (
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-xs text-blue-700 block mb-1">Bike ID</label>
                    <input
                      type="text"
                      value={editForm.bikeId || ''}
                      onChange={(e) => setEditForm({ ...editForm, bikeId: e.target.value })}
                      className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm"
                    />
                  </div>
                  <div>
                    <label className="text-xs text-blue-700 block mb-1">License Plate</label>
                    <input
                      type="text"
                      value={editForm.bikePlate || ''}
                      onChange={(e) => setEditForm({ ...editForm, bikePlate: e.target.value })}
                      className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm"
                    />
                  </div>
                  <div>
                    <label className="text-xs text-blue-700 block mb-1">Model</label>
                    <input
                      type="text"
                      value={editForm.bikeModel || ''}
                      onChange={(e) => setEditForm({ ...editForm, bikeModel: e.target.value })}
                      className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm"
                    />
                  </div>
                  <div>
                    <label className="text-xs text-blue-700 block mb-1">Battery ID</label>
                    <input
                      type="text"
                      value={editForm.batteryId || ''}
                      onChange={(e) => setEditForm({ ...editForm, batteryId: e.target.value })}
                      className="w-full px-3 py-2 border border-blue-200 rounded-lg text-sm"
                    />
                  </div>
                </div>
              ) : (
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-sm text-blue-600">Bike ID</span>
                    <span className="text-sm font-medium text-blue-800">{record.bikeId}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-blue-600">Model</span>
                    <span className="text-sm font-medium text-blue-800">{record.bikeModel}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-sm text-blue-600">License Plate</span>
                    <span className="text-sm font-medium text-blue-800">{record.bikePlate}</span>
                  </div>
                  {record.batteryId && (
                    <div className="flex justify-between">
                      <span className="text-sm text-blue-600">Battery ID</span>
                      <span className="text-sm font-medium text-blue-800">{record.batteryId}</span>
                    </div>
                  )}
                </div>
              )}
            </div>

            <div className="bg-orange-50 p-4 rounded-xl border border-orange-100 relative overflow-hidden transition-all duration-300">

              <div className="absolute inset-0 bg-slate-900/5 backdrop-blur-[1px] flex items-center justify-center z-10 p-2">
                <span className="px-3 py-1 bg-slate-900 text-white border border-slate-700 text-[10px] font-bold rounded-lg uppercase tracking-wider flex items-center gap-1.5 shadow-md">
                  <CheckCircle className="w-3.5 h-3.5 text-emerald-400" /> Populated via AI OCR
                </span>
              </div>

              <div className={ocrComplete ? 'filter blur-[1.5px] opacity-60 pointer-events-none' : ''}>
                <h3 className="font-semibold text-orange-800 mb-3 flex items-center gap-2">
                  <History className="w-5 h-5" /> Issue History
                </h3>
                <div className="space-y-2">
                  {record.batteryId && (
                    <Link
                      href={`/admin/maintenance/history/battery/${record.batteryId}?from=${record.id}`}
                      className="flex items-center justify-between p-2 bg-white rounded-lg hover:bg-orange-50 transition-colors"
                    >
                      <div className="flex items-center gap-2">
                        <Battery className="w-4 h-4 text-green-600" />
                        <span className="text-sm text-slate-700">Battery History</span>
                      </div>
                      <ArrowRight className="w-4 h-4 text-orange-400" />
                    </Link>
                  )}
                  {record.bikeId && (
                    <Link
                      href={`/admin/maintenance/history/bike/${record.bikeId}?from=${record.id}`}
                      className="flex items-center justify-between p-2 bg-white rounded-lg hover:bg-orange-50 transition-colors"
                    >
                      <div className="flex items-center gap-2">
                        <Bike className="w-4 h-4 text-purple-600" />
                        <span className="text-sm text-slate-700">Fleet History</span>
                      </div>
                      <ArrowRight className="w-4 h-4 text-orange-400" />
                    </Link>
                  )}
                </div>
              </div>
            </div>

            <div className="bg-green-50 p-4 rounded-xl border border-green-100">
              <h3 className="font-semibold text-green-800 mb-3 flex items-center gap-2">
                <User className="w-5 h-5" /> Reporter
              </h3>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-sm text-green-600">Name</span>
                  <span className="text-sm font-medium text-green-800">{record.reporterName}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-sm text-green-600">Phone</span>
                  <span className="text-sm font-medium text-green-800">{record.reporterPhone}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-sm text-green-600">Role</span>
                  <span className="text-sm font-medium text-green-800 capitalize">{record.reporterRole}</span>
                </div>
              </div>
            </div>

            <div className="bg-indigo-50 p-4 rounded-xl border border-indigo-100">
              <h3 className="font-semibold text-indigo-800 mb-3 flex items-center gap-2">
                <Image className="w-5 h-5" /> Images ({(editMode ? editForm.images : record.images)?.length})
              </h3>
              <div className="grid grid-cols-4 gap-2">
                {(editMode ? editForm.images : record.images)?.map((img) => (
                  <div key={img.id} className="relative aspect-square bg-white rounded-lg flex flex-col items-center justify-center border border-indigo-100">
                    <Image className="w-8 h-8 text-indigo-400" />
                    <span className="text-xs text-indigo-500 mt-1 text-center">{img.name}</span>
                    {editMode && (
                      <button
                        onClick={() => {
                          const updated = (editForm.images || []).filter((i: any) => i.id !== img.id);
                          setEditForm({ ...editForm, images: updated });
                        }}
                        className="absolute top-1 right-1 w-5 h-5 bg-red-100 rounded-full text-red-500 text-xs flex items-center justify-center"
                      >
                        ×
                      </button>
                    )}
                  </div>
                ))}
                {editMode && (
                  <label className="aspect-square bg-white rounded-lg flex flex-col items-center justify-center border border-dashed border-indigo-200 cursor-pointer hover:bg-indigo-50">
                    <Image className="w-8 h-8 text-indigo-400" />
                    <span className="text-xs text-indigo-500 mt-1">+ Add</span>
                    <input type="file" className="hidden" accept="image/*" />
                  </label>
                )}
                {(editMode ? editForm.images : record.images)?.length === 0 && !editMode && (
                  <p className="text-sm text-indigo-400 col-span-4 text-center py-4">No images</p>
                )}
              </div>
            </div>
            <div className="bg-amber-50 p-4 rounded-xl border border-amber-100">
              <h3 className="font-semibold text-amber-800 mb-3 flex items-center gap-2">
                <FileText className="w-5 h-5" /> Description
              </h3>
              {editMode ? (
                <textarea
                  value={editForm.description || ''}
                  onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                  className="w-full px-3 py-2 border border-amber-200 rounded-lg text-sm"
                  rows={3}
                />
              ) : (
                <>
                  <p className="text-sm text-amber-700 mb-3">{record.description}</p>
                  <div className="flex items-center gap-2 text-xs text-amber-600">
                    <MapPin className="w-3 h-3" /> {record.location}
                  </div>
                </>
              )}
            </div>
            <div className="bg-slate-50 p-4 rounded-xl border border-slate-100">
              <h3 className="font-semibold text-slate-800 mb-3 flex items-center gap-2">
                <MessageSquare className="w-5 h-5" /> Notes ({(editMode ? editForm.notes : record.notes)?.length})
              </h3>
              {editMode && (
                <div className="flex gap-2 mb-3">
                  <input
                    type="text"
                    id="newNoteInput"
                    placeholder="Add a note..."
                    className="flex-1 px-3 py-2 border border-slate-200 rounded-lg text-sm"
                    onKeyPress={(e) => {
                      if (e.key === 'Enter') {
                        const input = e.currentTarget as HTMLInputElement;
                        if (input.value.trim()) {
                          setEditForm({ ...editForm, notes: [...(editForm.notes || []), input.value.trim()] });
                          input.value = '';
                        }
                      }
                    }}
                  />
                  <button
                    onClick={() => {
                      const input = document.getElementById('newNoteInput') as HTMLInputElement;
                      if (input?.value.trim()) {
                        setEditForm({ ...editForm, notes: [...(editForm.notes || []), input.value.trim()] });
                        input.value = '';
                      }
                    }}
                    className="px-4 py-2 bg-accent text-white rounded-lg text-sm"
                  >
                    Add
                  </button>
                </div>
              )}
              <div className="space-y-2">
                {(editMode ? editForm.notes : record.notes)?.map((note, idx) => (
                  <div key={idx} className="text-sm text-slate-600 p-2 bg-white rounded-lg">
                    • {note}
                  </div>
                ))}
                {(editMode ? editForm.notes : record.notes)?.length === 0 && (
                  <p className="text-sm text-slate-400">No notes yet</p>
                )}
              </div>
            </div>

          </div>

          <div className="space-y-4">


            {/* Manual Invoice OCR Card */}
            <div className="bg-indigo-50/70 p-4 rounded-xl border border-indigo-100 space-y-3 relative overflow-hidden transition-all duration-300">
              <div className="flex items-center justify-between">
                <h3 className="font-semibold text-indigo-800 text-sm flex items-center gap-2">
                  <FileText className="w-5 h-5 text-indigo-600" /> {ocrComplete ? 'Manual Invoice OCR Upload' : 'Upload Manual Invoice'}
                </h3>
                {ocrComplete && (
                  <span className="px-2.5 py-0.5 bg-emerald-100 border border-emerald-200 text-emerald-800 text-[10px] font-bold rounded-full uppercase tracking-wider animate-pulse">
                    OCR Synced
                  </span>
                )}
              </div>

              {!isOcrProcessing && !ocrComplete && (
                <div className="border border-dashed border-indigo-300 hover:border-indigo-500 rounded-xl p-5 text-center cursor-pointer transition-all bg-white relative group hover:bg-indigo-50/50">
                  <input
                    type="file"
                    accept="image/*,.pdf"
                    className="absolute inset-0 opacity-0 cursor-pointer z-10"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (!file) return;
                      setOcrFileName(file.name);
                      setIsOcrProcessing(true);

                      setOcrStep('1/3: Parsing document layout & digital signature...');
                      setTimeout(() => {
                        setOcrStep('2/3: Running AI layout analysis & line item extraction...');
                        setTimeout(() => {
                          setOcrStep('3/3: Auto-populating ledger items and actual costs...');
                          setTimeout(() => {
                            setIsOcrProcessing(false);
                            setOcrComplete(true);
                            // Populate parts dynamically with mock OCR data!
                            setRecord(prev => {
                              if (!prev) return null;
                              return {
                                ...prev,
                                partsUsed: [
                                  { id: 'PU-OCR-1', partId: 'PRT-001', partName: 'Front fender (OCR Extracted)', quantity: 1, unitPrice: 1500, totalPrice: 1500, addedAt: new Date().toISOString().split('T')[0] },
                                  { id: 'PU-OCR-2', partId: 'PRT-003', partName: 'Mounting brackets (OCR Extracted)', quantity: 2, unitPrice: 800, totalPrice: 1600, addedAt: new Date().toISOString().split('T')[0] },
                                  { id: 'PU-OCR-3', partId: 'PRT-004', partName: 'Brake pads (OCR Extracted)', quantity: 2, unitPrice: 600, totalPrice: 1200, addedAt: new Date().toISOString().split('T')[0] },
                                ],
                                serviceCost: 1800,
                                actualCost: 6100, // 1500 + 1600 + 1200 + 1800
                                notes: [...prev.notes, `OCR Scan Success: Extracted items from manual invoice "${file.name}".`]
                              };
                            });
                          }, 1000);
                        }, 1200);
                      }, 1000);
                    }}
                  />
                  <div className="flex flex-col items-center justify-center space-y-2">
                    <div className="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center text-indigo-600 group-hover:scale-110 transition-transform">
                      <Plus className="w-5 h-5" />
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-slate-700">Upload manual invoice receipt</p>
                      <p className="text-xs text-slate-500 mt-0.5">No file chosen</p>
                      <p className="text-[10px] text-slate-400 mt-2 font-medium">Supports PDF, PNG, JPG (e.g. MNT-001-invoice.pdf)</p>
                    </div>
                  </div>
                </div>
              )}

              {isOcrProcessing && (
                <div className="p-4 bg-white border border-indigo-100 rounded-xl space-y-3">
                  <div className="flex justify-between text-xs">
                    <span className="text-indigo-800 font-semibold animate-pulse">Running JAIBEN AI OCR Engine...</span>
                    <span className="text-indigo-600 font-bold">{ocrStep.split(':')[0]}</span>
                  </div>
                  <div className="w-full bg-slate-100 rounded-full h-1.5 overflow-hidden border border-slate-200">
                    <div className="bg-gradient-to-r from-indigo-500 to-indigo-700 h-full w-2/3 animate-pulse rounded-full"></div>
                  </div>
                  <p className="text-[10px] text-slate-500 italic">{ocrStep}</p>
                </div>
              )}

              {ocrComplete && (
                <div className="p-4 bg-emerald-50 border border-emerald-100 rounded-xl space-y-2">
                  <div className="flex items-center gap-2 text-emerald-800 text-xs font-bold">
                    <CheckCircle className="w-4 h-4 text-emerald-600" />
                    <span>OCR PARSING COMPLETE</span>
                  </div>
                  <div className="text-xs text-slate-600 space-y-1.5 bg-white p-3 rounded-lg border border-emerald-100">
                    <p>📄 Document: <strong className="text-slate-800 font-semibold">{ocrFileName}</strong></p>
                    <p>🔧 Extracted Parts: <strong className="text-slate-800 font-semibold">3 items</strong></p>
                    <p>⚡ Labor Service Costs: <strong className="text-slate-800 font-semibold">৳1,800</strong></p>
                    <p>💰 Auto Total Synced: <strong className="text-slate-800 font-semibold">৳6,100</strong></p>
                  </div>
                  <button
                    onClick={() => {
                      setOcrComplete(false);
                      setOcrFileName('');
                      const found = mockMaintenance.find(r => r.id === id);
                      if (found) {
                        setRecord(found);
                      }
                    }}
                    className="w-full py-1.5 mt-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold rounded-lg transition-colors border border-slate-200 cursor-pointer"
                  >
                    Reset OCR Invoice Attachment
                  </button>
                </div>
              )}
            </div>

            <div className="bg-purple-50 p-4 rounded-xl border border-purple-100 relative overflow-hidden transition-all duration-300">
              {/* {ocrComplete && ( */}
              <div className="absolute inset-0 bg-slate-900/5 backdrop-blur-[1px] flex items-center justify-center z-10 p-2">
                <span className="px-3 py-1 bg-slate-900 text-white border border-slate-700 text-[10px] font-bold rounded-lg uppercase tracking-wider flex items-center gap-1.5 shadow-md">
                  <CheckCircle className="w-3.5 h-3.5 text-emerald-400" /> Populated via AI OCR
                </span>
              </div>
              {/* )} */}
              <div className={ocrComplete ? 'filter blur-[1.5px] opacity-60 pointer-events-none' : ''}>
                <h3 className="font-semibold text-purple-800 mb-3 flex items-center gap-2">
                  <DollarSign className="w-5 h-5" /> Cost Details
                </h3>
                <div className="bg-gradient-to-r from-purple-50 to-indigo-50 p-4 rounded-xl border border-purple-100">
                  <div className="flex items-center justify-between mb-3">
                    <h3 className="font-semibold text-purple-800 flex items-center gap-2">
                      <DollarSign className="w-5 h-5" /> Cost Breakdown
                    </h3>
                    {editMode && (
                      <input
                        type="number"
                        value={editForm.estimatedCost || 0}
                        onChange={(e) => setEditForm({ ...editForm, estimatedCost: parseInt(e.target.value) })}
                        className="px-2 py-1 border border-purple-200 rounded text-sm w-24"
                      />
                    )}
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between items-center text-sm">
                      <span className="text-slate-600">Estimated Cost:</span>
                      <span className="font-medium text-purple-700">৳{record.estimatedCost.toLocaleString()}</span>
                    </div>

                    <div className="border-t border-purple-100 pt-2">
                      <div className="flex justify-between items-center text-sm">
                        <span className="text-slate-600 flex items-center gap-1">
                          <Package className="w-4 h-4" /> Parts Total:
                        </span>
                        <span className="font-medium text-orange-600">৳{record.partsUsed?.reduce((sum, p) => sum + p.totalPrice, 0).toLocaleString() || 0}</span>
                      </div>

                      <div className="flex justify-between items-center text-sm mt-1">
                        <span className="text-slate-600 flex items-center gap-1">
                          <Wrench className="w-4 h-4" /> Service Cost (Labor):
                        </span>
                        <span className="font-medium text-blue-600">৳{(record.serviceCost || 0).toLocaleString()}</span>
                      </div>
                    </div>

                    <div className="border-t-2 border-purple-200 pt-2 mt-2">
                      <div className="flex justify-between items-center">
                        <span className="font-semibold text-purple-800">Actual Total Cost:</span>
                        <span className="text-xl font-bold text-purple-800">
                          ৳{((record.partsUsed?.reduce((sum, p) => sum + p.totalPrice, 0) || 0) + (record.serviceCost || 0)).toLocaleString()}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-cyan-50 p-4 rounded-xl border border-cyan-100">
              <h3 className="font-semibold text-cyan-800 mb-3 flex items-center gap-2">
                <User className="w-5 h-5" /> Assigned To
              </h3>
              {editMode ? (
                <select
                  value={editForm.assignedTo || ''}
                  onChange={(e) => setEditForm({ ...editForm, assignedTo: e.target.value })}
                  className="w-full px-3 py-2 border border-cyan-200 rounded-lg text-sm"
                >
                  <option value="">Select Service Center</option>
                  <option value="Service Center A">Service Center A</option>
                  <option value="Service Center B">Service Center B</option>
                  <option value="Authorized Service Center">Authorized Service Center</option>
                  <option value="Gulshan Hub">Gulshan Hub</option>
                  <option value="Banani Hub">Banani Hub</option>
                  <option value="Dhanmondi Hub">Dhanmondi Hub</option>
                </select>
              ) : (
                <p className="text-sm text-cyan-700">{record.assignedTo || 'Not assigned'}</p>
              )}
            </div>

            <div className="bg-orange-50 p-4 rounded-xl border border-orange-100 relative overflow-hidden transition-all duration-300">
              {/* {ocrComplete && ( */}
              <div className="absolute inset-0 bg-slate-900/5 backdrop-blur-[1px] flex items-center justify-center z-10 p-2">
                <span className="px-3 py-1 bg-slate-900 text-white border border-slate-700 text-[10px] font-bold rounded-lg uppercase tracking-wider flex items-center gap-1.5 shadow-md">
                  <CheckCircle className="w-3.5 h-3.5 text-emerald-400" /> Populated via AI OCR
                </span>
              </div>
              {/* )} */}
              <div className={ocrComplete ? 'filter blur-[1.5px] opacity-60 pointer-events-none' : ''}>
                <div className="flex items-center justify-between mb-3">
                  <h3 className="font-semibold text-orange-800 flex items-center gap-2">
                    <Wrench className="w-5 h-5" /> Parts Used
                  </h3>
                  {!editMode && (
                    <button
                      onClick={() => setShowAddPartModal(true)}
                      className="px-3 py-1 bg-orange-600 text-white text-xs rounded-lg hover:bg-orange-700 flex items-center gap-1"
                    >
                      <Plus className="w-3 h-3" /> Add Part
                    </button>
                  )}
                </div>
                <div className="space-y-3">
                  {record.partsUsed && record.partsUsed.length > 0 ? (
                    <>
                      <div className="hidden lg:block overflow-x-auto">
                        <table className="w-full text-sm">
                          <thead className="bg-orange-100">
                            <tr>
                              <th className="px-3 py-2 text-left text-orange-800 font-medium">Part</th>
                              <th className="px-3 py-2 text-center text-orange-800 font-medium">Qty</th>
                              <th className="px-3 py-2 text-right text-orange-800 font-medium">Unit Price</th>
                              <th className="px-3 py-2 text-right text-orange-800 font-medium">Total</th>
                              <th className="px-3 py-2 text-center text-orange-800 font-medium">Action</th>
                            </tr>
                          </thead>
                          <tbody>
                            {record.partsUsed?.map((part) => (
                              <tr key={part.id} className="bg-white border-b border-orange-100">
                                <td className="px-3 py-2 text-slate-700">{part.partName}</td>
                                <td className="px-3 py-2 text-center">
                                  <input
                                    type="number"
                                    min="1"
                                    value={part.quantity}
                                    onChange={(e) => {
                                      const newQty = Math.max(1, parseInt(e.target.value) || 1);
                                      setRecord(prev => prev ? {
                                        ...prev,
                                        partsUsed: prev.partsUsed?.map(p =>
                                          p.id === part.id
                                            ? { ...p, quantity: newQty, totalPrice: newQty * p.unitPrice }
                                            : p
                                        )
                                      } : null);
                                    }}
                                    className="w-16 px-2 py-1 border border-orange-200 rounded text-center text-sm"
                                  />
                                </td>
                                <td className="px-3 py-2 text-right text-slate-600">৳{part.unitPrice.toLocaleString()}</td>
                                <td className="px-3 py-2 text-right font-medium text-orange-700">৳{part.totalPrice.toLocaleString()}</td>
                                <td className="px-3 py-2 text-center">
                                  <button
                                    onClick={() => {
                                      setRecord(prev => prev ? {
                                        ...prev,
                                        partsUsed: prev.partsUsed?.filter(p => p.id !== part.id)
                                      } : null);
                                    }}
                                    className="text-red-400 hover:text-red-600 p-1"
                                  >
                                    <Trash2 className="w-4 h-4" />
                                  </button>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                      <div className="lg:hidden grid grid-cols-1 sm:grid-cols-2 gap-3">
                        {record.partsUsed.map((part) => (
                          <div key={part.id} className="bg-white rounded-lg border border-orange-200 p-3">
                            <div className="flex items-start justify-between mb-2">
                              <span className="font-medium text-slate-800">{part.partName}</span>
                              <button
                                onClick={() => {
                                  setRecord(prev => prev ? {
                                    ...prev,
                                    partsUsed: prev.partsUsed?.filter(p => p.id !== part.id)
                                  } : null);
                                }}
                                className="text-red-400 hover:text-red-600 p-1"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>
                            <div className="flex items-center justify-between text-sm mb-2">
                              <div className="flex items-center gap-2">
                                <span className="text-slate-500">Qty:</span>
                                <input
                                  type="number"
                                  min="1"
                                  value={part.quantity}
                                  onChange={(e) => {
                                    const newQty = Math.max(1, parseInt(e.target.value) || 1);
                                    setRecord(prev => prev ? {
                                      ...prev,
                                      partsUsed: prev.partsUsed?.map(p =>
                                        p.id === part.id
                                          ? { ...p, quantity: newQty, totalPrice: newQty * p.unitPrice }
                                          : p
                                      )
                                    } : null);
                                  }}
                                  className="w-16 px-2 py-1 border border-orange-200 rounded text-center text-sm"
                                />
                              </div>
                              <span className="text-slate-600">৳{part.unitPrice.toLocaleString()}/unit</span>
                            </div>
                            <div className="pt-2 border-t border-orange-100 flex justify-between">
                              <span className="text-xs text-slate-500">Total</span>
                              <span className="font-bold text-orange-700">৳{part.totalPrice.toLocaleString()}</span>
                            </div>
                          </div>
                        ))}
                      </div>
                    </>
                  ) : (
                    <p className="text-sm text-orange-400">No parts added</p>
                  )}
                  {record.partsUsed && record.partsUsed.length > 0 && (
                    <div className="bg-orange-50 rounded-lg p-3 flex justify-between items-center">
                      <span className="font-semibold text-orange-800">Parts Total:</span>
                      <span className="text-lg font-bold text-orange-700">
                        ৳{record.partsUsed.reduce((sum, p) => sum + p.totalPrice, 0).toLocaleString()}
                      </span>
                    </div>
                  )}
                </div>
              </div>
            </div>


          </div>
        </div>
      </div>

      {showCompleteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg">
            <div className="p-4 border-b border-slate-100 bg-gradient-to-r from-green-50 to-emerald-50">
              <h3 className="font-semibold text-slate-800 flex items-center gap-2">
                <FileText className="w-5 h-5 text-green-600" /> {invoiceCreated ? 'Edit Invoice' : 'Create Invoice'}
              </h3>
              <p className="text-xs text-slate-500">{record.id} • {record.bikeModel}</p>
            </div>
            <div className="p-4 space-y-4">
              <div className="bg-slate-50 p-3 rounded-lg">
                <div className="flex justify-between text-sm mb-2">
                  <span className="text-slate-500">Parts Total:</span>
                  <span className="font-medium text-orange-600">৳{record.partsUsed?.reduce((s, p) => s + p.totalPrice, 0).toLocaleString()}</span>
                </div>
                <div>
                  <label className="text-xs font-medium text-blue-600 mb-1 block">Service Cost (Labor)</label>
                  <div className="flex gap-2">
                    <input
                      type="number"
                      min="0"
                      value={record.serviceCost || ''}
                      onChange={(e) => setRecord(prev => prev ? { ...prev, serviceCost: parseInt(e.target.value) || 0 } : null)}
                      className="flex-1 px-3 py-2 border border-blue-200 rounded-lg text-sm"
                      placeholder="Enter labor cost"
                    />
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium text-slate-500 mb-1 block">Add Tips (৳)</label>
                  <input
                    type="number"
                    min="0"
                    value={invoiceData.tips}
                    onChange={(e) => setInvoiceData({ ...invoiceData, tips: parseInt(e.target.value) || 0 })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                    placeholder="0"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-slate-500 mb-1 block">Discount (৳)</label>
                  <input
                    type="number"
                    min="0"
                    value={invoiceData.discount}
                    onChange={(e) => setInvoiceData({ ...invoiceData, discount: parseInt(e.target.value) || 0 })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                    placeholder="0"
                  />
                </div>
              </div>

              <div className="bg-green-50 p-4 rounded-lg border border-green-100">
                <div className="flex justify-between items-center mb-2">
                  <span className="text-slate-600">Subtotal:</span>
                  <span className="font-medium text-slate-700">৳{((record.partsUsed?.reduce((s, p) => s + p.totalPrice, 0) || 0) + (record.serviceCost || 0)).toLocaleString()}</span>
                </div>
                {invoiceData.tips > 0 && (
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-slate-500">Tips:</span>
                    <span className="text-green-600">+৳{invoiceData.tips.toLocaleString()}</span>
                  </div>
                )}
                {invoiceData.discount > 0 && (
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-slate-500">Discount:</span>
                    <span className="text-red-500">-৳{invoiceData.discount.toLocaleString()}</span>
                  </div>
                )}
                <div className="border-t border-green-200 pt-2 mt-2">
                  <div className="flex justify-between items-center">
                    <span className="font-bold text-green-800">Total Amount:</span>
                    <span className="text-2xl font-bold text-green-700">৳{(((record.partsUsed?.reduce((s, p) => s + p.totalPrice, 0) || 0) + (record.serviceCost || 0)) + invoiceData.tips - invoiceData.discount).toLocaleString()}</span>
                  </div>
                </div>
              </div>

              <p className="text-xs text-slate-400 flex items-center gap-1">
                <AlertTriangle className="w-3 h-3" /> After payment, this maintenance will be marked as completed
              </p>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2">
              <button onClick={() => { setShowCompleteModal(false); setInvoiceData({ tips: 0, discount: 0 }); }} className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg">Cancel</button>
              <button
                onClick={() => { setInvoiceCreated(true); setShowCompleteModal(false); }}
                className="px-4 py-2 bg-green-600 text-white rounded-lg flex items-center gap-2"
              >
                <FileText className="w-4 h-4" /> {invoiceCreated ? 'Update Invoice' : 'Create Invoice'}
              </button>
            </div>
          </div>
        </div>
      )}

      {showPaymentModal && record && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg">
            <div className="p-4 border-b border-slate-100 bg-blue-50">
              <h3 className="font-semibold text-slate-800 flex items-center gap-2">
                <Wallet className="w-5 h-5 text-blue-600" /> Process Payment
              </h3>
              <div className="mt-2 bg-white p-3 rounded-lg border border-blue-100">
                <p className="text-xs text-slate-500">Invoice Total</p>
                <p className="text-2xl font-bold text-blue-700">৳{invoiceTotal.toLocaleString()}</p>
              </div>
            </div>
            <div className="p-4 space-y-4">
              <p className="text-sm text-slate-600 mb-2">Select payment method:</p>
              <button
                onClick={() => handlePayment('bank')}
                className="w-full p-4 border-2 border-slate-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 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">
                    <Building className="w-5 h-5 text-blue-600" />
                  </div>
                  <div className="text-left">
                    <p className="font-medium text-slate-800">Bank Transfer</p>
                    <p className="text-xs text-slate-500">Debit Bank (1200) → Credit Maintenance (5400)</p>
                  </div>
                </div>
              </button>
              <button
                onClick={() => handlePayment('cash')}
                className="w-full p-4 border-2 border-slate-200 rounded-lg hover:border-green-500 hover:bg-green-50 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">
                    <Wallet className="w-5 h-5 text-green-600" />
                  </div>
                  <div className="text-left">
                    <p className="font-medium text-slate-800">Offline (Cash)</p>
                    <p className="text-xs text-slate-500">Pay with cash</p>
                  </div>
                </div>
              </button>
              <button
                onClick={() => {
                  if (!record) return;
                  setRecord(prev => prev ? { ...prev, paymentStatus: 'pending' } : null);
                  setShowPaymentModal(false);
                }}
                className="w-full p-4 border-2 border-slate-200 rounded-lg hover:border-orange-500 hover:bg-orange-50 transition-colors"
              >
                <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 className="text-left">
                    <p className="font-medium text-slate-800">Pay Later</p>
                    <p className="text-xs text-slate-500">Mark as pending payment</p>
                  </div>
                </div>
              </button>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end">
              <button onClick={() => setShowPaymentModal(false)} className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg">Cancel</button>
            </div>
          </div>
        </div>
      )}

      {showInvoiceModal && record && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg">
            <div className="p-4 border-b border-slate-100 flex items-center justify-between">
              <h3 className="font-semibold text-slate-800">Invoice Generated!</h3>
            </div>
            <div className="p-6 text-center">
              <div className="w-20 h-20 mx-auto mb-4 rounded-full bg-green-100 flex items-center justify-center">
                <CheckCircle className="w-10 h-10 text-green-600" />
              </div>
              <p className="text-lg font-semibold text-slate-800 mb-2">Payment Complete</p>
              <p className="text-slate-600 mb-4">Invoice INV-{record.id} is ready</p>

              <div className="bg-slate-50 p-4 rounded-lg text-left mb-4">
                <div className="flex justify-between mb-2">
                  <span className="text-sm text-slate-500">Maintenance ID</span>
                  <span className="text-sm font-medium">{record.id}</span>
                </div>
                <div className="flex justify-between mb-2">
                  <span className="text-sm text-slate-500">Bike</span>
                  <span className="text-sm font-medium">{record.bikePlate}</span>
                </div>
                <div className="flex justify-between mb-2">
                  <span className="text-sm text-slate-500">Amount Paid</span>
                  <span className="text-sm font-bold text-green-600">৳{record.actualCost || record.estimatedCost}</span>
                </div>
              </div>

              <div className="flex items-center justify-center mb-4">
                <div className="w-24 h-24 bg-white border-2 border-slate-200 rounded-lg flex items-center justify-center">
                  <QrCode className="w-16 h-16 text-slate-400" />
                </div>
              </div>
              <p className="text-xs text-slate-400">Scan QR for verification</p>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-between">
              <button
                onClick={() => setShowInvoiceModal(false)}
                className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg"
              >
                Close
              </button>
              <button
                onClick={handleGenerateInvoice}
                className="px-4 py-2 bg-purple-600 text-white rounded-lg flex items-center gap-2"
              >
                <Printer className="w-4 h-4" /> Download PDF
              </button>
            </div>
          </div>
        </div>
      )}

      {showAddNoteModal && (
        <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">
              <h3 className="font-semibold text-slate-800">Add Note</h3>
            </div>
            <div className="p-4">
              <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 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">Cancel</button>
              <button
                onClick={handleAddNote}
                disabled={!newNoteText.trim()}
                className="px-4 py-2 bg-accent text-white rounded-lg disabled:opacity-50"
              >
                Save Note
              </button>
            </div>
          </div>
        </div>
      )}

      {showAddPartModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg">
            <div className="p-4 border-b border-slate-100 flex justify-between items-center">
              <h3 className="font-semibold text-slate-800 flex items-center gap-2">
                <Package className="w-5 h-5 text-orange-600" /> Add Part
              </h3>
              <button onClick={() => setShowAddPartModal(false)} className="text-slate-400 hover:text-slate-600">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="text-sm font-medium text-slate-600 mb-1 block">Select Part from EV Parts</label>
                <p className="text-xs text-slate-400 mb-2">Prices are based on selling price from Settings</p>
                <div className="relative mb-3">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <input
                    type="text"
                    placeholder="Search parts..."
                    value={partSearch}
                    onChange={(e) => setPartSearch(e.target.value)}
                    className="w-full pl-10 pr-4 py-2 border border-slate-200 rounded-lg text-sm"
                  />
                </div>
                <div className="max-h-48 overflow-y-auto border border-slate-200 rounded-lg">
                  {mockParts.filter(p => p.name.toLowerCase().includes(partSearch.toLowerCase())).map(part => (
                    <div
                      key={part.id}
                      onClick={() => { setSelectedPart(part); setPartQuantity(1); }}
                      className={`p-3 border-b border-slate-100 cursor-pointer hover:bg-orange-50 ${selectedPart?.id === part.id ? 'bg-orange-50 border-orange-300' : ''}`}
                    >
                      <div className="flex justify-between items-center">
                        <div>
                          <p className="font-medium text-slate-700">{part.name}</p>
                          <p className="text-xs text-slate-500">{part.category}</p>
                        </div>
                        <div className="text-right">
                          <p className="font-bold text-orange-600">৳{part.sellingPrice.toLocaleString()}</p>
                          <p className="text-xs text-slate-400">per unit</p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {selectedPart && (
                <div className="bg-orange-50 p-4 rounded-lg border border-orange-200">
                  <div className="flex items-center gap-4">
                    <div className="flex-1">
                      <label className="text-xs font-medium text-slate-500 mb-1 block">Quantity</label>
                      <input
                        type="number"
                        min="1"
                        value={partQuantity}
                        onChange={(e) => setPartQuantity(Math.max(1, parseInt(e.target.value) || 1))}
                        className="w-full px-3 py-2 border border-orange-200 rounded-lg text-sm"
                      />
                    </div>
                    <div className="flex-1">
                      <label className="text-xs font-medium text-slate-500 mb-1 block">Unit Price</label>
                      <p className="text-lg font-bold text-orange-700">৳{selectedPart.sellingPrice}</p>
                    </div>
                    <div className="flex-1">
                      <label className="text-xs font-medium text-slate-500 mb-1 block">Total</label>
                      <p className="text-lg font-bold text-orange-700">৳{(selectedPart.sellingPrice * partQuantity).toLocaleString()}</p>
                    </div>
                  </div>
                </div>
              )}


            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2">
              <button onClick={() => setShowAddPartModal(false)} className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg">Cancel</button>
              <button
                onClick={() => {
                  if (selectedPart) {
                    const newPart: PartUsed = {
                      id: 'PU-' + Date.now(),
                      partId: selectedPart.id,
                      partName: selectedPart.name,
                      quantity: partQuantity,
                      unitPrice: selectedPart.sellingPrice,
                      totalPrice: selectedPart.sellingPrice * partQuantity,
                      addedAt: new Date().toISOString().split('T')[0]
                    };
                    setRecord(prev => prev ? { ...prev, partsUsed: [...(prev.partsUsed || []), newPart] } : null);
                    setShowAddPartModal(false);
                    setSelectedPart(null);
                  }
                }}
                disabled={!selectedPart}
                className="px-4 py-2 bg-orange-600 text-white rounded-lg disabled:opacity-50 flex items-center gap-2"
              >
                <Plus className="w-4 h-4" /> Add Part
              </button>
            </div>
          </div>
        </div>
      )}

      {showPaymentSuccess && (
        <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-8 text-center">
              <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle className="w-12 h-12 text-green-600" />
              </div>
              <h3 className="text-2xl font-bold text-green-600 mb-2">Payment Successful!</h3>
              <p className="text-slate-600 mb-4">Maintenance has been completed</p>

              <div className="bg-slate-50 p-4 rounded-lg text-left mb-6">
                <div className="flex justify-between mb-2">
                  <span className="text-sm text-slate-500">Maintenance ID</span>
                  <span className="text-sm font-bold text-slate-700">{record?.id}</span>
                </div>
                <div className="flex justify-between mb-2">
                  <span className="text-sm text-slate-500">Bike</span>
                  <span className="text-sm font-medium text-slate-700">{record?.bikeModel}</span>
                </div>
                <div className="flex justify-between mb-2">
                  <span className="text-sm text-slate-500">Status</span>
                  <span className="text-sm font-bold text-green-600">Completed</span>
                </div>
                <div className="flex justify-between pt-2 border-t border-slate-200">
                  <span className="text-sm font-semibold text-slate-700">Total Paid</span>
                  <span className="text-lg font-bold text-green-600">৳{((record?.partsUsed?.reduce((s, p) => s + p.totalPrice, 0) || 0) + (record?.serviceCost || 0) + invoiceData.tips - invoiceData.discount).toLocaleString()}</span>
                </div>
              </div>

              <button
                onClick={() => { setShowPaymentSuccess(false); setInvoiceData({ tips: 0, discount: 0 }); }}
                className="px-6 py-3 bg-green-600 text-white rounded-lg font-semibold hover:bg-green-700"
              >
                Done
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}