import { useState, useMemo } from "react";
import {
  Box,
  Typography,
  Chip,
  IconButton,
  Tooltip,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
  Divider,
  ListSubheader,
  Badge,
  Button,
  useMediaQuery,
  useTheme,
  Collapse,
} from "@mui/material";
import {
  Add as AddIcon,
  Event as EventIcon,
  People as PeopleIcon,
  Place as PlaceIcon,
  Inventory as InventoryIcon,
  Person as PersonIcon,
  TableChart as TableIcon,
  Category as CategoryIcon,
  Groups as GroupsIcon,
  Badge as BadgeIcon,
  Folder as FolderIcon,
  List as ListIcon,
  Info as InfoIcon,
  Settings as SettingsIcon,
  Dataset as DatasetIcon,
  ExpandMore as ExpandMoreIcon,
  ExpandLess as ExpandLessIcon,
} from "@mui/icons-material";
import type { DatasetTypeDto } from "../../types/report";

interface DatasetSelectorProps {
  availableDatasets: DatasetTypeDto[];
  selectedDatasets: DatasetTypeDto[];
  onAddDataset: (dataset: DatasetTypeDto) => void;
  onRemoveDataset: (datasetId: string) => void;
  onOpenDatasetManager?: () => void;
}

export default function DatasetSelector({
  availableDatasets,
  selectedDatasets,
  onAddDataset,
  onRemoveDataset,
  onOpenDatasetManager,
}: DatasetSelectorProps) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const isTablet = useMediaQuery(theme.breakpoints.between("sm", "md"));

  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [hoveredDataset, setHoveredDataset] = useState<DatasetTypeDto | null>(
    null,
  );
  const [expanded, setExpanded] = useState(!isMobile);

  const handleOpenMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleCloseMenu = () => {
    setAnchorEl(null);
    setHoveredDataset(null);
  };

  const handleSelectDataset = (dataset: DatasetTypeDto) => {
    onAddDataset(dataset);
    handleCloseMenu();
  };

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

  const getCategoryColor = (
    category: string,
    isVirtual?: boolean,
  ): "primary" | "secondary" | "success" | "warning" | "info" => {
    // Virtual datasets sempre con colore info
    if (isVirtual) return "info";

    switch (category) {
      case "Principale":
        return "primary";
      case "Configurazione":
        return "secondary";
      case "Liste":
        return "success";
      default:
        // Categorie custom (incluse quelle dei virtual dataset)
        return "info";
    }
  };

  // I virtual dataset ora arrivano direttamente dall'API con isVirtual=true
  const unselectedDatasets = availableDatasets.filter(
    (ds) => !selectedDatasets.some((s) => s.id === ds.id),
  );

  // Conta i virtual dataset per il badge
  const virtualDatasetCount = availableDatasets.filter(
    (ds) => ds.isVirtual,
  ).length;

  // Raggruppa dataset non selezionati per categoria
  const groupedDatasets = useMemo(() => {
    const groups: Record<string, DatasetTypeDto[]> = {};
    unselectedDatasets.forEach((ds) => {
      const category = ds.category || "Altro";
      if (!groups[category]) {
        groups[category] = [];
      }
      groups[category].push(ds);
    });
    return groups;
  }, [unselectedDatasets]);

  // Categorie base + categorie dinamiche dai virtual dataset
  const categoryOrder = useMemo(() => {
    const baseCategories = ["Principale", "Configurazione", "Liste"];
    const allCategories = Object.keys(groupedDatasets);

    // Aggiungi categorie non presenti nelle base (dai virtual dataset)
    const additionalCategories = allCategories.filter(
      (cat) => !baseCategories.includes(cat),
    );

    return [...baseCategories, ...additionalCategories];
  }, [groupedDatasets]);

  // Compact mobile view
  if (isMobile) {
    return (
      <Box
        sx={{
          borderBottom: 1,
          borderColor: "divider",
          bgcolor: "grey.50",
        }}
      >
        {/* Header - always visible */}
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            p: 1,
            cursor: "pointer",
          }}
          onClick={() => setExpanded(!expanded)}
        >
          <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
            <DatasetIcon fontSize="small" color="primary" />
            <Typography variant="body2" fontWeight={500}>
              Dataset ({selectedDatasets.length})
            </Typography>
          </Box>
          <IconButton size="small">
            {expanded ? <ExpandLessIcon /> : <ExpandMoreIcon />}
          </IconButton>
        </Box>

        {/* Expandable content */}
        <Collapse in={expanded}>
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              gap: 0.5,
              px: 1,
              pb: 1,
              flexWrap: "wrap",
            }}
          >
            {selectedDatasets.map((dataset) => (
              <Chip
                key={dataset.id}
                icon={getDatasetIcon(dataset.icon)}
                label={dataset.name}
                size="small"
                color={getCategoryColor(dataset.category, dataset.isVirtual)}
                variant="filled"
                onDelete={() => onRemoveDataset(dataset.id)}
                sx={{ fontWeight: 500 }}
              />
            ))}

            {selectedDatasets.length === 0 && (
              <Typography
                variant="caption"
                color="text.secondary"
                fontStyle="italic"
              >
                Nessun dataset selezionato
              </Typography>
            )}

            {unselectedDatasets.length > 0 && (
              <IconButton size="small" onClick={handleOpenMenu} color="primary">
                <AddIcon fontSize="small" />
              </IconButton>
            )}
          </Box>
        </Collapse>

        {/* Menu - shared */}
        <Menu
          anchorEl={anchorEl}
          open={Boolean(anchorEl)}
          onClose={handleCloseMenu}
          PaperProps={{
            sx: { minWidth: 280, maxHeight: "70vh" },
          }}
        >
          <Box sx={{ px: 2, py: 1 }}>
            <Typography variant="subtitle2" color="primary">
              Seleziona Dataset
            </Typography>
          </Box>
          <Divider />

          {categoryOrder.map((category) => {
            const datasets = groupedDatasets[category];
            if (!datasets || datasets.length === 0) return null;

            return (
              <Box key={category}>
                <ListSubheader
                  sx={{
                    bgcolor: "grey.100",
                    lineHeight: "28px",
                    fontSize: "0.7rem",
                    fontWeight: 600,
                  }}
                >
                  {category}
                </ListSubheader>
                {datasets.map((dataset) => (
                  <MenuItem
                    key={dataset.id}
                    onClick={() => handleSelectDataset(dataset)}
                    sx={{ py: 1 }}
                  >
                    <ListItemIcon
                      sx={{
                        color: `${getCategoryColor(dataset.category, dataset.isVirtual)}.main`,
                      }}
                    >
                      {getDatasetIcon(dataset.icon)}
                    </ListItemIcon>
                    <ListItemText
                      primary={dataset.name}
                      primaryTypographyProps={{ variant: "body2" }}
                    />
                  </MenuItem>
                ))}
              </Box>
            );
          })}

          {onOpenDatasetManager && [
            <Divider key="divider" />,
            <MenuItem
              key="manager"
              onClick={() => {
                handleCloseMenu();
                onOpenDatasetManager();
              }}
            >
              <ListItemIcon>
                <SettingsIcon fontSize="small" />
              </ListItemIcon>
              <ListItemText primary="Gestisci Dataset" />
            </MenuItem>,
          ]}
        </Menu>
      </Box>
    );
  }

  // Tablet/Desktop view
  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        gap: 1,
        p: isTablet ? 1 : 1.5,
        borderBottom: 1,
        borderColor: "divider",
        bgcolor: "grey.50",
        flexWrap: "wrap",
        minHeight: isTablet ? 44 : 52,
      }}
    >
      <Typography
        variant="caption"
        color="text.secondary"
        sx={{ mr: 1, fontWeight: 500 }}
      >
        Dataset:
      </Typography>

      {selectedDatasets.map((dataset) => (
        <Tooltip
          key={dataset.id}
          title={
            <Box>
              <Typography variant="body2" fontWeight={600}>
                {dataset.name}
              </Typography>
              <Typography variant="caption">{dataset.description}</Typography>
              <Typography variant="caption" display="block" color="grey.400">
                Categoria: {dataset.category}
              </Typography>
            </Box>
          }
          arrow
        >
          <Chip
            icon={getDatasetIcon(dataset.icon)}
            label={dataset.name}
            size="small"
            color={getCategoryColor(dataset.category, dataset.isVirtual)}
            variant="filled"
            onDelete={() => onRemoveDataset(dataset.id)}
            sx={{ fontWeight: 500 }}
          />
        </Tooltip>
      ))}

      {selectedDatasets.length === 0 && (
        <Typography variant="caption" color="text.secondary" fontStyle="italic">
          Nessun dataset selezionato - Aggiungi un dataset per accedere ai campi
          dati
        </Typography>
      )}

      {unselectedDatasets.length > 0 && (
        <>
          <Tooltip title="Aggiungi dataset">
            <Badge
              badgeContent={unselectedDatasets.length}
              color="primary"
              sx={{
                "& .MuiBadge-badge": { fontSize: 10, height: 16, minWidth: 16 },
              }}
            >
              <IconButton size="small" onClick={handleOpenMenu} color="primary">
                <AddIcon fontSize="small" />
              </IconButton>
            </Badge>
          </Tooltip>

          <Menu
            anchorEl={anchorEl}
            open={Boolean(anchorEl)}
            onClose={handleCloseMenu}
            PaperProps={{
              sx: { minWidth: 320, maxHeight: 400 },
            }}
          >
            <Box sx={{ px: 2, py: 1 }}>
              <Typography variant="subtitle2" color="primary">
                Seleziona Dataset
              </Typography>
              <Typography variant="caption" color="text.secondary">
                I dataset determinano quali dati sono disponibili nel report
              </Typography>
            </Box>
            <Divider />

            {categoryOrder.map((category) => {
              const datasets = groupedDatasets[category];
              if (!datasets || datasets.length === 0) return null;

              return (
                <Box key={category}>
                  <ListSubheader
                    sx={{
                      bgcolor: "grey.100",
                      lineHeight: "32px",
                      fontSize: "0.75rem",
                      fontWeight: 600,
                      color: "text.secondary",
                    }}
                  >
                    {category}
                    {category === "Personalizzato" && (
                      <Chip
                        label="Virtual"
                        size="small"
                        color="info"
                        sx={{ ml: 1, height: 18, fontSize: "0.65rem" }}
                      />
                    )}
                  </ListSubheader>
                  {datasets.map((dataset) => (
                    <MenuItem
                      key={dataset.id}
                      onClick={() => handleSelectDataset(dataset)}
                      onMouseEnter={() => setHoveredDataset(dataset)}
                      onMouseLeave={() => setHoveredDataset(null)}
                      sx={{
                        py: 1,
                        bgcolor:
                          hoveredDataset?.id === dataset.id
                            ? "action.hover"
                            : "inherit",
                      }}
                    >
                      <ListItemIcon
                        sx={{
                          color: `${getCategoryColor(dataset.category, dataset.isVirtual)}.main`,
                        }}
                      >
                        {getDatasetIcon(dataset.icon)}
                      </ListItemIcon>
                      <ListItemText
                        primary={
                          <Box
                            sx={{
                              display: "flex",
                              alignItems: "center",
                              gap: 1,
                            }}
                          >
                            {dataset.name}
                            {dataset.isVirtual && (
                              <Chip
                                label="Virtual"
                                size="small"
                                color="info"
                                sx={{ height: 16, fontSize: "0.6rem" }}
                              />
                            )}
                          </Box>
                        }
                        secondary={dataset.description}
                        primaryTypographyProps={{
                          variant: "body2",
                          fontWeight: 500,
                          component: "div",
                        }}
                        secondaryTypographyProps={{
                          variant: "caption",
                          sx: {
                            display: "-webkit-box",
                            WebkitLineClamp: 2,
                            WebkitBoxOrient: "vertical",
                            overflow: "hidden",
                          },
                        }}
                      />
                    </MenuItem>
                  ))}
                </Box>
              );
            })}

            {/* Link to dataset manager */}
            {onOpenDatasetManager && [
              <Divider key="divider-manager" />,
              <MenuItem
                key="menu-item-manager"
                onClick={() => {
                  handleCloseMenu();
                  onOpenDatasetManager();
                }}
              >
                <ListItemIcon>
                  <SettingsIcon fontSize="small" />
                </ListItemIcon>
                <ListItemText
                  primary="Gestisci Dataset Virtuali"
                  secondary="Crea e modifica dataset personalizzati"
                  primaryTypographyProps={{
                    variant: "body2",
                    fontWeight: 500,
                  }}
                  secondaryTypographyProps={{ variant: "caption" }}
                />
              </MenuItem>,
            ]}
          </Menu>
        </>
      )}

      {/* Dataset Manager Button */}
      {onOpenDatasetManager && !isTablet && (
        <Tooltip title="Gestisci Dataset Virtuali">
          <Button
            size="small"
            variant="outlined"
            startIcon={<DatasetIcon />}
            onClick={onOpenDatasetManager}
            sx={{ ml: "auto" }}
          >
            Dataset Virtuali
            {virtualDatasetCount > 0 && (
              <Chip
                label={virtualDatasetCount}
                size="small"
                color="info"
                sx={{ ml: 1, height: 18, minWidth: 18, fontSize: "0.65rem" }}
              />
            )}
          </Button>
        </Tooltip>
      )}

      {/* Tablet: Compact manager button */}
      {onOpenDatasetManager && isTablet && (
        <Tooltip title="Gestisci Dataset Virtuali">
          <IconButton
            size="small"
            onClick={onOpenDatasetManager}
            sx={{ ml: "auto" }}
          >
            <SettingsIcon fontSize="small" />
          </IconButton>
        </Tooltip>
      )}

      {/* Info sui dataset selezionati */}
      {selectedDatasets.length > 0 && !onOpenDatasetManager && (
        <Tooltip
          title={
            <Box>
              <Typography variant="caption" fontWeight={600}>
                Dataset selezionati:
              </Typography>
              {selectedDatasets.map((ds) => (
                <Typography key={ds.id} variant="caption" display="block">
                  • {ds.name}: {ds.description}
                </Typography>
              ))}
            </Box>
          }
        >
          <IconButton size="small" sx={{ ml: "auto" }}>
            <InfoIcon fontSize="small" color="action" />
          </IconButton>
        </Tooltip>
      )}
    </Box>
  );
}
