import CloseIcon from "@mui/icons-material/Close";
import SearchIcon from "@mui/icons-material/Search";
import {
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  InputAdornment,
  List,
  ListItem,
  ListItemButton,
  ListItemText,
  Stack,
  TextField,
  Typography
} from "@mui/material";
import { useMutation } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { searchPaperlessDocuments } from "../api/contracts";
import { useSnackbar } from "../hooks/useSnackbar";
import { PaperlessDocument, PaperlessSearchResponse } from "../types";

interface Props {
  open: boolean;
  onClose: () => void;
  onSelect: (document: PaperlessDocument) => void;
}

export default function PaperlessSearchDialog({ open, onClose, onSelect }: Props) {
  const { showMessage } = useSnackbar();
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<PaperlessSearchResponse | null>(null);
  const { t } = useTranslation();

  const searchMutation = useMutation({
    mutationFn: (term: string) => searchPaperlessDocuments(term),
    onSuccess: (data) => setResults(data),
    onError: (error: Error) => showMessage(error.message ?? t("paperlessDialog.error"), "error")
  });

  useEffect(() => {
    if (!open) {
      setQuery("");
      setResults(null);
    }
  }, [open]);

  const handleSearch = () => {
    if (query.trim().length < 2) {
      showMessage(t("paperlessDialog.minChars"), "warning");
      return;
    }
    searchMutation.mutate(query.trim());
  };

  return (
    <Dialog open={open} onClose={onClose} fullWidth maxWidth="md">
      <DialogTitle>
        {t("paperlessDialog.title")}
        <IconButton
          aria-label="close"
          onClick={onClose}
          sx={{ position: "absolute", right: 12, top: 12 }}
        >
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <DialogContent>
        <Stack spacing={2}>
          <TextField
            label={t("contracts.searchLabel")}
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === "Enter") {
                event.preventDefault();
                handleSearch();
              }
            }}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton onClick={handleSearch} edge="end">
                    <SearchIcon />
                  </IconButton>
                </InputAdornment>
              )
            }}
            placeholder={t("paperlessDialog.searchPlaceholder")}
            fullWidth
            autoFocus
          />
          {searchMutation.isPending && <Typography>{t("paperlessDialog.searching")}</Typography>}
          {results && results.results.length === 0 && !searchMutation.isPending && (
            <Typography color="text.secondary">{t("paperlessDialog.noResults")}</Typography>
          )}
          {results && results.results.length > 0 && (
            <List>
              {results.results.map((doc) => (
                <ListItem key={doc.id} disablePadding>
                  <ListItemButton
                    onClick={() => {
                      onSelect(doc);
                      onClose();
                    }}
                  >
                    <ListItemText
                      primary={doc.title ?? `Dokument #${doc.id}`}
                      secondary={
                        <Box component="span" sx={{ display: "block", color: "text.secondary" }}>
                          {(doc as Record<string, unknown>).correspondent
                            ? `${t("paperlessDialog.correspondent")}: ${(doc as Record<string, unknown>).correspondent}`
                            : ""}
                        </Box>
                      }
                    />
                  </ListItemButton>
                </ListItem>
              ))}
            </List>
          )}
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>{t("paperlessDialog.cancel")}</Button>
      </DialogActions>
    </Dialog>
  );
}
