import { useState, useEffect, useCallback } from "react";
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  CircularProgress,
  Alert,
  List,
  ListItemButton,
  ListItemText,
  ListItemIcon,
  Chip,
  TextField,
  InputAdornment,
  Paper,
  Divider,
  IconButton,
  Tooltip,
  alpha,
  useMediaQuery,
  useTheme,
  AppBar,
  Toolbar,
} from "@mui/material";
import {
  Search as SearchIcon,
  Event as EventIcon,
  People as PeopleIcon,
  Place as PlaceIcon,
  Inventory as InventoryIcon,
  Person as PersonIcon,
  Category as CategoryIcon,
  Groups as GroupsIcon,
  Badge as BadgeIcon,
  Folder as FolderIcon,
  TableChart as TableIcon,
  Check as CheckIcon,
  Clear as ClearIcon,
  Close as CloseIcon,
  ArrowBack as BackIcon,
} from "@mui/icons-material";
import { useQueries } from "@tanstack/react-query";
import { reportGeneratorService } from "../../services/reportService";
import type {
  DatasetTypeDto,
  DataSourceSelection,
  EntityListItemDto,
} from "../../types/report";

interface PreviewDialogProps {
  open: boolean;
  onClose: () => void;
  selectedDatasets: DatasetTypeDto[];
  onGeneratePreview: (dataSources: DataSourceSelection[]) => void;
  isGenerating: boolean;
}

