import React, { useState, useEffect, useRef, Fragment } from 'react';
import {
  Avatar,
  AppBar,
  Backdrop,
  Box,
  Button,
  Checkbox,
  Divider,
  Drawer,
  IconButton,
  InputBase,
  List,
  ListItem,
  Paper,
  Skeleton,
  Stack,
  Toolbar,
  Typography,
  useMediaQuery,
  useTheme
} from '@mui/material';
import { useQuery } from '@tanstack/react-query';
import dayjs from 'dayjs';

import {
  MdMenu,
  MdSearch,
  MdClear,
  MdRefresh,
  MdLocalShipping,
  MdCheckCircle,
  MdHighlightOff,
  MdGroups,
  MdAccessTime,
  MdLocationOn,
  MdMyLocation
} from 'react-icons/md';

import RiderLocationMap from './RiderLocationMap';
import { fetchRidersLogs } from '../api/api';
import CircularLoader from 'components/nearle_components/CircularLoader';
import error500 from 'assets/images/maintenance/Error500.png';

// ============================================================================
// Design tokens — shared with the rest of the redesigned operator pages.
// ============================================================================
const DT = {
  radiusPill: 999,
  radiusCard: 16,
  shadowSoft: '0 14px 40px rgba(15, 23, 42, 0.10)',
  shadowMd: '0 8px 24px rgba(15, 23, 42, 0.08)',
  shadowPop: '0 18px 50px rgba(15, 23, 42, 0.18)',
  textPrimary: '#0f172a',
  textSecondary: '#64748b',
  textMuted: '#94a3b8',
  borderSubtle: '#e2e8f0',
  divider: '#f1f5f9',
  surface: '#ffffff',
  surfaceAlt: '#f8fafc'
};
const dtA = (c, suffix) => `${c}${suffix}`;
const tint = (c) => dtA(c, '08');
const soft = (c) => dtA(c, '18');
const ring = (c) => dtA(c, '26');
const edge = (c) => dtA(c, '55');

const BRAND = '#662582';
const BRAND_LIGHT = '#9255AB';
const C_ACTIVE = '#10b981';
const C_INACTIVE = '#ef4444';

const drawerWidth = 360;

// Soft pill used for status / count chips throughout the page.
const SoftPill = ({ color, icon, children, sx = {} }) => (
  <Box
    sx={{
      display: 'inline-flex',
      alignItems: 'center',
      gap: 0.5,
      px: 0.875,
      py: 0.25,
      borderRadius: 999,
      bgcolor: tint(color),
      border: `1px solid ${edge(color)}`,
      color,
      fontSize: 11,
      fontWeight: 800,
      whiteSpace: 'nowrap',
      ...sx
    }}
  >
    {icon}
    {children}
  </Box>
);

