import React, { useState, useEffect, useRef } from 'react';
import {
  Typography,
  Box,
  TextField,
  CircularProgress,
  InputAdornment,
  Skeleton,
} from '@mui/material';
import { Search, MenuBook } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { bookstackApi } from '../../services/bookstack';
import type { BookStackSearchResult } from '../../types/bookstack.types';
import { safeOpenUrl } from '../../utils/safeOpenUrl';
import { WidgetCard } from '../templates/WidgetCard';

function stripHtml(html: string): string {
  return html.replace(/<[^>]*>/g, '').trim();
}

const ResultRow: React.FC<{ result: BookStackSearchResult; showDivider: boolean }> = ({
  result,
  showDivider: _showDivider,
}) => {
  const preview = result.preview_html?.content ? stripHtml(result.preview_html.content) : '';

  return (
    <>
      <Box
        onClick={() => safeOpenUrl(result.url)}
        sx={{
          py: 1.5,
          px: 1,
          cursor: 'pointer',
          borderRadius: 1,
          transition: 'background-color 0.15s ease',
          '&:hover': { bgcolor: 'action.hover' },
        }}
      >
        <Typography variant="subtitle2" noWrap>
          {result.name}
        </Typography>
        {preview && (
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{
              mt: 0.25,
              overflow: 'hidden',
              display: '-webkit-box',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical',
            }}
          >
            {preview}
          </Typography>
        )}
      </Box>
    </>
  );
};

const BookStackSearchWidget: React.FC = () => {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<BookStackSearchResult[]>([]);
  const [searching, setSearching] = useState(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const latestQueryRef = useRef<string>('');
  const isMountedRef = useRef(true);

  useEffect(() => {
    return () => { isMountedRef.current = false; };
  }, []);

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

  // undefined while loading, true/false once known
  // On error (e.g. 403), treat as configured to avoid "nicht eingerichtet" message
  const configured = configLoading ? undefined : configError ? true : (data?.configured ?? false);

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);

    if (!query.trim()) {
      setResults([]);
      setSearching(false);
      return;
    }

    setSearching(true);
    const thisQuery = query.trim();
    latestQueryRef.current = thisQuery;

    debounceRef.current = setTimeout(async () => {
      try {
        const response = await bookstackApi.search(thisQuery);
        if (isMountedRef.current && latestQueryRef.current === thisQuery) {
          setResults(response.data);
        }
      } catch {
        if (isMountedRef.current && latestQueryRef.current === thisQuery) {
          setResults([]);
        }
      } finally {
        if (isMountedRef.current && latestQueryRef.current === thisQuery) {
          setSearching(false);
        }
      }
    }, 400);

    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [query]);

  if (configured === undefined) {
    return (
      <WidgetCard
        title="Wissen — Suche"
        icon={<MenuBook />}
        isLoading
        skeleton={<Skeleton variant="rectangular" height={40} sx={{ borderRadius: 1 }} animation="wave" />}
      />
    );
  }

  if (configured === false) {
    return (
      <WidgetCard
        title="Wissen — Suche"
        icon={<MenuBook />}
        isEmpty
        emptyMessage="BookStack nicht eingerichtet"
      />
    );
  }

  return (
    <WidgetCard
      title="Wissen — Suche"
      icon={<MenuBook />}
    >
      <TextField
        fullWidth
        size="small"
        placeholder="Suchbegriff eingeben..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              {searching ? <CircularProgress size={16} /> : <Search fontSize="small" />}
            </InputAdornment>
          ),
        }}
      />

      {!searching && query.trim() && results.length === 0 && (
        <Typography variant="body2" color="text.secondary" sx={{ py: 2, textAlign: 'center' }}>
          Keine Ergebnisse für \u201e{query}\u201c
        </Typography>
      )}

      {results.length > 0 && (
        <Box sx={{ mt: 1, maxHeight: 300, overflow: 'auto' }}>
          {results.map((result, index) => (
            <ResultRow
              key={result.id}
              result={result}
              showDivider={index < results.length - 1}
            />
          ))}
        </Box>
      )}
    </WidgetCard>
  );
};

export default BookStackSearchWidget;