export default function PreviewDialog({
  open,
  onClose,
  selectedDatasets,
  onGeneratePreview,
  isGenerating,
}: PreviewDialogProps) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

  const [selections, setSelections] = useState<Record<string, number | null>>(
    {},
  );
  const [searchTerms, setSearchTerms] = useState<Record<string, string>>({});
  const [activeDataset, setActiveDataset] = useState<string | null>(null);
  const [mobileShowList, setMobileShowList] = useState(true); // Mobile: show dataset list or entity list

  // Fetch entities for each selected dataset
  const entityQueries = useQueries({
    queries: selectedDatasets.map((dataset) => ({
      queryKey: ["dataset-entities", dataset.id, searchTerms[dataset.id] || ""],
      queryFn: () => reportGeneratorService.getEntitiesForDataset(dataset.id),
      enabled: open,
      staleTime: 30000,
    })),
  });

  // Reset selections when dialog opens or datasets change
  useEffect(() => {
    if (open) {
      const initialSelections: Record<string, number | null> = {};
      const initialSearch: Record<string, string> = {};
      selectedDatasets.forEach((ds) => {
        initialSelections[ds.id] = null;
        initialSearch[ds.id] = "";
      });
      setSelections(initialSelections);
      setSearchTerms(initialSearch);
      setActiveDataset(
        selectedDatasets.length > 0 ? selectedDatasets[0].id : null,
      );
      setMobileShowList(true);
    }
  }, [open, selectedDatasets]);

  const handleSelectionChange = (datasetId: string, entityId: number) => {
    setSelections((prev) => ({
      ...prev,
      [datasetId]: entityId,
    }));

    // On mobile, go back to list after selection
    if (isMobile) {
      setMobileShowList(true);
    }

    // Passa al prossimo dataset non selezionato
    const currentIndex = selectedDatasets.findIndex(
      (ds) => ds.id === datasetId,
    );
    const nextUnselected = selectedDatasets.find(
      (ds, idx) => idx > currentIndex && !selections[ds.id],
    );
    if (nextUnselected) {
      setActiveDataset(nextUnselected.id);
      if (isMobile) {
        setTimeout(() => setMobileShowList(false), 300);
      }
    }
  };

  const handleSearchChange = (datasetId: string, value: string) => {
    setSearchTerms((prev) => ({
      ...prev,
      [datasetId]: value,
    }));
  };

  const handleClearSelection = (datasetId: string) => {
    setSelections((prev) => ({
      ...prev,
      [datasetId]: null,
    }));
  };

  const handleGenerate = () => {
    const dataSources: DataSourceSelection[] = selectedDatasets
      .filter(
        (ds) => selections[ds.id] !== null && selections[ds.id] !== undefined,
      )
      .map((ds) => ({
        datasetId: ds.id,
        entityId: selections[ds.id]!,
      }));

    if (dataSources.length === 0) {
      return;
    }

    onGeneratePreview(dataSources);
  };

  const handleSelectDataset = (datasetId: string) => {
    setActiveDataset(datasetId);
    if (isMobile) {
      setMobileShowList(false);
    }
  };

  const getDatasetIcon = (icon: string) => {
    switch (icon) {
      case "event":
        return <EventIcon />;
      case "people":
        return <PeopleIcon />;
      case "place":
        return <PlaceIcon />;
      case "inventory":
        return <InventoryIcon />;
      case "person":
        return <PersonIcon />;
      case "category":
        return <CategoryIcon />;
      case "groups":
        return <GroupsIcon />;
      case "badge":
        return <BadgeIcon />;
      case "folder":
        return <FolderIcon />;
      default:
        return <TableIcon />;
    }
  };

  const filterEntities = useCallback(
    (entities: EntityListItemDto[], search: string) => {
      if (!search) return entities;
      const searchLower = search.toLowerCase();
      return entities.filter(
        (e) =>
          e.label.toLowerCase().includes(searchLower) ||
          e.description.toLowerCase().includes(searchLower) ||
          (e.secondaryInfo &&
            e.secondaryInfo.toLowerCase().includes(searchLower)),
      );
    },
    [],
  );

  const allSelected = selectedDatasets.every(
    (ds) => selections[ds.id] !== null,
  );
  const selectedCount = selectedDatasets.filter(
    (ds) => selections[ds.id] !== null,
  ).length;
  const hasError = entityQueries.some((q) => q.isError);

  // Trova il dataset attivo e i suoi dati
  const activeDatasetObj = selectedDatasets.find(
    (ds) => ds.id === activeDataset,
  );
  const activeQueryIndex = selectedDatasets.findIndex(
    (ds) => ds.id === activeDataset,
  );
  const activeQuery =
    activeQueryIndex >= 0 ? entityQueries[activeQueryIndex] : null;
  const activeEntities = activeQuery?.data || [];
  const filteredEntities = filterEntities(
    activeEntities as EntityListItemDto[],
    searchTerms[activeDataset || ""] || "",
  );

  // Render dataset list (sidebar on desktop, main view on mobile)
  const renderDatasetList = () => (
    <List disablePadding>
      {selectedDatasets.map((dataset, index) => {
        const isSelected = selections[dataset.id] !== null;
        const isActive = activeDataset === dataset.id;
        const query = entityQueries[index];
        const selectedEntity = isSelected
          ? ((query.data as EntityListItemDto[]) || []).find(
              (e) => e.id === selections[dataset.id],
            )
          : null;

        return (
          <ListItemButton
            key={dataset.id}
            selected={isActive}
            onClick={() => handleSelectDataset(dataset.id)}
            sx={{
              borderBottom: 1,
              borderColor: "divider",
              bgcolor: isSelected
                ? (theme) => alpha(theme.palette.success.main, 0.08)
                : "inherit",
              py: isMobile ? 1.5 : 1,
            }}
          >
            <ListItemIcon sx={{ minWidth: 36 }}>
              {isSelected ? (
                <CheckIcon color="success" />
              ) : (
                getDatasetIcon(dataset.icon)
              )}
            </ListItemIcon>
            <ListItemText
              primary={dataset.name}
              secondary={
                selectedEntity ? selectedEntity.label : "Non selezionato"
              }
              primaryTypographyProps={{
                variant: "body2",
                fontWeight: isActive ? 600 : 400,
              }}
              secondaryTypographyProps={{
                variant: "caption",
                noWrap: true,
                color: isSelected ? "success.main" : "text.secondary",
              }}
            />
            {isSelected && (
              <Tooltip title="Rimuovi selezione">
                <IconButton
                  size="small"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleClearSelection(dataset.id);
                  }}
                >
                  <ClearIcon fontSize="small" />
                </IconButton>
              </Tooltip>
            )}
          </ListItemButton>
        );
      })}
    </List>
  );

  // Render entity list for active dataset
  const renderEntityList = () => {
    if (!activeDatasetObj) return null;

    return (
      <Box
        sx={{
          flex: 1,
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
          height: "100%",
        }}
      >
        {/* Header dataset attivo */}
        <Box
          sx={{
            p: 2,
            borderBottom: 1,
            borderColor: "divider",
            bgcolor: "grey.50",
          }}
        >
          {isMobile && (
            <Box display="flex" alignItems="center" gap={1} mb={1}>
              <IconButton size="small" onClick={() => setMobileShowList(true)}>
                <BackIcon />
              </IconButton>
              <Typography variant="subtitle2">Seleziona</Typography>
            </Box>
          )}
          <Box display="flex" alignItems="center" gap={1} mb={1}>
            {getDatasetIcon(activeDatasetObj.icon)}
            <Typography variant="subtitle1" fontWeight={600}>
              {activeDatasetObj.name}
            </Typography>
            {!isMobile && (
              <Chip
                label={activeDatasetObj.category}
                size="small"
                variant="outlined"
                sx={{ ml: "auto" }}
              />
            )}
          </Box>
          {!isMobile && (
            <Typography
              variant="caption"
              color="text.secondary"
              display="block"
              mb={1.5}
            >
              {activeDatasetObj.description}
            </Typography>
          )}

          {/* Ricerca */}
          <TextField
            placeholder={`Cerca...`}
            size="small"
            fullWidth
            value={searchTerms[activeDataset || ""] || ""}
            onChange={(e) => handleSearchChange(activeDataset!, e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon fontSize="small" />
                </InputAdornment>
              ),
              endAdornment: searchTerms[activeDataset || ""] && (
                <InputAdornment position="end">
                  <IconButton
                    size="small"
                    onClick={() => handleSearchChange(activeDataset!, "")}
                  >
                    <ClearIcon fontSize="small" />
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
        </Box>

        {/* Lista entità */}
        <Box sx={{ flex: 1, overflow: "auto" }}>
          {activeQuery?.isLoading ? (
            <Box display="flex" justifyContent="center" py={4}>
              <CircularProgress />
            </Box>
          ) : filteredEntities.length === 0 ? (
            <Box sx={{ p: 3, textAlign: "center" }}>
              <Typography variant="body2" color="text.secondary">
                {searchTerms[activeDataset || ""]
                  ? "Nessun risultato trovato"
                  : "Nessuna entità disponibile"}
              </Typography>
            </Box>
          ) : (
            <List disablePadding>
              {filteredEntities.map((entity) => {
                const isEntitySelected =
                  selections[activeDataset!] === entity.id;

                return (
                  <ListItemButton
                    key={entity.id}
                    onClick={() =>
                      handleSelectionChange(activeDataset!, entity.id)
                    }
                    selected={isEntitySelected}
                    sx={{
                      borderBottom: 1,
                      borderColor: "divider",
                      bgcolor: isEntitySelected
                        ? (theme) => alpha(theme.palette.primary.main, 0.12)
                        : "inherit",
                      py: isMobile ? 1.5 : 1,
                    }}
                  >
                    <ListItemIcon sx={{ minWidth: 36 }}>
                      {isEntitySelected ? (
                        <CheckIcon color="primary" />
                      ) : (
                        <Box sx={{ width: 24 }} />
                      )}
                    </ListItemIcon>
                    <ListItemText
                      primary={entity.label}
                      secondary={
                        <Box component="span">
                          {entity.description}
                          {entity.secondaryInfo && !isMobile && (
                            <Typography
                              component="span"
                              variant="caption"
                              color="text.disabled"
                              sx={{ display: "block" }}
                            >
                              {entity.secondaryInfo}
                            </Typography>
                          )}
                        </Box>
                      }
                      primaryTypographyProps={{
                        variant: "body2",
                        fontWeight: isEntitySelected ? 600 : 400,
                      }}
                      secondaryTypographyProps={{
                        variant: "caption",
                      }}
                    />
                    {entity.status && (
                      <Chip
                        label={entity.status}
                        size="small"
                        color={
                          entity.status === "Confermato"
                            ? "success"
                            : entity.status === "Preventivo"
                              ? "warning"
                              : "default"
                        }
                        variant="outlined"
                        sx={{ ml: 1 }}
                      />
                    )}
                  </ListItemButton>
                );
              })}
            </List>
          )}
        </Box>

        {/* Footer con conteggio */}
        <Box
          sx={{
            p: 1,
            borderTop: 1,
            borderColor: "divider",
            bgcolor: "grey.50",
          }}
        >
          <Typography variant="caption" color="text.secondary">
            {filteredEntities.length} risultati
          </Typography>
        </Box>
      </Box>
    );
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      fullScreen={isMobile}
      PaperProps={{
        sx: {
          height: isMobile ? "100%" : "80vh",
          maxHeight: isMobile ? "100%" : 700,
        },
      }}
    >
      {/* Mobile AppBar */}
      {isMobile ? (
        <AppBar position="static" color="default" elevation={0}>
          <Toolbar>
            <IconButton edge="start" onClick={onClose}>
              <CloseIcon />
            </IconButton>
            <Typography variant="h6" sx={{ flex: 1, ml: 1 }}>
              Anteprima Report
            </Typography>
            <Chip
              label={`${selectedCount}/${selectedDatasets.length}`}
              color={allSelected ? "success" : "default"}
              size="small"
            />
          </Toolbar>
        </AppBar>
      ) : (
        <DialogTitle sx={{ pb: 1 }}>
          <Box
            display="flex"
            alignItems="center"
            justifyContent="space-between"
          >
            <Typography variant="h6">Anteprima Report</Typography>
            <Chip
              label={`${selectedCount}/${selectedDatasets.length} selezionati`}
              color={allSelected ? "success" : "default"}
              size="small"
            />
          </Box>
          <Typography variant="body2" color="text.secondary">
            Seleziona un'entità per ogni dataset da utilizzare nell'anteprima
          </Typography>
        </DialogTitle>
      )}

      <Divider />

      <DialogContent sx={{ p: 0, display: "flex", overflow: "hidden" }}>
        {hasError && (
          <Alert severity="error" sx={{ m: 2 }}>
            Errore nel caricamento dei dati disponibili
          </Alert>
        )}

        {selectedDatasets.length === 0 ? (
          <Box sx={{ p: 3, textAlign: "center", width: "100%" }}>
            <Alert severity="info">
              Non ci sono dataset selezionati per questo template. Aggiungi
              almeno un dataset per poter generare l'anteprima.
            </Alert>
          </Box>
        ) : isMobile ? (
          // Mobile: Switch between dataset list and entity list
          <Box
            sx={{
              flex: 1,
              display: "flex",
              flexDirection: "column",
              overflow: "hidden",
            }}
          >
            {mobileShowList ? (
              <Box sx={{ flex: 1, overflow: "auto" }}>
                <Box
                  sx={{
                    p: 2,
                    bgcolor: "grey.50",
                    borderBottom: 1,
                    borderColor: "divider",
                  }}
                >
                  <Typography variant="body2" color="text.secondary">
                    Seleziona un'entità per ogni dataset
                  </Typography>
                </Box>
                {renderDatasetList()}
              </Box>
            ) : (
              renderEntityList()
            )}
          </Box>
        ) : (
          // Desktop: Side by side
          <>
            {/* Lista dataset (sidebar) */}
            <Paper
              elevation={0}
              sx={{
                width: 240,
                borderRight: 1,
                borderColor: "divider",
                overflow: "auto",
                flexShrink: 0,
              }}
            >
              {renderDatasetList()}
            </Paper>

            {/* Area principale con lista entità */}
            {renderEntityList()}
          </>
        )}
      </DialogContent>

      <Divider />

      <DialogActions sx={{ px: isMobile ? 2 : 3, py: 2 }}>
        <Button onClick={onClose} fullWidth={isMobile}>
          Annulla
        </Button>
        <Button
          variant="contained"
          onClick={handleGenerate}
          disabled={
            !allSelected || isGenerating || selectedDatasets.length === 0
          }
          startIcon={isGenerating ? <CircularProgress size={16} /> : null}
          fullWidth={isMobile}
        >
          {isGenerating
            ? "Generazione..."
            : isMobile
              ? "Genera PDF"
              : "Genera Anteprima PDF"}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
