import React, { useState, useEffect, useCallback } from 'react';
import { Clock, CheckCircle, Car, User, Activity, Loader2, Calendar, ChevronLeft } from 'lucide-react';
import { motion } from 'framer-motion';
import { useNavigate } from 'react-router-dom';

interface ActiveShift {
  id: string;
  vehicleId: string;
  vehicle?: {
    registration_number?: string;
    vehicle_type?: string;
  };
  driverId: string;
  driver?: {
    userId?: string;
    type?: string;
    user?: { name?: string };
  };
  staffId: string;
  staff?: {
    userId?: string;
    type?: string;
    user?: { name?: string };
  };
  startTime: string;
  endTime: string | null;
  status: string;
  notes?: string | null;
}

export const FleetActiveShifts: React.FC = () => {
  const navigate = useNavigate();
  const [shifts, setShifts] = useState<ActiveShift[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const fetchActiveShifts = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const token = localStorage.getItem('teleems_token') || '';
      const res = await fetch('https://teleems-api-gateway.onrender.com/v1/fleet/shifts/active', {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.message || 'Failed to fetch active shifts');
      
      const data = json?.data?.data || json?.data || [];
      setShifts(Array.isArray(data) ? data : []);
    } catch (err: any) {
      console.error('Error fetching active shifts:', err);
      setError(err.message || 'An error occurred while fetching shifts.');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchActiveShifts();
  }, [fetchActiveShifts]);

  return (
    <div className="animate-in fade-in duration-500" style={{ color: '#0F172A', fontFamily: 'Inter, sans-serif' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <button 
          onClick={() => navigate(-1)}
          style={{ 
            display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', 
            background: '#FFFFFF', border: '1px solid #E2E8F0', 
            borderRadius: '12px', color: '#475569', fontSize: '0.8rem', fontWeight: 700, cursor: 'pointer',
            boxShadow: '0 1px 2px rgba(15, 23, 42, 0.05)', transition: 'all 0.2s'
          }}
          onMouseEnter={e => e.currentTarget.style.background = '#F8FAFC'}
          onMouseLeave={e => e.currentTarget.style.background = '#FFFFFF'}
        >
          <ChevronLeft size={16} /> Back to Dashboard
        </button>
        <button 
          onClick={fetchActiveShifts}
          style={{ 
            display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', 
            background: '#FFFFFF', border: '1px solid #E2E8F0', 
            borderRadius: '12px', color: '#06B6D4', fontSize: '0.8rem', fontWeight: 700, cursor: 'pointer',
            boxShadow: '0 1px 2px rgba(15, 23, 42, 0.05)', transition: 'all 0.2s'
          }}
          onMouseEnter={e => e.currentTarget.style.background = '#F8FAFC'}
          onMouseLeave={e => e.currentTarget.style.background = '#FFFFFF'}
        >
          {loading ? <Loader2 size={14} className="spin" /> : '↺ Refresh Status'}
        </button>
      </div>

      {error && (
        <div style={{ background: '#FEF2F2', border: '1px solid #FCA5A5', padding: '16px 20px', borderRadius: '12px', color: '#EF4444', fontSize: '0.85rem', fontWeight: 600, marginBottom: 24, display: 'flex', alignItems: 'center', gap: '8px' }}>
          <Activity size={16} /> {error}
        </div>
      )}

      {loading ? (
        <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', minHeight: 300, gap: '16px' }}>
          <Loader2 size={36} color="#06B6D4" className="spin" />
          <span style={{ color: '#64748B', fontWeight: 600, fontSize: '0.9rem' }}>Fetching active shift telemetries...</span>
        </div>
      ) : shifts.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '80px 24px', background: '#FFFFFF', border: '1px dashed #CBD5E1', borderRadius: '16px', boxShadow: '0 4px 6px -1px rgba(0,0,0,0.02)' }}>
          <CheckCircle size={48} color="#10B981" style={{ marginBottom: 16, opacity: 0.8 }} />
          <h3 style={{ fontSize: '1.1rem', fontWeight: 800, color: '#0F172A', margin: '0 0 8px' }}>All Clear</h3>
          <p style={{ color: '#64748B', fontSize: '0.9rem', margin: 0 }}>No active shifts at the moment. All shifts have been completed or none are currently scheduled.</p>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))', gap: '20px' }}>
          {shifts.map((shift, i) => (
            <motion.div 
              key={shift.id} 
              initial={{ opacity: 0, y: 15 }} 
              animate={{ opacity: 1, y: 0 }} 
              transition={{ delay: i * 0.05, duration: 0.3 }}
              style={{ 
                background: '#FFFFFF', 
                border: '1px solid #E2E8F0', 
                borderRadius: '20px', 
                padding: '24px',
                boxShadow: '0 4px 12px -2px rgba(15, 23, 42, 0.05)',
                display: 'flex',
                flexDirection: 'column',
                gap: '20px',
                position: 'relative',
                overflow: 'hidden'
              }}
              whileHover={{ y: -4, boxShadow: '0 12px 20px -4px rgba(15, 23, 42, 0.08)', borderColor: '#CBD5E1' }}
            >
              {/* Top Accent Line */}
              <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: '4px', background: 'linear-gradient(90deg, #06B6D4, #3B82F6)' }} />

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                  <div style={{ width: '48px', height: '48px', borderRadius: '14px', background: 'rgba(6, 182, 212, 0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Car size={24} color="#06B6D4" />
                  </div>
                  <div>
                    <div style={{ fontWeight: 800, fontSize: '1.1rem', color: '#0F172A', marginBottom: '2px' }}>
                      {shift.vehicle?.registration_number || 'Unknown Vehicle'}
                    </div>
                    <div style={{ fontSize: '0.75rem', fontWeight: 700, color: '#06B6D4', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                      {shift.vehicle?.vehicle_type || 'N/A Type'}
                    </div>
                  </div>
                </div>

                {/* Status Badge */}
                <div style={{ padding: '6px 12px', background: '#DCFCE7', border: '1px solid #BBF7D0', borderRadius: '20px', display: 'flex', alignItems: 'center', gap: '6px' }}>
                  <Clock size={14} color="#15803D" />
                  <span style={{ fontSize: '0.75rem', fontWeight: 800, color: '#15803D', letterSpacing: '0.5px' }}>{shift.status}</span>
                </div>
              </div>

              {/* Time details */}
              <div style={{ padding: '12px 16px', background: '#F8FAFC', borderRadius: '12px', border: '1px dashed #CBD5E1' }}>
                <div style={{ fontSize: '0.7rem', fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', marginBottom: '4px', letterSpacing: '0.5px' }}>Shift Started At</div>
                <div style={{ fontSize: '0.9rem', fontWeight: 700, color: '#334155', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <Calendar size={14} color="#64748B" /> {new Date(shift.startTime).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}
                </div>
              </div>

              {/* Crew Members */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                <div style={{ fontSize: '0.7rem', fontWeight: 800, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.5px', marginLeft: '4px' }}>Assigned Crew</div>
                
                {/* Driver */}
                <div style={{ display: 'flex', alignItems: 'center', gap: '14px', padding: '14px', background: '#FFFFFF', border: '1px solid #E2E8F0', borderRadius: '14px' }}>
                  <div style={{ width: '36px', height: '36px', borderRadius: '50%', background: '#F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <User size={18} color="#64748B" />
                  </div>
                  <div>
                    <div style={{ fontSize: '0.9rem', fontWeight: 700, color: '#0F172A' }}>
                      {shift.driver?.user?.name || 'Driver Profile'}
                    </div>
                    <div style={{ fontSize: '0.75rem', color: '#64748B', fontWeight: 600 }}>Pilot / Driver</div>
                  </div>
                </div>

                {/* Staff / EMT */}
                <div style={{ display: 'flex', alignItems: 'center', gap: '14px', padding: '14px', background: '#FFFFFF', border: '1px solid #E2E8F0', borderRadius: '14px' }}>
                  <div style={{ width: '36px', height: '36px', borderRadius: '50%', background: '#EFF6FF', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Activity size={18} color="#3B82F6" />
                  </div>
                  <div>
                    <div style={{ fontSize: '0.9rem', fontWeight: 700, color: '#0F172A' }}>
                      {shift.staff?.user?.name || 'EMT/Staff Profile'}
                    </div>
                    <div style={{ fontSize: '0.75rem', color: '#3B82F6', fontWeight: 600 }}>
                      {shift.staff?.type === 'DOCTOR' ? 'Medical Doctor' : 'Emergency Medical Tech'}
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>
          ))}
        </div>
      )}

      <style>{`@keyframes spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}} .spin{animation:spin 1s linear infinite}`}</style>
    </div>
  );
};
