import React from 'react';
import {
  Typography,
  Box,
  Skeleton,
} from '@mui/material';
import { MenuBook } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { formatDistanceToNow } from 'date-fns';
import { de } from 'date-fns/locale';
import { bookstackApi } from '../../services/bookstack';
import type { BookStackPage } from '../../types/bookstack.types';
import { safeOpenUrl } from '../../utils/safeOpenUrl';
import { ListCard } from '../templates/ListCard';
import { WidgetCard } from '../templates/WidgetCard';

const PageRow: React.FC<{ page: BookStackPage }> = ({ page }) => {
  const handleClick = () => {
    safeOpenUrl(page.url);
  };

  const relativeTime = page.updated_at
    ? formatDistanceToNow(new Date(page.updated_at), { addSuffix: true, locale: de })
    : null;

  return (
    <Box
      onClick={handleClick}
      sx={{
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
        px: 1,
        cursor: 'pointer',
        borderRadius: 1,
        transition: 'background-color 0.15s ease',
        '&:hover': { bgcolor: 'action.hover' },
      }}
    >
      <Box sx={{ flex: 1, minWidth: 0 }}>
        <Typography variant="subtitle2" noWrap>
          {page.name}
        </Typography>
        {page.book && (
          <Typography variant="body2" color="text.secondary" noWrap sx={{ mt: 0.25 }}>
            {page.book.name}
          </Typography>
        )}
      </Box>
      {relativeTime && (
        <Typography
          variant="caption"
          color="text.secondary"
          sx={{ ml: 1, whiteSpace: 'nowrap', mt: 0.25 }}
        >
          {relativeTime}
        </Typography>
      )}
    </Box>
  );
};

const BookStackRecentWidget: React.FC = () => {
  const { data, isLoading, isError } = useQuery({
    queryKey: ['bookstack-recent'],
    queryFn: () => bookstackApi.getRecent(),
    refetchInterval: 5 * 60 * 1000,
    retry: 1,
  });

  const configured = data?.configured ?? false;
  const pages = (data?.data ?? []).slice(0, 5);

  // Only show "nicht eingerichtet" when we got a successful response with configured=false
  if (data && !configured) {
    return (
      <WidgetCard
        title="Wissen — Neueste Seiten"
        icon={<MenuBook />}
        isEmpty
        emptyMessage="BookStack nicht eingerichtet"
      />
    );
  }

  if (isError) {
    return (
      <WidgetCard
        title="Wissen — Neueste Seiten"
        icon={<MenuBook />}
        isError
        errorMessage="BookStack nicht erreichbar"
      />
    );
  }

  return (
    <ListCard
      title="Wissen — Neueste Seiten"
      icon={<MenuBook />}
      items={pages}
      renderItem={(page) => <PageRow key={page.id} page={page} />}
      isLoading={isLoading}
      skeletonCount={5}
      skeletonItem={
        <Box sx={{ mb: 0.5 }}>
          <Skeleton variant="text" width="70%" height={22} animation="wave" />
          <Skeleton variant="text" width="50%" height={18} animation="wave" />
        </Box>
      }
      emptyMessage="Keine Seiten gefunden"
    />
  );
};

export default BookStackRecentWidget;
