/**
 * @ai-summary Desktop sidebar panel for audit logs
 * @ai-context Collapsible panel showing paginated audit logs for desktop views
 */

import React, { useState } from 'react';
import {
  Box,
  Paper,
  Typography,
  IconButton,
  List,
  ListItem,
  ListItemText,
  Collapse,
  Divider,
} from '@mui/material';
import {
  ExpandLess,
  ExpandMore,
  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 AuditLogPanel component
 */
export interface AuditLogPanelProps {
  resourceType?: 'admin' | 'catalog' | 'station';
  limit?: number;
  pollIntervalMs?: number;
}

/**
 * Desktop sidebar panel for displaying audit logs
 *
 * @example
 * ```tsx
 * <AuditLogPanel
 *   resourceType="catalog"
 *   limit={50}
 *   pollIntervalMs={5000}
 * />
 * ```
 */
export const AuditLogPanel: React.FC<AuditLogPanelProps> = ({
  resourceType,
  limit = 50,
  pollIntervalMs = 5000,
}) => {
  const [collapsed, setCollapsed] = useState(false);

  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 (
    <Paper
      sx={{
        width: 320,
        height: 'fit-content',
        maxHeight: 'calc(100vh - 200px)',
        display: 'flex',
        flexDirection: 'column',
        boxShadow: 2,
      }}
    >
      {/* Header */}
      <Box
        sx={{
          p: 2,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          borderBottom: 1,
          borderColor: 'divider',
        }}
      >
        <Box>
          <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
            Audit Logs
          </Typography>
          <Typography variant="caption" color="text.secondary">
            {resourceLabel} (Last {limit})
          </Typography>
        </Box>
        <IconButton
          onClick={() => setCollapsed(!collapsed)}
          size="small"
          aria-label={collapsed ? 'expand' : 'collapse'}
          sx={{ minWidth: 44, minHeight: 44 }}
        >
          {collapsed ? <ExpandMore /> : <ExpandLess />}
        </IconButton>
      </Box>

      {/* Content */}
      <Collapse in={!collapsed}>
        <Box sx={{ flex: 1, overflow: 'auto', minHeight: 200 }}>
          {loading && <AdminSkeleton.SkeletonRow 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 dense>
              {logs.map((log) => (
                <React.Fragment key={log.id}>
                  <ListItem alignItems="flex-start">
                    <ListItemText
                      primary={
                        <Typography variant="body2" sx={{ fontWeight: 600 }}>
                          {log.action}
                        </Typography>
                      }
                      secondary={
                        <Box>
                          <Typography
                            variant="caption"
                            component="span"
                            color="text.secondary"
                          >
                            {dayjs(log.createdAt).fromNow()}
                          </Typography>
                          {log.resourceType && (
                            <Typography
                              variant="caption"
                              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: 1,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              borderTop: 1,
              borderColor: 'divider',
            }}
          >
            <Typography variant="caption" color="text.secondary">
              Updated {dayjs(lastUpdated).fromNow()}
            </Typography>
            <Box>
              <IconButton
                size="small"
                onClick={prevPage}
                disabled={pagination.offset === 0}
                aria-label="previous page"
                sx={{ minWidth: 44, minHeight: 44 }}
              >
                <ChevronLeft />
              </IconButton>
              <IconButton
                size="small"
                onClick={nextPage}
                disabled={!hasMore}
                aria-label="next page"
                sx={{ minWidth: 44, minHeight: 44 }}
              >
                <ChevronRight />
              </IconButton>
            </Box>
          </Box>
        )}
      </Collapse>
    </Paper>
  );
};
