/**
 * @ai-summary Mobile bottom sheet drawer for audit logs
 * @ai-context Bottom drawer showing paginated audit logs optimized for mobile
 */

import React from 'react';
import {
  Drawer,
  Box,
  Typography,
  IconButton,
  List,
  ListItem,
  ListItemText,
  Divider,
} from '@mui/material';
import { Close, ChevronLeft, ChevronRight } from '@mui/icons-material';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useAuditLogStream } from '../hooks/useAuditLogStream';
import { AdminSkeleton } from './AdminSkeleton';
import { EmptyState } from './EmptyState';
import { ErrorState } from './ErrorState';

dayjs.extend(relativeTime);

/**
 * Props for AuditLogDrawer component
 */
export interface AuditLogDrawerProps {
  open: boolean;
  onClose: () => void;
  resourceType?: 'admin' | 'catalog' | 'station';
  limit?: number;
  pollIntervalMs?: number;
}

/**
 * Mobile bottom sheet drawer for displaying audit logs
 *
 * @example
 * ```tsx
 * <AuditLogDrawer
 *   open={drawerOpen}
 *   onClose={() => setDrawerOpen(false)}
 *   resourceType="station"
 *   limit={50}
 * />
 * ```
 */
export const AuditLogDrawer: React.FC<AuditLogDrawerProps> = ({
  open,
  onClose,
  resourceType,
  limit = 50,
  pollIntervalMs = 5000,
}) => {
  const {
    logs,
    loading,
    error,
    pagination,
    hasMore,
    nextPage,
    prevPage,
    refetch,
    lastUpdated,
  } = useAuditLogStream({
    resourceType,
    limit,
    pollIntervalMs,
  });

  const resourceLabel = resourceType
    ? `${resourceType.charAt(0).toUpperCase()}${resourceType.slice(1)} Changes`
    : 'All Changes';

  return (
    <Drawer
      anchor="bottom"
      open={open}
      onClose={onClose}
      PaperProps={{
        sx: {
          maxHeight: '80vh',
          borderTopLeftRadius: 16,
          borderTopRightRadius: 16,
        },
      }}
    >
      <Box sx={{ width: '100%', display: 'flex', flexDirection: 'column' }}>
        {/* Header */}
        <Box
          sx={{
            p: 2,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            borderBottom: 1,
            borderColor: 'divider',
          }}
        >
          <Box>
            <Typography variant="h6" sx={{ fontWeight: 600 }}>
              Audit Logs
            </Typography>
            <Typography variant="caption" color="text.secondary">
              {resourceLabel}
            </Typography>
          </Box>
          <IconButton
            onClick={onClose}
            aria-label="close"
            sx={{ minWidth: 44, minHeight: 44 }}
          >
            <Close />
          </IconButton>
        </Box>

        {/* Content */}
        <Box sx={{ flex: 1, overflow: 'auto', minHeight: 200 }}>
          {loading && <AdminSkeleton.SkeletonCard count={3} />}

          {error && <ErrorState error={error} onRetry={refetch} />}

          {!loading && !error && logs.length === 0 && (
            <EmptyState
              title="No Audit Logs"
              description="No activity recorded yet"
              icon={null}
            />
          )}

          {!loading && !error && logs.length > 0 && (
            <List>
              {logs.map((log) => (
                <React.Fragment key={log.id}>
                  <ListItem
                    alignItems="flex-start"
                    sx={{
                      minHeight: 64,
                    }}
                  >
                    <ListItemText
                      primary={
                        <Typography
                          variant="body1"
                          sx={{ fontWeight: 600, mb: 0.5 }}
                        >
                          {log.action}
                        </Typography>
                      }
                      secondary={
                        <Box>
                          <Typography
                            variant="body2"
                            component="span"
                            color="text.secondary"
                          >
                            {dayjs(log.createdAt).fromNow()}
                          </Typography>
                          {log.resourceType && (
                            <Typography
                              variant="body2"
                              component="span"
                              color="text.secondary"
                              sx={{ ml: 1 }}
                            >
                              | {log.resourceType}
                            </Typography>
                          )}
                        </Box>
                      }
                    />
                  </ListItem>
                  <Divider component="li" />
                </React.Fragment>
              ))}
            </List>
          )}
        </Box>

        {/* Footer with pagination */}
        {!loading && logs.length > 0 && (
          <Box
            sx={{
              p: 2,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              borderTop: 1,
              borderColor: 'divider',
              minHeight: 64,
            }}
          >
            <Typography variant="body2" color="text.secondary">
              Updated {dayjs(lastUpdated).fromNow()}
            </Typography>
            <Box>
              <IconButton
                onClick={prevPage}
                disabled={pagination.offset === 0}
                aria-label="previous page"
                sx={{ minWidth: 44, minHeight: 44 }}
              >
                <ChevronLeft />
              </IconButton>
              <IconButton
                onClick={nextPage}
                disabled={!hasMore}
                aria-label="next page"
                sx={{ minWidth: 44, minHeight: 44 }}
              >
                <ChevronRight />
              </IconButton>
            </Box>
          </Box>
        )}
      </Box>
    </Drawer>
  );
};
