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

export const FleetPendingRequests: React.FC = () => {
  const [, setSearchParams] = useSearchParams();
  const [requests, setRequests] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  
  // Filtering & Pagination states
  const [statusFilter, setStatusFilter] = useState<string>('PENDING');
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [isSearchFocused, setIsSearchFocused] = useState<boolean>(false);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [itemsPerPage, setItemsPerPage] = useState<number>(8);

  // Inline loading when clicking action buttons
  const [processingId, setProcessingId] = useState<string | null>(null);

  const fetchRequests = async (searchFilter?: string) => {
    setLoading(true);
    setError(null);
    try {
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) {
        setError('Session token expired. Please log in.');
        return;
      }
      const params: any = {};
      if (statusFilter) params.status = statusFilter;
      if (searchFilter) params.search = searchFilter;
      
      const res = await fleetApi.getRestockRequests(token, params);
      const data = res?.data?.data || res?.data || [];
      setRequests(Array.isArray(data) ? data : []);
      setCurrentPage(1);
    } catch (err: any) {
      console.error('Failed to fetch restock requests:', err);
      setError(err?.message || 'Failed to fetch restock requests.');
    } finally {
      setLoading(false);
    }
  };

  const isFirstMount = React.useRef(true);

  // Initial load
  useEffect(() => {
    fetchRequests();
  }, []);

  // Debounced search and status filter
  useEffect(() => {
    if (isFirstMount.current) {
      isFirstMount.current = false;
      return;
    }
    
    const timer = setTimeout(() => {
      fetchRequests(searchQuery.trim() || undefined);
    }, 400);
    
    return () => clearTimeout(timer);
  }, [searchQuery, statusFilter]);

  const handleUpdateStatus = async (requestId: string, nextStatus: 'APPROVED' | 'COMPLETED') => {
    if (!requestId) return;
    setProcessingId(requestId);
    try {
      const token = localStorage.getItem('teleems_token') || '';
      await fleetApi.updateRestockRequestStatus(requestId, nextStatus, token);
      alert(`Request has been successfully marked as ${nextStatus}!`);
      // Reload current tab requests
      fetchRequests();
    } catch (err: any) {
      console.error('Failed to update request status:', err);
      alert(err?.message || `Failed to mark request as ${nextStatus}. Please try again.`);
    } finally {
      setProcessingId(null);
    }
  };

  // The API now handles filtering by search and status
  const filteredRequests = requests;

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

  return (
    <div className="animate-in fade-in duration-500" style={{ fontFamily: "'Inter', sans-serif" }}>
      {/* Top action bar */}
      <div style={{ marginBottom: '24px', display: 'flex', gap: '12px', alignItems: 'center' }}>
        <button 
          onClick={() => setSearchParams({ tab: 'warehouse' })}
          style={{ 
            background: 'rgba(255,255,255,0.05)', 
            border: '1px solid rgba(255,255,255,0.1)', 
            color: '#94A3B8', 
            borderRadius: '12px', 
            width: '52px', 
            height: '42px',
            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 Warehouse Stock"
        >
          <ArrowLeft size={18} />
        </button>

        {/* Search filter input */}
        <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: '320px',
          position: 'relative'
        }}>
          <Search size={16} color={isSearchFocused ? "#06B6D4" : "#64748B"} />
          <input 
            type="text" 
            placeholder="Search request items or users..." 
            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>

        {/* Status filters */}
        <div style={{ display: 'flex', gap: '8px', marginLeft: 'auto' }}>
          {[
            { id: 'PENDING', label: 'Pending Approval', count: statusFilter === 'PENDING' ? filteredRequests.length : null },
            { id: 'APPROVED', label: 'Approved (Awaiting Handover)', count: statusFilter === 'APPROVED' ? filteredRequests.length : null }
          ].map(tab => (
            <button
              key={tab.id}
              onClick={() => {
                setStatusFilter(tab.id);
                setSearchQuery('');
              }}
              style={{
                background: statusFilter === tab.id ? '#06B6D4' : '#FFFFFF',
                color: statusFilter === tab.id ? '#FFFFFF' : '#475569',
                border: statusFilter === tab.id ? '1px solid #06B6D4' : '1px solid #CBD5E1',
                borderRadius: '12px',
                padding: '10px 18px',
                fontSize: '0.8125rem',
                fontWeight: 700,
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                boxShadow: statusFilter === tab.id ? '0 4px 12px rgba(6, 182, 212, 0.2)' : '0 1px 2px rgba(15, 23, 42, 0.05)',
                transition: 'all 0.2s ease'
              }}
            >
              {tab.label}
              {tab.count !== null && (
                <span style={{
                  background: statusFilter === tab.id ? '#FFFFFF' : 'rgba(6, 182, 212, 0.1)',
                  color: statusFilter === tab.id ? '#06B6D4' : '#06B6D4',
                  padding: '2px 6px',
                  borderRadius: '6px',
                  fontSize: '0.7rem',
                  fontWeight: 800
                }}>
                  {tab.count}
                </span>
              )}
            </button>
          ))}
        </div>
      </div>

      <Card title={`${statusFilter.charAt(0) + statusFilter.slice(1).toLowerCase()} Restock Requests Ledger`}>
        {loading ? (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '100px', gap: '16px', color: '#64748B' }}>
            <Activity size={32} className="spin" style={{ color: '#06B6D4' }} />
            <span style={{ fontSize: '0.875rem', fontWeight: 600 }}>FETCHING TRANSACTION RECORDS...</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' }}>Synchronization Failed</h3>
            <p style={{ fontSize: '0.82rem', color: '#94A3B8', maxWidth: '360px', margin: '0 auto' }}>{error}</p>
          </div>
        ) : currentItems.length === 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '100px 24px', color: '#64748B' }}>
            <Package size={48} style={{ opacity: 0.2, marginBottom: '16px', color: '#06B6D4' }} />
            <h3 style={{ fontSize: '1rem', fontWeight: 700, color: '#475569', marginBottom: '4px' }}>No Supply Requests</h3>
            <p style={{ fontSize: '0.8125rem' }}>There are no restock requests matching this state filter right now.</p>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            <AnimatePresence>
              {currentItems.map((req) => {
                const requestedUser = typeof req.requested_by === 'object' && req.requested_by !== null
                  ? (req.requested_by.name || req.requested_by.username || 'Unknown User')
                  : (req.requested_by || 'N/A');

                return (
                  <motion.div
                    key={req.id}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, scale: 0.95 }}
                    transition={{ duration: 0.2 }}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      padding: '20px 24px',
                      borderRadius: '16px',
                      background: '#FFFFFF',
                      border: '1px solid #E2E8F0',
                      boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03)',
                      position: 'relative',
                      overflow: 'hidden'
                    }}
                    whileHover={{ 
                      y: -2, 
                      boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.08), 0 4px 6px -2px rgba(0, 0, 0, 0.04)',
                      borderColor: '#CBD5E1'
                    }}
                  >
                    {/* Subtle status indicator line on the left */}
                    <div style={{
                      position: 'absolute',
                      left: 0,
                      top: 0,
                      bottom: 0,
                      width: '4px',
                      background: statusFilter === 'PENDING' ? '#F59E0B' : statusFilter === 'APPROVED' ? '#3B82F6' : '#10B981'
                    }} />

                    <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flex: '2', minWidth: '250px' }}>
                      <div style={{
                        width: '48px',
                        height: '48px',
                        borderRadius: '12px',
                        background: 'rgba(6, 182, 212, 0.08)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: '#06B6D4'
                      }}>
                        <Package size={24} />
                      </div>
                      <div>
                        <div style={{ fontWeight: 700, fontSize: '1.05rem', color: '#0F172A', marginBottom: '4px' }}>
                          {req.items && req.items.length > 0 ? req.items[0].name : 'Unknown Item'}
                        </div>
                        <div style={{ fontSize: '0.75rem', color: '#64748B', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                          {req.vehicle?.registration_number || 'Medical Supply'}
                        </div>
                      </div>
                    </div>

                    <div style={{ flex: '1', minWidth: '120px' }}>
                      <div style={{ fontSize: '0.7rem', color: '#94A3B8', textTransform: 'uppercase', fontWeight: 700, marginBottom: '6px', letterSpacing: '0.5px' }}>Quantity</div>
                      <div style={{ fontWeight: 900, fontSize: '1.25rem', color: '#06B6D4', display: 'flex', alignItems: 'baseline', gap: '4px' }}>
                        {req.items && req.items.length > 0 ? req.items[0].quantityRequested : 0} <span style={{ fontSize: '0.8rem', color: '#64748B', fontWeight: 600 }}>Units</span>
                      </div>
                    </div>

                    <div style={{ flex: '1.5', minWidth: '180px' }}>
                      <div style={{ fontSize: '0.7rem', color: '#94A3B8', textTransform: 'uppercase', fontWeight: 700, marginBottom: '6px', letterSpacing: '0.5px' }}>Requested By</div>
                      <div style={{ fontWeight: 600, fontSize: '0.9rem', color: '#334155', display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <div style={{ 
                          width: '26px', 
                          height: '26px', 
                          borderRadius: '50%', 
                          background: '#F1F5F9', 
                          display: 'flex', 
                          alignItems: 'center', 
                          justifyContent: 'center', 
                          fontSize: '0.7rem', 
                          color: '#475569', 
                          fontWeight: 800,
                          border: '1px solid #E2E8F0'
                        }}>
                          {requestedUser.charAt(0).toUpperCase()}
                        </div>
                        {requestedUser}
                      </div>
                      <div style={{ fontSize: '0.75rem', color: '#94A3B8', marginTop: '6px', display: 'flex', alignItems: 'center', gap: '4px' }}>
                        <Clock size={12} />
                        {new Date(req.createdAt || req.updatedAt).toLocaleDateString()}
                      </div>
                    </div>

                    <div style={{ flex: '1', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '16px', minWidth: '140px' }}>
                      <span style={{
                        fontSize: '0.7rem',
                        fontWeight: 800,
                        textTransform: 'uppercase',
                        color: statusFilter === 'PENDING' ? '#D97706' : statusFilter === 'APPROVED' ? '#1D4ED8' : '#15803D',
                        background: statusFilter === 'PENDING' ? '#FEF3C7' : statusFilter === 'APPROVED' ? '#DBEAFE' : '#DCFCE7',
                        padding: '6px 12px',
                        borderRadius: '20px',
                        letterSpacing: '0.5px'
                      }}>
                        {req.status}
                      </span>

                      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                        {statusFilter === 'PENDING' && (
                          <motion.button
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                            disabled={processingId !== null}
                            onClick={() => handleUpdateStatus(req.id, 'APPROVED')}
                            style={{
                              background: 'linear-gradient(135deg, #10B981 0%, #059669 100%)',
                              border: 'none',
                              color: '#FFFFFF',
                              borderRadius: '10px',
                              padding: '8px 18px',
                              fontSize: '0.8rem',
                              fontWeight: 700,
                              cursor: processingId !== null ? 'not-allowed' : 'pointer',
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: '6px',
                              opacity: processingId !== null ? 0.7 : 1,
                              boxShadow: '0 4px 12px rgba(16, 185, 129, 0.25)'
                            }}
                          >
                            {processingId === req.id ? (
                              <Activity size={14} className="spin" />
                            ) : (
                              <Check size={14} strokeWidth={3} />
                            )}
                            APPROVE
                          </motion.button>
                        )}
                        {statusFilter === 'APPROVED' && (
                          <motion.button
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                            disabled={processingId !== null}
                            onClick={() => handleUpdateStatus(req.id, 'COMPLETED')}
                            style={{
                              background: 'linear-gradient(135deg, #3B82F6 0%, #2563EB 100%)',
                              border: 'none',
                              color: '#FFFFFF',
                              borderRadius: '10px',
                              padding: '8px 18px',
                              fontSize: '0.8rem',
                              fontWeight: 700,
                              cursor: processingId !== null ? 'not-allowed' : 'pointer',
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: '6px',
                              opacity: processingId !== null ? 0.7 : 1,
                              boxShadow: '0 4px 12px rgba(59, 130, 246, 0.25)'
                            }}
                          >
                            {processingId === req.id ? (
                              <Activity size={14} className="spin" />
                            ) : (
                              <Truck size={14} />
                            )}
                            HAND OVER
                          </motion.button>
                        )}
                        {statusFilter === 'COMPLETED' && (
                          <div style={{ display: 'inline-flex', alignItems: 'center', gap: '6px', color: '#10B981', fontSize: '0.8rem', fontWeight: 800 }}>
                            <CheckCircle size={16} /> COMPLETED
                          </div>
                        )}
                      </div>
                    </div>
                  </motion.div>
                );
              })}
            </AnimatePresence>
          </div>
        )}

        {!loading && !error && (
          <Pagination
            currentPage={currentPage}
            totalItems={filteredRequests.length}
            itemsPerPage={itemsPerPage}
            onPageChange={setCurrentPage}
            onItemsPerPageChange={setItemsPerPage}
            itemsLabel="transactions"
          />
        )}
      </Card>
    </div>
  );
};
