import React, { useEffect, useState } from 'react';
import { Database, Search, Activity, AlertTriangle, ArrowLeft, X, ShoppingCart, Truck, PlusCircle, Package, ClipboardList } from 'lucide-react';
import { useSearchParams } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { fleetApi } from '../../api/fleet';
import { Card } from '../../components/Common';
import { Pagination } from '../../components/Pagination';

export const FleetWarehouseStock: React.FC = () => {
  const [, setSearchParams] = useSearchParams();
  const [stockList, setStockList] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterCategory, setFilterCategory] = useState('');
  const [isSearchFocused, setIsSearchFocused] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  // Master Inventory for dropdowns
  const [inventory, setInventory] = useState<any[]>([]);

  // Bulk Restock states
  interface BulkRestockRow {
    itemId: string;
    quantity: number;
    reason: string;
  }
  const [showBulkRestockModal, setShowBulkRestockModal] = useState<boolean>(false);
  const [bulkRestockRows, setBulkRestockRows] = useState<BulkRestockRow[]>([
    { itemId: '', quantity: 100, reason: 'Shipment from HealthCare Distributors' }
  ]);
  const [bulkRestockIsSubmitting, setBulkRestockIsSubmitting] = useState<boolean>(false);
  const [bulkRestockError, setBulkRestockError] = useState<string | null>(null);

  // Assign to Vehicle states
  interface AssignVehicleRow {
    itemId: string;
    quantity: number;
    batch_number: string;
    expiry_date: string;
  }
  const [showAssignVehicleModal, setShowAssignVehicleModal] = useState<boolean>(false);
  const [assignVehicleId, setAssignVehicleId] = useState<string>('');
  const [assignSupplierName, setAssignSupplierName] = useState<string>('Central Warehouse');
  const [assignReason, setAssignReason] = useState<string>('Ambulance Initial Stocking');
  const [assignVehicleRows, setAssignVehicleRows] = useState<AssignVehicleRow[]>([
    { itemId: '', quantity: 100, batch_number: '', expiry_date: '' }
  ]);
  const [assignVehicleIsSubmitting, setAssignVehicleIsSubmitting] = useState<boolean>(false);
  const [assignVehicleError, setAssignVehicleError] = useState<string | null>(null);
  const [vehiclesList, setVehiclesList] = useState<any[]>([]);

  // Pending restock requests states
  const [pendingRequests, setPendingRequests] = useState<any[]>([]);
  const [loadingRequests, setLoadingRequests] = useState<boolean>(true);

  const fetchRequests = async () => {
    try {
      setLoadingRequests(true);
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) return;
      const res = await fleetApi.getPendingRestockRequests(token);
      const data = res?.data?.data || res?.data || [];
      setPendingRequests(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error('Failed to fetch pending requests:', err);
    } finally {
      setLoadingRequests(false);
    }
  };

  const fetchStock = async (nameFilter?: string, catFilter?: string) => {
    setLoading(true);
    setError(null);
    try {
      const token = localStorage.getItem('teleems_token') || '';
      const response = await fleetApi.searchWarehouseStock(token, { name: nameFilter, category: catFilter });
      const data = response?.data?.data?.data || response?.data?.data || response?.data || [];
      setStockList(Array.isArray(data) ? data : []);
    } catch (err: any) {
      console.error('Failed to fetch warehouse stock:', err);
      setError(err?.message || 'Failed to fetch warehouse stock data.');
    } finally {
      setLoading(false);
    }
  };

  const isFirstMount = React.useRef(true);

  useEffect(() => {
    fetchStock();
    fetchRequests();
  }, []);

  // Debounced search for name and category
  useEffect(() => {
    if (isFirstMount.current) {
      isFirstMount.current = false;
      return;
    }
    
    const timer = setTimeout(() => {
      fetchStock(searchQuery.trim() || undefined, filterCategory || undefined);
      setCurrentPage(1);
    }, 400);
    return () => clearTimeout(timer);
  }, [searchQuery, filterCategory]);

  useEffect(() => {
    const fetchInventory = async () => {
      try {
        const token = localStorage.getItem('teleems_token') || '';
        const response = await fleetApi.getInventoryMaster(token);
        const data = response?.data?.data || response?.data || [];
        setInventory(Array.isArray(data) ? data : []);
      } catch (err) {
        console.error('Failed to fetch inventory master:', err);
      }
    };
    fetchInventory();
  }, []);

  useEffect(() => {
    const fetchVehicles = async () => {
      try {
        const token = localStorage.getItem('teleems_token') || '';
        const userStr = localStorage.getItem('teleems_user');
        let orgId = '';
        if (userStr) {
          const u = JSON.parse(userStr);
          orgId = u.organisationId || '';
        }
        const res = await fleetApi.getVehicles(token, orgId);
        const data = res?.data?.data || res?.data || [];
        setVehiclesList(Array.isArray(data) ? data : []);
      } catch (e) {
        console.error('Failed to fetch vehicles:', e);
      }
    };
    fetchVehicles();
  }, []);

  const handleSubmitBulkRestock = async (e: React.FormEvent) => {
    e.preventDefault();
    setBulkRestockError(null);
    setBulkRestockIsSubmitting(true);

    if (bulkRestockRows.length === 0) {
      setBulkRestockError('Please add at least one item to restock.');
      setBulkRestockIsSubmitting(false);
      return;
    }

    const invalidRow = bulkRestockRows.find(row => !row.itemId || row.quantity <= 0);
    if (invalidRow) {
      setBulkRestockError('Please ensure all rows have an item selected and a positive quantity.');
      setBulkRestockIsSubmitting(false);
      return;
    }

    try {
      const token = localStorage.getItem('teleems_token') || '';
      const payload = bulkRestockRows.map(row => ({
        itemId: row.itemId,
        quantity: Number(row.quantity),
        reason: row.reason || 'Bulk Shipment'
      }));

      await fleetApi.restockInventory(payload, token);
      alert(`Successfully processed bulk restock for ${bulkRestockRows.length} items!`);
      setShowBulkRestockModal(false);
      fetchStock();
      fetchRequests();
    } catch (err: any) {
      console.error('Failed bulk restock:', err);
      setBulkRestockError(err?.message || 'Failed to submit bulk restock. Check item compatibility or try again.');
    } finally {
      setBulkRestockIsSubmitting(false);
    }
  };

  const handleSubmitAssignVehicle = async (e: React.FormEvent) => {
    e.preventDefault();
    setAssignVehicleError(null);
    setAssignVehicleIsSubmitting(true);

    if (!assignVehicleId) {
      setAssignVehicleError('Please select a vehicle.');
      setAssignVehicleIsSubmitting(false);
      return;
    }

    if (assignVehicleRows.length === 0) {
      setAssignVehicleError('Please add at least one item to assign.');
      setAssignVehicleIsSubmitting(false);
      return;
    }

    const invalidRow = assignVehicleRows.find(row => !row.itemId || row.quantity <= 0);
    if (invalidRow) {
      setAssignVehicleError('Please ensure all rows have an item selected and a positive quantity.');
      setAssignVehicleIsSubmitting(false);
      return;
    }

    try {
      const token = localStorage.getItem('teleems_token') || '';
      const payload = {
        supplier_name: assignSupplierName,
        reason: assignReason,
        items: assignVehicleRows.map(row => ({
          itemId: row.itemId,
          quantity: Number(row.quantity),
          batch_number: row.batch_number || 'N/A',
          expiry_date: row.expiry_date || new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toISOString().split('T')[0]
        }))
      };

      await fleetApi.assignToVehicle(assignVehicleId, payload, token);
      alert(`Successfully assigned inventory to vehicle!`);
      setShowAssignVehicleModal(false);
      fetchStock();
      fetchRequests();
    } catch (err: any) {
      console.error('Failed to assign to vehicle:', err);
      setAssignVehicleError(err?.message || 'Failed to submit assignment. Check item details or try again.');
    } finally {
      setAssignVehicleIsSubmitting(false);
    }
  };

  const filteredStock = stockList;

  const totalPages = Math.ceil(filteredStock.length / itemsPerPage);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredStock.slice(indexOfFirstItem, indexOfLastItem);

  return (
    <div className="animate-in fade-in duration-500">
      <div style={{ marginBottom: '24px', display: 'flex', gap: '12px' }}>
        <button 
          onClick={() => setSearchParams({ tab: 'inventory' })}
          style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', color: '#94A3B8', borderRadius: '12px', width: '52px', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', transition: 'all 0.2s', flexShrink: 0 }}
          onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
          onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.05)'}
          title="Back to Inventory"
        >
          <ArrowLeft size={18} />
        </button>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: '10px',
          background: '#FFFFFF',
          padding: '10px 16px',
          borderRadius: '12px',
          border: isSearchFocused ? '1px solid #06B6D4' : '1px solid #CBD5E1',
          boxShadow: isSearchFocused ? '0 0 0 3px rgba(6, 182, 212, 0.15)' : '0 2px 4px rgba(15, 23, 42, 0.01)',
          transition: 'all 0.2s ease',
          width: '380px',
          position: 'relative'
        }}>
          <Search size={16} color={isSearchFocused ? "#06B6D4" : "#64748B"} style={{ transition: 'color 0.2s' }} />
          <input 
            type="text" 
            placeholder="Search warehouse stock by name or category..." 
            value={searchQuery} 
            onChange={e => setSearchQuery(e.target.value)}
            onFocus={() => setIsSearchFocused(true)}
            onBlur={() => setIsSearchFocused(false)}
            className="stations-search-input"
            style={{ 
              background: 'transparent', 
              border: 'none', 
              color: '#0F172A', 
              fontSize: '0.875rem', 
              outline: 'none', 
              width: '100%',
              paddingRight: searchQuery ? '24px' : '0'
            }} 
          />
          {searchQuery && (
            <button 
              onClick={() => setSearchQuery('')}
              style={{
                position: 'absolute',
                right: '12px',
                background: 'transparent',
                border: 'none',
                cursor: 'pointer',
                color: '#94A3B8',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '2px',
                borderRadius: '50%',
              }}
              onMouseEnter={e => e.currentTarget.style.color = '#475569'}
              onMouseLeave={e => e.currentTarget.style.color = '#94A3B8'}
            >
              <X size={14} />
            </button>
          )}
        </div>

        {/* Category Dropdown */}
        <select
          value={filterCategory}
          onChange={(e) => setFilterCategory(e.target.value)}
          style={{
            padding: '10px 16px',
            borderRadius: '12px',
            border: '1px solid #CBD5E1',
            background: '#FFFFFF',
            color: '#0F172A',
            fontSize: '0.875rem',
            outline: 'none',
            cursor: 'pointer'
          }}
        >
          <option value="">All Categories</option>
          {Array.from(new Set(inventory.map(item => item.category).filter(Boolean))).map(c => (
            <option key={c} value={c}>{c}</option>
          ))}
        </select>

        <button 
          onClick={() => {
            const initialItemId = inventory.length > 0 ? inventory[0].id : '';
            setBulkRestockRows([
              { itemId: initialItemId, quantity: 100, reason: 'Shipment from HealthCare Distributors' }
            ]);
            setBulkRestockError(null);
            setShowBulkRestockModal(true);
          }}
          className="btn-secondary" 
          style={{ 
            display: 'flex', 
            alignItems: 'center', 
            gap: '8px',
            background: 'rgba(59, 130, 246, 0.1)',
            border: '1px solid rgba(59, 130, 246, 0.3)',
            color: '#3B82F6',
            borderRadius: '12px',
            padding: '8px 16px',
            fontSize: '0.8125rem',
            fontWeight: 700,
            cursor: 'pointer',
            transition: 'all 0.2s',
            marginLeft: 'auto'
          }}
          onMouseEnter={e => {
            e.currentTarget.style.background = 'rgba(59, 130, 246, 0.2)';
          }}
          onMouseLeave={e => {
            e.currentTarget.style.background = 'rgba(59, 130, 246, 0.1)';
          }}
        >
          <ShoppingCart size={16} /> BULK RESTOCK
        </button>
        <button 
          onClick={() => {
            const initialItemId = inventory.length > 0 ? inventory[0].id : '';
            setAssignVehicleRows([
              { itemId: initialItemId, quantity: 100, batch_number: '', expiry_date: '' }
            ]);
            setAssignVehicleError(null);
            setShowAssignVehicleModal(true);
          }}
          className="btn-secondary" 
          style={{ 
            display: 'flex', 
            alignItems: 'center', 
            gap: '8px',
            background: 'rgba(245, 158, 11, 0.1)',
            border: '1px solid rgba(245, 158, 11, 0.3)',
            color: '#F59E0B',
            borderRadius: '12px',
            padding: '8px 16px',
            fontSize: '0.8125rem',
            fontWeight: 700,
            cursor: 'pointer',
            transition: 'all 0.2s'
          }}
          onMouseEnter={e => {
            e.currentTarget.style.background = 'rgba(245, 158, 11, 0.2)';
          }}
          onMouseLeave={e => {
            e.currentTarget.style.background = 'rgba(245, 158, 11, 0.1)';
          }}
        >
          <Truck size={16} /> ASSIGN TO VEHICLE
        </button>

        <button 
          onClick={() => setSearchParams({ tab: 'pending-requests' })}
          className="btn-secondary" 
          style={{ 
            display: 'flex', 
            alignItems: 'center', 
            gap: '8px',
            background: 'rgba(6, 182, 212, 0.1)',
            border: '1px solid rgba(6, 182, 212, 0.3)',
            color: '#06B6D4',
            borderRadius: '12px',
            padding: '8px 16px',
            fontSize: '0.8125rem',
            fontWeight: 700,
            cursor: 'pointer',
            transition: 'all 0.2s'
          }}
          onMouseEnter={e => {
            e.currentTarget.style.background = 'rgba(6, 182, 212, 0.2)';
          }}
          onMouseLeave={e => {
            e.currentTarget.style.background = 'rgba(6, 182, 212, 0.1)';
          }}
        >
          <ClipboardList size={16} /> STOCK REQUESTS
        </button>
      </div>


      <Card title="Warehouse Inventory Catalog">
        {loading ? (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '100px', gap: '16px', color: 'var(--text-secondary)' }}>
            <Activity size={32} className="spin" style={{ color: 'var(--accent-cyan)' }} />
            <span style={{ fontSize: '0.875rem', fontWeight: 600 }}>SYNCHRONIZING WAREHOUSE DATA...</span>
          </div>
        ) : error ? (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '80px 24px', textAlign: 'center', color: '#EF4444' }}>
            <AlertTriangle size={48} style={{ marginBottom: '16px', opacity: 0.8 }} />
            <h3 style={{ fontSize: '1.1rem', fontWeight: 700, marginBottom: '8px' }}>Warehouse Connection Failed</h3>
            <p style={{ fontSize: '0.82rem', color: '#94A3B8', maxWidth: '360px', margin: '0 auto' }}>{error}</p>
          </div>
        ) : filteredStock.length === 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '100px 24px', color: '#64748B' }}>
            <Database size={48} style={{ opacity: 0.2, marginBottom: '16px' }} />
            <h3 style={{ fontSize: '1rem', fontWeight: 700, color: '#94A3B8', marginBottom: '4px' }}>Warehouse is Empty</h3>
            <p style={{ fontSize: '0.8125rem' }}>No stock data found or search returned no results.</p>
          </div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ textAlign: 'left', opacity: 0.5, fontSize: '0.65rem', textTransform: 'uppercase', borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
                <th style={{ padding: '16px 12px' }}>Supply Item</th>
                <th style={{ padding: '16px 12px' }}>Category</th>
                <th style={{ padding: '16px 12px' }}>Quantity Available</th>
                <th style={{ padding: '16px 12px' }}>Reorder Point</th>
                <th style={{ padding: '16px 12px' }}>Last Updated</th>
              </tr>
            </thead>
            <tbody>
              {currentItems.map((item) => (
                <tr key={item.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)', transition: 'background 0.2s' }} className="hover-glow">
                  <td style={{ padding: '16px 12px' }}>
                    <div style={{ fontWeight: 700, fontSize: '0.875rem' }}>
                      {item.item_master?.name || 'Unknown Item'}
                    </div>
                  </td>
                  <td style={{ padding: '16px 12px' }}>
                    <span style={{ fontSize: '0.7rem', fontWeight: 700, color: '#06B6D4', background: 'rgba(6, 182, 212, 0.1)', padding: '4px 8px', borderRadius: '6px' }}>
                      {item.item_master?.category || 'GENERAL'}
                    </span>
                  </td>
                  <td style={{ padding: '16px 12px' }}>
                    <div style={{ fontWeight: 900, fontSize: '1.1rem', color: '#10B981' }}>
                      {item.quantity}
                      <span style={{ fontSize: '0.7rem', color: '#64748B', fontWeight: 500, marginLeft: '6px' }}>Units</span>
                    </div>
                  </td>
                  <td style={{ padding: '16px 12px' }}>
                    <div style={{ fontSize: '0.8rem', color: '#94A3B8', fontWeight: 600 }}>
                      {item.item_master?.min_stock_threshold || 0}
                    </div>
                  </td>
                  <td style={{ padding: '16px 12px' }}>
                    <div style={{ fontSize: '0.75rem', color: '#64748B' }}>
                      {new Date(item.updatedAt).toLocaleString()}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}

        {!loading && !error && filteredStock.length > 0 && (
          <Pagination
            currentPage={currentPage}
            totalItems={filteredStock.length}
            itemsPerPage={itemsPerPage}
            onPageChange={setCurrentPage}
            onItemsPerPageChange={setItemsPerPage}
            itemsLabel="items"
          />
        )}
      </Card>



      {/* Bulk Restock Modal */}
      {showBulkRestockModal && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'rgba(15, 23, 42, 0.4)',
          backdropFilter: 'blur(8px)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1500,
          animation: 'fadeIn 0.25s ease-out'
        }}>
          <motion.div 
            initial={{ opacity: 0, scale: 0.95, y: 10 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 10 }}
            transition={{ duration: 0.25, ease: 'easeOut' }}
            style={{
              width: '100%',
              maxWidth: '820px',
              background: '#FFFFFF',
              border: '1px solid #E2E8F0',
              borderRadius: '20px',
              padding: '30px',
              boxShadow: '0 20px 40px rgba(15, 23, 42, 0.15)',
              fontFamily: "'Inter', sans-serif",
              boxSizing: 'border-box',
              maxHeight: '90vh',
              display: 'flex',
              flexDirection: 'column'
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', borderBottom: '1px solid #F1F5F9', paddingBottom: '16px', flexShrink: 0 }}>
              <div>
                <h3 style={{ fontSize: '1.25rem', fontWeight: 900, color: '#0F172A', margin: 0, letterSpacing: '-0.5px' }}>Bulk Restock Intake Ledger</h3>
                <span style={{ fontSize: '0.75rem', color: '#0284C7', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '1px' }}>Warehouse bulk stock ingestion</span>
              </div>
              <button 
                onClick={() => setShowBulkRestockModal(false)}
                style={{ background: 'transparent', border: 'none', color: '#64748B', cursor: 'pointer', fontSize: '1.1rem' }}
                onMouseEnter={e => e.currentTarget.style.color = '#0F172A'}
                onMouseLeave={e => e.currentTarget.style.color = '#64748B'}
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleSubmitBulkRestock} style={{ display: 'flex', flexDirection: 'column', gap: '20px', overflow: 'hidden', flex: 1 }}>
              {bulkRestockError && (
                <div style={{ background: 'rgba(239, 68, 68, 0.1)', border: '1px solid rgba(239, 68, 68, 0.2)', color: '#EF4444', padding: '12px 16px', borderRadius: '10px', fontSize: '0.8rem', display: 'flex', alignItems: 'center', gap: '8px', flexShrink: 0 }}>
                  <AlertTriangle size={16} />
                  <span>{bulkRestockError}</span>
                </div>
              )}

              {/* Rows List Container */}
              <div style={{ overflowY: 'auto', paddingRight: '4px', display: 'flex', flexDirection: 'column', gap: '12px', flex: 1, minHeight: '150px' }}>
                {bulkRestockRows.map((row, index) => {
                  const matchedItem = inventory.find(item => item.id === row.itemId);
                  return (
                    <div 
                      key={index} 
                      style={{ 
                        display: 'grid', 
                        gridTemplateColumns: '1.5fr 1fr 1.5fr auto', 
                        gap: '12px', 
                        alignItems: 'center',
                        background: '#F8FAFC',
                        border: '1px solid #E2E8F0',
                        borderRadius: '12px',
                        padding: '14px'
                      }}
                    >
                      {/* Item Select */}
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                        <label style={{ fontSize: '0.65rem', fontWeight: 800, color: '#64748B', textTransform: 'uppercase' }}>Select Supply Item</label>
                        <select 
                          value={row.itemId}
                          onChange={(e) => {
                            const newRows = [...bulkRestockRows];
                            newRows[index].itemId = e.target.value;
                            setBulkRestockRows(newRows);
                          }}
                          style={{
                            background: '#FFFFFF',
                            border: '1px solid #D1D5DB',
                            borderRadius: '8px',
                            padding: '8px 12px',
                            color: '#0F172A',
                            fontSize: '0.8rem',
                            outline: 'none',
                            cursor: 'pointer'
                          }}
                        >
                          <option value="">-- Choose Item --</option>
                          {inventory.map(item => (
                            <option key={item.id} value={item.id}>
                              {item.name} ({item.category})
                            </option>
                          ))}
                        </select>
                      </div>

                      {/* Quantity Input */}
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                        <label style={{ fontSize: '0.65rem', fontWeight: 800, color: '#64748B', textTransform: 'uppercase' }}>
                          Quantity {matchedItem ? `(${matchedItem.unit_of_measure || matchedItem.unit || 'Units'})` : ''}
                        </label>
                        <input 
                          type="number" 
                          min="1"
                          value={row.quantity}
                          onChange={(e) => {
                            const newRows = [...bulkRestockRows];
                            newRows[index].quantity = Number(e.target.value);
                            setBulkRestockRows(newRows);
                          }}
                          style={{
                            background: '#FFFFFF',
                            border: '1px solid #D1D5DB',
                            borderRadius: '8px',
                            padding: '8px 12px',
                            color: '#0F172A',
                            fontSize: '0.8rem',
                            outline: 'none',
                            fontWeight: 700
                          }}
                        />
                      </div>

                      {/* Reason Select/Input */}
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                        <label style={{ fontSize: '0.65rem', fontWeight: 800, color: '#64748B', textTransform: 'uppercase' }}>Reason / Supplier</label>
                        <select 
                          value={row.reason}
                          onChange={(e) => {
                            const newRows = [...bulkRestockRows];
                            newRows[index].reason = e.target.value;
                            setBulkRestockRows(newRows);
                          }}
                          style={{
                            background: '#FFFFFF',
                            border: '1px solid #D1D5DB',
                            borderRadius: '8px',
                            padding: '8px 12px',
                            color: '#0F172A',
                            fontSize: '0.8rem',
                            outline: 'none',
                            cursor: 'pointer'
                          }}
                        >
                          <option value="Shipment from HealthCare Distributors">Shipment from HealthCare Distributors</option>
                          <option value="Shipment from MediStore">Shipment from MediStore</option>
                          <option value="Routine Stock Replenishment">Routine Stock Replenishment</option>
                          <option value="Emergency Intake">Emergency Intake</option>
                        </select>
                      </div>

                      {/* Remove Action */}
                      <button 
                        type="button"
                        onClick={() => {
                          const newRows = bulkRestockRows.filter((_, rIdx) => rIdx !== index);
                          setBulkRestockRows(newRows);
                        }}
                        style={{
                          background: 'rgba(239, 68, 68, 0.1)',
                          border: 'none',
                          color: '#EF4444',
                          padding: '8px',
                          borderRadius: '8px',
                          cursor: 'pointer',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          alignSelf: 'end',
                          marginBottom: '2px',
                          transition: 'all 0.2s'
                        }}
                        onMouseEnter={e => e.currentTarget.style.background = 'rgba(239, 68, 68, 0.2)'}
                        onMouseLeave={e => e.currentTarget.style.background = 'rgba(239, 68, 68, 0.1)'}
                        title="Remove row"
                      >
                        <X size={16} />
                      </button>
                    </div>
                  );
                })}

                {/* Add Row Button */}
                <button 
                  type="button"
                  onClick={() => {
                    const firstId = inventory.length > 0 ? inventory[0].id : '';
                    setBulkRestockRows([
                      ...bulkRestockRows,
                      { itemId: firstId, quantity: 100, reason: 'Shipment from HealthCare Distributors' }
                    ]);
                  }}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '8px',
                    background: 'rgba(2, 132, 199, 0.05)',
                    border: '1px dashed rgba(2, 132, 199, 0.3)',
                    color: '#0284C7',
                    borderRadius: '12px',
                    padding: '12px',
                    fontSize: '0.8rem',
                    fontWeight: 700,
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                  onMouseEnter={e => {
                    e.currentTarget.style.background = 'rgba(2, 132, 199, 0.1)';
                  }}
                  onMouseLeave={e => {
                    e.currentTarget.style.background = 'rgba(2, 132, 199, 0.05)';
                  }}
                >
                  <PlusCircle size={16} /> ADD ANOTHER ITEM ROW
                </button>
              </div>

              {/* Bottom Buttons */}
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px', borderTop: '1px solid #F1F5F9', paddingTop: '20px', flexShrink: 0 }}>
                <button 
                  type="button" 
                  onClick={() => setShowBulkRestockModal(false)}
                  className="btn-ghost"
                  style={{ padding: '10px 20px', fontSize: '0.8rem', color: '#475569', background: 'transparent', border: 'none', cursor: 'pointer', fontWeight: 600 }}
                >
                  CANCEL
                </button>
                <button 
                  type="submit" 
                  className="btn-primary"
                  disabled={bulkRestockIsSubmitting}
                  style={{ padding: '10px 24px', fontSize: '0.8rem', display: 'flex', alignItems: 'center', gap: '8px', background: '#22C55E', color: '#FFFFFF', border: 'none', borderRadius: '8px', fontWeight: 700, cursor: 'pointer' }}
                >
                  {bulkRestockIsSubmitting ? (
                    <>
                      <Activity size={14} className="spin" /> PROCESSING...
                    </>
                  ) : (
                    'SUBMIT BULK INGESTION'
                  )}
                </button>
              </div>
            </form>
          </motion.div>
        </div>
      )}

      {/* Assign to Vehicle Modal */}
      {showAssignVehicleModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(15, 23, 42, 0.4)', zIndex: 10000, display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }} onClick={(e) => { if (e.target === e.currentTarget) setShowAssignVehicleModal(false); }}>
          <motion.div initial={{ scale: 0.95, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} style={{ background: '#FFFFFF', borderRadius: '16px', width: '900px', maxWidth: '95vw', maxHeight: '90vh', overflow: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: '0 20px 40px rgba(15, 23, 42, 0.2)' }}>
            
            {/* Header */}
            <div style={{ padding: '20px 24px', borderBottom: '1px solid #F1F5F9', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: '#F8FAFC' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                <div style={{ background: 'rgba(245, 158, 11, 0.1)', padding: '10px', borderRadius: '12px', color: '#F59E0B' }}>
                  <Truck size={20} />
                </div>
                <div>
                  <h2 style={{ margin: 0, fontSize: '1.1rem', fontWeight: 800, color: '#0F172A' }}>Assign to Vehicle</h2>
                  <p style={{ margin: '4px 0 0', fontSize: '0.8rem', color: '#64748B' }}>Transfer inventory stock to an active fleet vehicle</p>
                </div>
              </div>
              <button onClick={() => setShowAssignVehicleModal(false)} style={{ background: '#FFFFFF', border: '1px solid #E2E8F0', padding: '6px', borderRadius: '8px', cursor: 'pointer', color: '#64748B' }}>
                <X size={16} />
              </button>
            </div>

            {/* Form */}
            <form onSubmit={handleSubmitAssignVehicle} style={{ flex: 1, overflowY: 'auto', padding: '24px', display: 'flex', flexDirection: 'column', gap: '24px' }}>
              {assignVehicleError && (
                <div style={{ padding: '12px 16px', background: 'rgba(239, 68, 68, 0.1)', border: '1px solid rgba(239, 68, 68, 0.2)', borderRadius: '8px', color: '#EF4444', fontSize: '0.85rem', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <AlertTriangle size={16} /> {assignVehicleError}
                </div>
              )}

              {/* Top Configuration Details */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px', background: '#F8FAFC', padding: '16px', borderRadius: '12px', border: '1px solid #E2E8F0' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '6px' }}>Select Target Vehicle *</label>
                  <select 
                    required
                    value={assignVehicleId}
                    onChange={(e) => setAssignVehicleId(e.target.value)}
                    style={{ width: '100%', background: '#FFFFFF', border: '1px solid #D1D5DB', borderRadius: '8px', padding: '8px 12px', color: '#0F172A', fontSize: '0.8rem', outline: 'none' }}
                  >
                    <option value="" disabled>-- Select Vehicle --</option>
                    {vehiclesList.map(v => (
                      <option key={v.id} value={v.id}>{v.registration_number} {v.brand ? `(${v.brand})` : ''}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '6px' }}>Supplier / Source</label>
                  <input 
                    type="text"
                    required
                    value={assignSupplierName}
                    onChange={(e) => setAssignSupplierName(e.target.value)}
                    style={{ width: '100%', background: '#FFFFFF', border: '1px solid #D1D5DB', borderRadius: '8px', padding: '8px 12px', color: '#0F172A', fontSize: '0.8rem', outline: 'none' }}
                  />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '6px' }}>Assignment Reason</label>
                  <select 
                    value={assignReason}
                    onChange={(e) => setAssignReason(e.target.value)}
                    style={{ width: '100%', background: '#FFFFFF', border: '1px solid #D1D5DB', borderRadius: '8px', padding: '8px 12px', color: '#0F172A', fontSize: '0.8rem', outline: 'none' }}
                  >
                    <option value="Ambulance Initial Stocking">Ambulance Initial Stocking</option>
                    <option value="Routine Restock">Routine Restock</option>
                    <option value="Emergency Restock">Emergency Restock</option>
                  </select>
                </div>
              </div>

              {/* Rows */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                <h3 style={{ margin: 0, fontSize: '0.9rem', fontWeight: 700, color: '#0F172A', borderBottom: '1px solid #E2E8F0', paddingBottom: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <Package size={16} color="#0284C7" /> Items to Assign
                </h3>
                
                {assignVehicleRows.map((row, index) => (
                  <div key={index} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr auto', gap: '12px', alignItems: 'center', background: '#FFFFFF', padding: '12px', borderRadius: '12px', border: '1px solid #E2E8F0' }}>
                    <div>
                      <label style={{ display: 'block', fontSize: '0.65rem', fontWeight: 700, color: '#64748B', marginBottom: '4px', textTransform: 'uppercase' }}>Select Item</label>
                      <select 
                        required
                        value={row.itemId}
                        onChange={(e) => {
                          const newRows = [...assignVehicleRows];
                          newRows[index].itemId = e.target.value;
                          setAssignVehicleRows(newRows);
                        }}
                        style={{ width: '100%', background: '#F8FAFC', border: '1px solid #D1D5DB', borderRadius: '6px', padding: '8px', color: '#0F172A', fontSize: '0.8rem', outline: 'none' }}
                      >
                        <option value="" disabled>-- Select item --</option>
                        {inventory.map(invItem => (
                          <option key={invItem.id} value={invItem.id}>{invItem.name} ({invItem.unit_of_measure || invItem.unit || 'Units'})</option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label style={{ display: 'block', fontSize: '0.65rem', fontWeight: 700, color: '#64748B', marginBottom: '4px', textTransform: 'uppercase' }}>Quantity</label>
                      <input 
                        type="number"
                        min="1"
                        required
                        value={row.quantity}
                        onChange={(e) => {
                          const newRows = [...assignVehicleRows];
                          newRows[index].quantity = Number(e.target.value);
                          setAssignVehicleRows(newRows);
                        }}
                        style={{ width: '100%', background: '#F8FAFC', border: '1px solid #D1D5DB', borderRadius: '6px', padding: '8px', color: '#0F172A', fontSize: '0.8rem', outline: 'none' }}
                      />
                    </div>
                    <div>
                      <label style={{ display: 'block', fontSize: '0.65rem', fontWeight: 700, color: '#64748B', marginBottom: '4px', textTransform: 'uppercase' }}>Batch No</label>
                      <input 
                        type="text"
                        placeholder="e.g. B-2024"
                        value={row.batch_number}
                        onChange={(e) => {
                          const newRows = [...assignVehicleRows];
                          newRows[index].batch_number = e.target.value;
                          setAssignVehicleRows(newRows);
                        }}
                        style={{ width: '100%', background: '#F8FAFC', border: '1px solid #D1D5DB', borderRadius: '6px', padding: '8px', color: '#0F172A', fontSize: '0.8rem', outline: 'none' }}
                      />
                    </div>
                    <div>
                      <label style={{ display: 'block', fontSize: '0.65rem', fontWeight: 700, color: '#64748B', marginBottom: '4px', textTransform: 'uppercase' }}>Expiry Date</label>
                      <input 
                        type="date"
                        required
                        value={row.expiry_date}
                        onChange={(e) => {
                          const newRows = [...assignVehicleRows];
                          newRows[index].expiry_date = e.target.value;
                          setAssignVehicleRows(newRows);
                        }}
                        style={{ width: '100%', background: '#F8FAFC', border: '1px solid #D1D5DB', borderRadius: '6px', padding: '8px', color: '#0F172A', fontSize: '0.8rem', outline: 'none' }}
                      />
                    </div>
                    <button 
                      type="button"
                      onClick={() => setAssignVehicleRows(assignVehicleRows.filter((_, rIdx) => rIdx !== index))}
                      style={{ background: 'rgba(239, 68, 68, 0.1)', border: 'none', color: '#EF4444', padding: '8px', borderRadius: '8px', cursor: 'pointer', alignSelf: 'end', marginBottom: '2px' }}
                    >
                      <X size={16} />
                    </button>
                  </div>
                ))}

                <button 
                  type="button"
                  onClick={() => {
                    const firstId = inventory.length > 0 ? inventory[0].id : '';
                    setAssignVehicleRows([...assignVehicleRows, { itemId: firstId, quantity: 100, batch_number: '', expiry_date: '' }]);
                  }}
                  style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', background: 'rgba(245, 158, 11, 0.05)', border: '1px dashed rgba(245, 158, 11, 0.3)', color: '#F59E0B', borderRadius: '12px', padding: '12px', fontSize: '0.8rem', fontWeight: 700, cursor: 'pointer' }}
                >
                  <PlusCircle size={16} /> ADD ANOTHER ITEM
                </button>
              </div>

              {/* Bottom Buttons */}
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px', borderTop: '1px solid #F1F5F9', paddingTop: '20px', flexShrink: 0 }}>
                <button 
                  type="button" 
                  onClick={() => setShowAssignVehicleModal(false)}
                  style={{ padding: '10px 20px', fontSize: '0.8rem', color: '#475569', background: 'transparent', border: 'none', cursor: 'pointer', fontWeight: 600 }}
                >
                  CANCEL
                </button>
                <button 
                  type="submit" 
                  disabled={assignVehicleIsSubmitting}
                  style={{ padding: '10px 24px', fontSize: '0.8rem', display: 'flex', alignItems: 'center', gap: '8px', background: '#F59E0B', color: '#FFFFFF', border: 'none', borderRadius: '8px', fontWeight: 700, cursor: 'pointer' }}
                >
                  {assignVehicleIsSubmitting ? <><Activity size={14} className="spin" /> PROCESSING...</> : 'CONFIRM ASSIGNMENT'}
                </button>
              </div>
            </form>
          </motion.div>
        </div>
      )}

      <style>{`
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        .spin { animation: spin 1s linear infinite; }
        .hover-glow:hover { background: rgba(255,255,255,0.02); }
      `}</style>
    </div>
  );
};