const RidersLogs = () => {
  const theme = useTheme();
  const isDesktop = useMediaQuery('(min-width:900px)');
  const [open, setOpen] = useState(false);
  const [selectedRiders, setSelectedRiders] = useState([]);
  const [riderSearch, setRiderSearch] = useState('');
  const searchRef = useRef(null);
  const appId = 1;

  const {
    data: riders,
    isLoading: ridersIsLoading,
    isFetching: riderIsFetching,
    refetch: riderLogsRefetch,
    error: riderLogsError
  } = useQuery({
    queryKey: [appId, dayjs().format('YYYY-MM-DD'), riderSearch],
    queryFn: fetchRidersLogs,
    refetchInterval: 5 * 60 * 1000
  });

  // Only active riders are surfaced on this page — inactive riders are filtered
  // out entirely before they reach the list, selection, counts, or map.
  const activeRiders = React.useMemo(
    () => (riders || []).filter((r) => r.status === 'active'),
    [riders]
  );

  useEffect(() => {
    setSelectedRiders(activeRiders);
  }, [activeRiders]);

  useEffect(() => {
    setOpen(isDesktop);
  }, [isDesktop]);

  // Ctrl/Cmd+K focuses the rider search.
  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();
        searchRef.current && searchRef.current.focus();
      }
      if (event.key === 'Escape' && document.activeElement === searchRef.current) {
        searchRef.current.blur();
      }
    };
    document.addEventListener('keydown', handleKeyPress);
    return () => document.removeEventListener('keydown', handleKeyPress);
  }, []);

  // Counts shown in the drawer header (active riders only).
  const totalRiders = activeRiders.length;
  const activeCount = totalRiders;
  const isAllSelected = totalRiders > 0 && selectedRiders?.length === totalRiders;

  return (
    <Fragment>
      <Backdrop
        sx={{
          color: '#fff',
          zIndex: (t) => t.zIndex.drawer + 1
        }}
        open={ridersIsLoading || riderIsFetching}
      >
        <CircularLoader color="inherit" />
      </Backdrop>

      <Paper
        elevation={0}
        sx={{
          borderRadius: DT.radiusCard / 8,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          overflow: 'hidden',
          background: '#fff'
        }}
      >
        <Box sx={{ display: 'flex', width: '100%', height: '100%', position: 'relative' }}>
          {/* ============================================= || Drawer || ============================================= */}
          <Drawer
            variant={isDesktop ? 'persistent' : 'temporary'}
            open={open}
            onClose={() => !isDesktop && setOpen(false)}
            ModalProps={{ keepMounted: true }}
            sx={{
              '& .MuiDrawer-paper': {
                width: drawerWidth,
                position: 'absolute',
                left: 0,
                top: 0,
                height: '100%',
                overflowY: 'auto',
                transition: 'transform 0.35s ease-in-out',
                zIndex: 13,
                borderRight: `1px solid ${DT.borderSubtle}`,
                backgroundColor: '#fff'
              }
            }}
          >
            {/* ===== Drawer header — gradient strip with title + count pills ===== */}
            <Box
              sx={{
                position: 'sticky',
                top: 0,
                zIndex: 5,
                // Solid white base UNDER the translucent brand gradient so the
                // scrolling rider list never shows through the sticky header.
                backgroundColor: '#fff',
                backgroundImage: `linear-gradient(135deg, ${tint(BRAND)} 0%, ${tint(BRAND_LIGHT)} 100%)`,
                borderBottom: `1px solid ${DT.borderSubtle}`,
                p: 1.75
              }}
            >
              <Stack direction="row" alignItems="center" spacing={1.25} sx={{ mb: 1.25 }}>
                <Avatar
                  sx={{
                    width: 38,
                    height: 38,
                    bgcolor: BRAND,
                    color: '#fff',
                    boxShadow: `0 6px 18px ${ring(BRAND)}`
                  }}
                >
                  <MdGroups size={20} />
                </Avatar>
                <Stack sx={{ flex: 1, minWidth: 0 }}>
                  <Typography
                    sx={{
                      fontWeight: 800,
                      color: DT.textPrimary,
                      fontSize: { xs: '1rem', sm: '1.1rem' },
                      lineHeight: 1.1
                    }}
                    noWrap
                  >
                    Riders
                  </Typography>
                  <Stack direction="row" alignItems="center" spacing={0.5} sx={{ mt: 0.25 }}>
                    <Box
                      sx={{
                        width: 7,
                        height: 7,
                        borderRadius: '50%',
                        bgcolor: C_ACTIVE,
                        boxShadow: `0 0 0 3px ${ring(C_ACTIVE)}`
                      }}
                    />
                    <Typography variant="caption" sx={{ color: DT.textSecondary, fontWeight: 600 }}>
                      Updated · {dayjs().format('hh:mm A')}
                    </Typography>
                  </Stack>
                </Stack>
              </Stack>

              {/* Count pills */}
              <Stack direction="row" spacing={0.75} flexWrap="wrap" useFlexGap sx={{ mb: 1.25 }}>
                <SoftPill color={BRAND} icon={<MdGroups size={11} />}>
                  Total · {totalRiders}
                </SoftPill>
                <SoftPill color={C_ACTIVE} icon={<MdCheckCircle size={11} />}>
                  Active · {activeCount}
                </SoftPill>
              </Stack>

              {/* Pill search */}
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 0.75,
                  px: 1.25,
                  py: 0.5,
                  borderRadius: 999,
                  bgcolor: '#fff',
                  border: `1.5px solid ${edge(BRAND)}`,
                  transition: 'all 0.18s',
                  '&:focus-within': {
                    borderColor: BRAND,
                    boxShadow: `0 0 0 3px ${ring(BRAND)}`
                  }
                }}
              >
                <MdSearch size={16} style={{ color: BRAND, flexShrink: 0 }} />
                <InputBase
                  inputRef={searchRef}
                  placeholder="Search rider (ctrl+k)"
                  value={riderSearch}
                  onChange={(e) => setRiderSearch(e.target.value)}
                  autoComplete="off"
                  sx={{
                    flex: 1,
                    fontSize: 13,
                    fontWeight: 600,
                    color: DT.textPrimary,
                    '& input::placeholder': { color: DT.textMuted, opacity: 1 }
                  }}
                />
                {riderSearch && (
                  <IconButton size="small" onClick={() => setRiderSearch('')} sx={{ p: 0.25, color: BRAND }}>
                    <MdClear size={14} />
                  </IconButton>
                )}
              </Box>
            </Box>

            {/* ===== "All" selection pill ===== */}
            <Box sx={{ p: 1.25, pb: 0.5 }}>
              <Box
                onClick={() => {
                  if (!isAllSelected) {
                    setSelectedRiders(activeRiders);
                  }
                }}
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 1,
                  px: 1,
                  py: 0.75,
                  borderRadius: 999,
                  cursor: 'pointer',
                  border: `1.5px solid ${isAllSelected ? BRAND : edge(BRAND)}`,
                  bgcolor: isAllSelected ? BRAND : tint(BRAND),
                  color: isAllSelected ? '#fff' : BRAND,
                  transition: 'all 0.18s',
                  boxShadow: isAllSelected ? `0 6px 18px ${ring(BRAND)}` : 'none',
                  '&:hover': {
                    borderColor: BRAND,
                    boxShadow: `0 0 0 3px ${ring(BRAND)}`
                  }
                }}
              >
                <Checkbox
                  size="small"
                  checked={isAllSelected}
                  onChange={(e) => {
                    if (e.target.checked) {
                      setSelectedRiders(activeRiders);
                    }
                  }}
                  sx={{
                    p: 0,
                    color: isAllSelected ? '#fff' : BRAND,
                    '&.Mui-checked': { color: '#fff' }
                  }}
                />
                <Typography variant="caption" sx={{ fontWeight: 800, fontSize: 12.5 }}>
                  Show All Riders
                </Typography>
                <Box
                  sx={{
                    ml: 'auto',
                    minWidth: 24,
                    height: 20,
                    px: 0.625,
                    display: 'inline-flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    borderRadius: 999,
                    fontSize: 11,
                    fontWeight: 800,
                    bgcolor: isAllSelected ? 'rgba(255,255,255,0.22)' : '#fff',
                    color: isAllSelected ? '#fff' : BRAND,
                    border: isAllSelected ? 'none' : `1px solid ${edge(BRAND)}`
                  }}
                >
                  {totalRiders}
                </Box>
              </Box>
            </Box>

            {/* ===== Rider list ===== */}
            <List sx={{ px: 1, py: 0.5 }}>
              {ridersIsLoading || riderIsFetching
                ? Array.from({ length: 8 }).map((_, index) => (
                    <ListItem key={index} sx={{ px: 1, py: 1 }}>
                      <Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
                        <Skeleton variant="circular" width={32} height={32} />
                        <Stack sx={{ flex: 1 }}>
                          <Skeleton variant="text" width="60%" height={18} />
                          <Skeleton variant="text" width="40%" height={14} />
                        </Stack>
                        <Stack spacing={0.5}>
                          <Skeleton variant="text" width={60} height={16} />
                          <Skeleton variant="text" width={80} height={12} />
                        </Stack>
                      </Stack>
                    </ListItem>
                  ))
                : activeRiders.map((row) => {
                    const isSelected = selectedRiders?.length === 1 && selectedRiders[0]?.userid === row?.userid;
                    const statusColor = row.status === 'active' ? C_ACTIVE : C_INACTIVE;
                    const initial = (row.firstname || row.username || '?').charAt(0).toUpperCase();
                    const name =
                      row.username && row.username.length > 0
                        ? `${row.username.slice(0, 25)}${row.username.length > 25 ? '…' : ''}`
                        : `${row.firstname || ''}${row.lastname ? ` ${row.lastname}` : ''}`.trim() || 'Rider';

                    return (
                      <Box
                        key={row.userid}
                        onClick={() => {
                          // Tapping the card selects this rider in isolation.
                          setSelectedRiders([row]);
                        }}
                        sx={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: 1,
                          p: 1,
                          mb: 0.625,
                          borderRadius: 2,
                          cursor: 'pointer',
                          border: `1px solid ${isSelected ? edge(BRAND) : DT.divider}`,
                          bgcolor: isSelected ? tint(BRAND) : '#fff',
                          transition: 'all 0.15s',
                          '&:hover': {
                            borderColor: edge(BRAND),
                            bgcolor: isSelected ? soft(BRAND) : DT.surfaceAlt,
                            boxShadow: DT.shadowSoft
                          }
                        }}
                      >
                        <Checkbox
                          size="small"
                          checked={isSelected}
                          onClick={(e) => e.stopPropagation()}
                          onChange={(e) => {
                            if (e.target.checked) {
                              setSelectedRiders([row]);
                            } else {
                              setSelectedRiders(activeRiders);
                            }
                          }}
                          sx={{
                            p: 0.5,
                            color: edge(BRAND),
                            '&.Mui-checked': { color: BRAND }
                          }}
                        />

                        <Avatar
                          sx={{
                            width: 36,
                            height: 36,
                            bgcolor: soft(statusColor),
                            color: statusColor,
                            fontWeight: 800,
                            fontSize: 14,
                            position: 'relative'
                          }}
                        >
                          {initial}
                          <Box
                            sx={{
                              position: 'absolute',
                              bottom: -1,
                              right: -1,
                              width: 10,
                              height: 10,
                              borderRadius: '50%',
                              bgcolor: statusColor,
                              border: '2px solid #fff'
                            }}
                          />
                        </Avatar>

                        <Stack sx={{ flex: 1, minWidth: 0 }}>
                          <Typography
                            sx={{
                              fontWeight: 700,
                              color: DT.textPrimary,
                              fontSize: 13,
                              lineHeight: 1.15
                            }}
                            noWrap
                          >
                            {name}
                          </Typography>
                          <Stack direction="row" alignItems="center" spacing={0.5} sx={{ mt: 0.25 }}>
                            <Typography variant="caption" sx={{ color: DT.textSecondary, fontSize: 11 }} noWrap>
                              {row.contactno || '##########'}
                            </Typography>
                          </Stack>
                        </Stack>

                        <Stack alignItems="flex-end" spacing={0.5} sx={{ minWidth: 0 }}>
                          <SoftPill
                            color={statusColor}
                            icon={row.status === 'active' ? <MdCheckCircle size={10} /> : <MdHighlightOff size={10} />}
                            sx={{ fontSize: 10 }}
                          >
                            {row.status === 'active' ? 'Active' : 'Inactive'}
                          </SoftPill>
                          <Stack direction="row" alignItems="center" spacing={0.375}>
                            <MdAccessTime size={10} style={{ color: DT.textMuted }} />
                            <Typography sx={{ fontSize: 10, color: DT.textMuted, fontWeight: 700 }} noWrap>
                              {row.logdate ? dayjs(row.logdate).format('DD/MM · hh:mm A') : '—'}
                            </Typography>
                          </Stack>
                        </Stack>
                      </Box>
                    );
                  })}

              {!ridersIsLoading && !riderIsFetching && totalRiders === 0 && (
                <Stack alignItems="center" spacing={1.25} sx={{ py: 6, px: 2 }}>
                  <Avatar sx={{ width: 56, height: 56, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                    <MdGroups size={24} />
                  </Avatar>
                  <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                    No riders to show
                  </Typography>
                  <Typography variant="caption" sx={{ color: DT.textSecondary, textAlign: 'center' }}>
                    {riderSearch ? 'Try a different rider name.' : 'Pull-to-refresh once you have rider activity.'}
                  </Typography>
                </Stack>
              )}
            </List>
          </Drawer>

          {/* ============================================= || AppBar || ============================================= */}
          <AppBar
            elevation={0}
            position="absolute"
            sx={{
              top: 0,
              left: open && isDesktop ? `${drawerWidth}px` : 0,
              width: open && isDesktop ? `calc(100% - ${drawerWidth}px)` : '100%',
              transition: 'left 0.3s ease, width 0.3s ease',
              background: `linear-gradient(135deg, ${tint(BRAND)} 0%, ${tint(BRAND_LIGHT)} 100%)`,
              borderBottom: `1px solid ${DT.borderSubtle}`,
              color: DT.textPrimary
            }}
          >
            <Toolbar sx={{ minHeight: { xs: 60, md: 68 } }}>
              <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ width: '100%' }}>
                <Stack direction="row" alignItems="center" spacing={1.25}>
                  <IconButton
                    onClick={() => setOpen(!open)}
                    sx={{
                      bgcolor: '#fff',
                      border: `1px solid ${DT.borderSubtle}`,
                      borderRadius: 999,
                      color: BRAND,
                      '&:hover': { bgcolor: tint(BRAND), borderColor: edge(BRAND) }
                    }}
                  >
                    <MdMenu size={18} />
                  </IconButton>
                  <Avatar
                    sx={{
                      width: 36,
                      height: 36,
                      bgcolor: BRAND,
                      color: '#fff',
                      boxShadow: `0 6px 18px ${ring(BRAND)}`
                    }}
                  >
                    <MdLocationOn size={18} />
                  </Avatar>
                  <Stack>
                    <Typography
                      sx={{
                        fontWeight: 800,
                        color: DT.textPrimary,
                        lineHeight: 1.1,
                        fontSize: { xs: '0.95rem', sm: '1.1rem', md: '1.25rem' }
                      }}
                    >
                      Riders Locations
                    </Typography>
                    <Stack direction="row" alignItems="center" spacing={0.5} sx={{ mt: 0.25 }}>
                      <Box
                        sx={{
                          width: 7,
                          height: 7,
                          borderRadius: '50%',
                          bgcolor: C_ACTIVE,
                          boxShadow: `0 0 0 3px ${ring(C_ACTIVE)}`
                        }}
                      />
                      <Typography variant="caption" sx={{ color: DT.textSecondary, fontWeight: 600 }}>
                        Live · {selectedRiders?.length || 0} of {totalRiders} on map
                      </Typography>
                    </Stack>
                  </Stack>
                </Stack>

                <Stack direction="row" alignItems="center" spacing={1}>
                  <SoftPill color={BRAND} icon={<MdMyLocation size={11} />} sx={{ display: { xs: 'none', sm: 'inline-flex' } }}>
                    {dayjs().format('DD MMM YYYY')}
                  </SoftPill>
                  <Button
                    variant="contained"
                    onClick={() => riderLogsRefetch()}
                    startIcon={<MdRefresh size={16} />}
                    sx={{
                      borderRadius: 999,
                      px: 2,
                      bgcolor: BRAND,
                      fontWeight: 700,
                      boxShadow: `0 6px 18px ${ring(BRAND)}`,
                      textTransform: 'none',
                      '&:hover': { bgcolor: '#4D1C61' }
                    }}
                  >
                    Refresh
                  </Button>
                </Stack>
              </Stack>
            </Toolbar>
          </AppBar>

          {/* ============================================= || Map area || ============================================= */}
          <Box
            sx={{
              flexGrow: 1,
              overflow: 'auto',
              pt: { xs: '60px', md: '68px' },
              pl: open && isDesktop ? `${drawerWidth}px` : 0,
              transition: 'padding-left 0.3s ease',
              minHeight: '80vh',
              bgcolor: DT.surfaceAlt
            }}
          >
            {(ridersIsLoading || riderIsFetching) && (
              <Box position="relative" width="100%" height="80vh" display="grid" placeItems="center">
                <Skeleton
                  variant="rectangular"
                  width="100%"
                  height="100%"
                  animation="wave"
                  sx={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    borderRadius: 0,
                    zIndex: 1
                  }}
                />
              </Box>
            )}

            {selectedRiders?.length > 0 && !riderLogsError && <RiderLocationMap riderLocations={selectedRiders} />}

            {riderLogsError && (
              <Stack alignItems="center" justifyContent="center" sx={{ p: 4, height: '70vh' }}>
                <Paper
                  elevation={0}
                  sx={{
                    p: 3,
                    borderRadius: DT.radiusCard / 8,
                    border: '1px solid',
                    borderColor: edge(C_INACTIVE),
                    bgcolor: tint(C_INACTIVE),
                    maxWidth: 520,
                    textAlign: 'center'
                  }}
                >
                  <Avatar sx={{ bgcolor: C_INACTIVE, color: '#fff', width: 56, height: 56, mx: 'auto', mb: 1.5 }}>
                    <MdHighlightOff size={26} />
                  </Avatar>
                  <Typography variant="h6" sx={{ fontWeight: 800, color: DT.textPrimary, mb: 0.5 }}>
                    Couldn’t load rider logs
                  </Typography>
                  <Typography variant="caption" sx={{ color: DT.textSecondary, fontWeight: 600 }}>
                    The map is unavailable right now. Try refreshing in a moment.
                  </Typography>
                  <Box sx={{ mt: 2 }}>
                    <Button
                      variant="contained"
                      onClick={() => riderLogsRefetch()}
                      startIcon={<MdRefresh size={16} />}
                      sx={{
                        borderRadius: 999,
                        px: 3,
                        bgcolor: BRAND,
                        fontWeight: 700,
                        boxShadow: `0 6px 18px ${ring(BRAND)}`,
                        textTransform: 'none',
                        '&:hover': { bgcolor: '#4D1C61' }
                      }}
                    >
                      Retry
                    </Button>
                  </Box>
                </Paper>
                <Box
                  component="img"
                  src={error500}
                  alt="error"
                  sx={{ mt: 2, maxWidth: 240, opacity: 0.6, filter: 'grayscale(0.2)' }}
                />
              </Stack>
            )}
          </Box>
        </Box>
      </Paper>
    </Fragment>
  );
};

export default RidersLogs;
