import { useState } from "react";
import {
  Box,
  Typography,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Slider,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  ToggleButton,
  ToggleButtonGroup,
  Divider,
  InputAdornment,
  IconButton,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  Button,
  Chip,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import {
  ExpandMore as ExpandMoreIcon,
  FormatBold as BoldIcon,
  FormatItalic as ItalicIcon,
  FormatAlignLeft as AlignLeftIcon,
  FormatAlignCenter as AlignCenterIcon,
  FormatAlignRight as AlignRightIcon,
  FormatAlignJustify as JustifyIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  DragIndicator as DragIcon,
  Image as ImageIcon,
  AspectRatio as AspectRatioIcon,
  FlipToFront as FlipHIcon,
  FlipToBack as FlipVIcon,
  Upload as UploadIcon,
} from "@mui/icons-material";
import type {
  AprtElement,
  AprtPage,
  AprtStyle,
  AprtContent,
  AprtImageSettings,
  PageSize,
  PageOrientation,
  AprtMargins,
  AprtTableColumn,
  DataSchemaDto,
  DatasetTypeDto,
} from "../../types/report";
import { defaultImageSettings } from "../../types/report";

interface PropertiesPanelProps {
  element: AprtElement | null;
  onUpdateElement: (updates: Partial<AprtElement>) => void;
  // Page settings (effective values - from current page or template defaults)
  pageSize?: PageSize;
  orientation?: PageOrientation;
  margins?: AprtMargins;
  onUpdatePage?: (updates: {
    pageSize?: PageSize;
    orientation?: PageOrientation;
    margins?: AprtMargins;
  }) => void;
  fontFamilies: string[];
  // Dataset info for table configuration
  availableDatasets?: DatasetTypeDto[];
  dataSchemas?: Record<string, DataSchemaDto>;
  // Image upload
  onOpenImageUpload?: () => void;
  // Current page for page-specific settings
  currentPage?: AprtPage;
  onUpdateCurrentPage?: (updates: Partial<AprtPage>) => void;
  /** When true, hides borders (used inside CollapsiblePanel) */
  embedded?: boolean;
}

export default function PropertiesPanel({
  element,
  onUpdateElement,
  pageSize,
  orientation,
  margins,
  onUpdatePage,
  fontFamilies,
  availableDatasets = [],
  dataSchemas = {},
  onOpenImageUpload,
  currentPage,
  onUpdateCurrentPage,
  embedded = false,
}: PropertiesPanelProps) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

  const [expanded, setExpanded] = useState<string[]>([
    "position",
    "style",
    "content",
  ]);

  const handleAccordion =
    (panel: string) => (_: unknown, isExpanded: boolean) => {
      setExpanded((prev) =>
        isExpanded ? [...prev, panel] : prev.filter((p) => p !== panel),
      );
    };

  const updatePosition = (key: string, value: number) => {
    if (!element) return;
    onUpdateElement({
      position: { ...element.position, [key]: value },
    });
  };

  const updateStyle = (key: keyof AprtStyle, value: unknown) => {
    if (!element) return;
    onUpdateElement({
      style: { ...element.style, [key]: value },
    });
  };

  const updateContent = (key: keyof AprtContent, value: unknown) => {
    if (!element) return;
    onUpdateElement({
      content: { ...element.content, [key]: value } as AprtContent,
    });
  };

  const updateImageSettings = (
    key: keyof AprtImageSettings,
    value: unknown,
  ) => {
    if (!element) return;
    const currentSettings = element.imageSettings || defaultImageSettings;
    onUpdateElement({
      imageSettings: { ...currentSettings, [key]: value } as AprtImageSettings,
    });
  };

  // Special handler for maintainAspectRatio toggle
  // When switching to YES, correct the dimensions to match original aspect ratio
  const handleMaintainAspectRatioChange = (maintainAspectRatio: boolean) => {
    if (!element || element.type !== "image") return;

    const currentSettings = element.imageSettings || defaultImageSettings;

    if (
      maintainAspectRatio &&
      currentSettings.originalWidth &&
      currentSettings.originalHeight
    ) {
      // Calculate original aspect ratio
      const originalAspect =
        currentSettings.originalWidth / currentSettings.originalHeight;

      // Current width - we'll adjust height to match aspect ratio
      const currentWidth = element.position.width;

      // Correct height based on current width to maintain aspect ratio
      const correctedHeight = currentWidth / originalAspect;

      // Update both imageSettings and position
      onUpdateElement({
        imageSettings: { ...currentSettings, maintainAspectRatio: true },
        position: {
          ...element.position,
          height: Math.round(correctedHeight * 100) / 100, // Round to 2 decimals
        },
      });
    } else {
      // Just update the setting without changing dimensions
      onUpdateElement({
        imageSettings: { ...currentSettings, maintainAspectRatio },
      });
    }
  };

  // Panel width based on context (full width when embedded)
  const panelWidth = embedded ? "100%" : isMobile ? "100%" : 280;

  if (!element) {
    // Show page settings when no element selected
    return (
      <Box
        sx={{
          width: panelWidth,
          minWidth: embedded ? undefined : isMobile ? undefined : 280,
          borderLeft: embedded ? 0 : isMobile ? 0 : 1,
          borderColor: "divider",
          p: 2,
          overflow: "auto",
          height: "100%",
          // Hide scrollbar but keep functionality
          "&::-webkit-scrollbar": {
            width: 0,
            background: "transparent",
          },
          scrollbarWidth: "none", // Firefox
          msOverflowStyle: "none", // IE/Edge
        }}
      >
        {!isMobile && !embedded && (
          <Typography variant="subtitle2" color="primary" gutterBottom>
            {currentPage
              ? `Pagina: ${currentPage.name}`
              : "Impostazioni Pagina"}
          </Typography>
        )}

        <Box
          display="flex"
          flexDirection="column"
          gap={2}
          mt={isMobile ? 0 : 2}
        >
          {/* Page name (only if currentPage is available) */}
          {currentPage && onUpdateCurrentPage && (
            <>
              <TextField
                label="Nome Pagina"
                size="small"
                value={currentPage.name}
                onChange={(e) => onUpdateCurrentPage({ name: e.target.value })}
                fullWidth
              />
              <Divider />
            </>
          )}

          <FormControl fullWidth size="small">
            <InputLabel>Formato</InputLabel>
            <Select
              value={pageSize || "A4"}
              label="Formato"
              onChange={(e) => {
                const newPageSize = e.target.value as PageSize;
                if (currentPage && onUpdateCurrentPage) {
                  onUpdateCurrentPage({ pageSize: newPageSize });
                } else {
                  onUpdatePage?.({ pageSize: newPageSize });
                }
              }}
            >
              <MenuItem value="A4">A4</MenuItem>
              <MenuItem value="A3">A3</MenuItem>
              <MenuItem value="A5">A5</MenuItem>
              <MenuItem value="Letter">Letter</MenuItem>
              <MenuItem value="Legal">Legal</MenuItem>
            </Select>
          </FormControl>

          <FormControl fullWidth size="small">
            <InputLabel>Orientamento</InputLabel>
            <Select
              value={orientation || "portrait"}
              label="Orientamento"
              onChange={(e) => {
                const newOrientation = e.target.value as PageOrientation;
                if (currentPage && onUpdateCurrentPage) {
                  onUpdateCurrentPage({ orientation: newOrientation });
                } else {
                  onUpdatePage?.({ orientation: newOrientation });
                }
              }}
            >
              <MenuItem value="portrait">Verticale</MenuItem>
              <MenuItem value="landscape">Orizzontale</MenuItem>
            </Select>
          </FormControl>

          <Divider />

          <Typography variant="caption" color="text.secondary">
            Margini (mm)
          </Typography>

          <Box display="grid" gridTemplateColumns="1fr 1fr" gap={1}>
            <TextField
              label="Sopra"
              type="number"
              size="small"
              value={margins?.top || 20}
              onChange={(e) => {
                const newMargins = { ...margins!, top: Number(e.target.value) };
                if (currentPage && onUpdateCurrentPage) {
                  onUpdateCurrentPage({ margins: newMargins });
                } else {
                  onUpdatePage?.({ margins: newMargins });
                }
              }}
            />
            <TextField
              label="Sotto"
              type="number"
              size="small"
              value={margins?.bottom || 20}
              onChange={(e) => {
                const newMargins = {
                  ...margins!,
                  bottom: Number(e.target.value),
                };
                if (currentPage && onUpdateCurrentPage) {
                  onUpdateCurrentPage({ margins: newMargins });
                } else {
                  onUpdatePage?.({ margins: newMargins });
                }
              }}
            />
            <TextField
              label="Sinistra"
              type="number"
              size="small"
              value={margins?.left || 15}
              onChange={(e) => {
                const newMargins = {
                  ...margins!,
                  left: Number(e.target.value),
                };
                if (currentPage && onUpdateCurrentPage) {
                  onUpdateCurrentPage({ margins: newMargins });
                } else {
                  onUpdatePage?.({ margins: newMargins });
                }
              }}
            />
            <TextField
              label="Destra"
              type="number"
              size="small"
              value={margins?.right || 15}
              onChange={(e) => {
                const newMargins = {
                  ...margins!,
                  right: Number(e.target.value),
                };
                if (currentPage && onUpdateCurrentPage) {
                  onUpdateCurrentPage({ margins: newMargins });
                } else {
                  onUpdatePage?.({ margins: newMargins });
                }
              }}
            />
          </Box>

          {/* Background color for current page */}
          {currentPage && onUpdateCurrentPage && (
            <>
              <Divider />
              <Box>
                <Typography variant="caption" color="text.secondary">
                  Colore Sfondo
                </Typography>
                <input
                  type="color"
                  value={currentPage.backgroundColor || "#ffffff"}
                  onChange={(e) =>
                    onUpdateCurrentPage({ backgroundColor: e.target.value })
                  }
                  style={{
                    width: "100%",
                    height: 32,
                    border: "none",
                    cursor: "pointer",
                    marginTop: 4,
                  }}
                />
              </Box>
            </>
          )}
        </Box>
      </Box>
    );
  }

  return (
    <Box
      sx={{
        width: panelWidth,
        minWidth: embedded ? undefined : isMobile ? undefined : 280,
        borderLeft: embedded ? 0 : isMobile ? 0 : 1,
        borderColor: "divider",
        overflow: "auto",
        height: "100%",
        // Hide scrollbar but keep functionality
        "&::-webkit-scrollbar": {
          width: 0,
          background: "transparent",
        },
        scrollbarWidth: "none", // Firefox
        msOverflowStyle: "none", // IE/Edge
      }}
    >
      {/* Element header - show only when not embedded (CollapsiblePanel has its own header) */}
      {!embedded && (
        <Box sx={{ p: 2, borderBottom: 1, borderColor: "divider" }}>
          <Typography variant="subtitle2" color="primary">
            {element.name || `Elemento ${element.type}`}
          </Typography>
          <Typography variant="caption" color="text.secondary">
            {element.type.toUpperCase()} - ID: {element.id.slice(0, 8)}
          </Typography>
        </Box>
      )}

      {/* Position */}
      <Accordion
        expanded={expanded.includes("position")}
        onChange={handleAccordion("position")}
        disableGutters
        sx={{ "&:before": { display: "none" } }}
      >
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle2">Posizione</Typography>
        </AccordionSummary>
        <AccordionDetails sx={{ pt: 0 }}>
          <Box display="grid" gridTemplateColumns="1fr 1fr" gap={1}>
            <TextField
              label="X"
              type="number"
              size="small"
              value={Math.round(element.position.x * 10) / 10}
              onChange={(e) => updatePosition("x", Number(e.target.value))}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">mm</InputAdornment>
                ),
              }}
            />
            <TextField
              label="Y"
              type="number"
              size="small"
              value={Math.round(element.position.y * 10) / 10}
              onChange={(e) => updatePosition("y", Number(e.target.value))}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">mm</InputAdornment>
                ),
              }}
            />
            <TextField
              label="Larghezza"
              type="number"
              size="small"
              value={Math.round(element.position.width * 10) / 10}
              onChange={(e) => updatePosition("width", Number(e.target.value))}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">mm</InputAdornment>
                ),
              }}
            />
            <TextField
              label="Altezza"
              type="number"
              size="small"
              value={Math.round(element.position.height * 10) / 10}
              onChange={(e) => updatePosition("height", Number(e.target.value))}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">mm</InputAdornment>
                ),
              }}
            />
            <TextField
              label="Rotazione"
              type="number"
              size="small"
              value={element.position.rotation || 0}
              onChange={(e) =>
                updatePosition("rotation", Number(e.target.value))
              }
              InputProps={{
                endAdornment: <InputAdornment position="end">°</InputAdornment>,
              }}
              sx={{ gridColumn: "span 2" }}
            />
          </Box>
        </AccordionDetails>
      </Accordion>

      {/* Style */}
      {(element.type === "text" || element.type === "shape") && (
        <Accordion
          expanded={expanded.includes("style")}
          onChange={handleAccordion("style")}
          disableGutters
          sx={{ "&:before": { display: "none" } }}
        >
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography variant="subtitle2">Stile</Typography>
          </AccordionSummary>
          <AccordionDetails sx={{ pt: 0 }}>
            <Box display="flex" flexDirection="column" gap={2}>
              {element.type === "text" && (
                <>
                  <FormControl fullWidth size="small">
                    <InputLabel>Font</InputLabel>
                    <Select
                      value={element.style.fontFamily}
                      label="Font"
                      onChange={(e) =>
                        updateStyle("fontFamily", e.target.value)
                      }
                    >
                      {fontFamilies.map((font) => (
                        <MenuItem key={font} value={font}>
                          {font}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>

                  <Box
                    display="flex"
                    gap={1}
                    alignItems="center"
                    flexWrap="wrap"
                  >
                    <TextField
                      label="Dimensione"
                      type="number"
                      size="small"
                      value={element.style.fontSize}
                      onChange={(e) =>
                        updateStyle("fontSize", Number(e.target.value))
                      }
                      sx={{ width: isMobile ? "100%" : 100 }}
                    />
                    <ToggleButtonGroup size="small">
                      <ToggleButton
                        value="bold"
                        selected={element.style.fontWeight === "bold"}
                        onChange={() =>
                          updateStyle(
                            "fontWeight",
                            element.style.fontWeight === "bold"
                              ? "normal"
                              : "bold",
                          )
                        }
                      >
                        <BoldIcon />
                      </ToggleButton>
                      <ToggleButton
                        value="italic"
                        selected={element.style.fontStyle === "italic"}
                        onChange={() =>
                          updateStyle(
                            "fontStyle",
                            element.style.fontStyle === "italic"
                              ? "normal"
                              : "italic",
                          )
                        }
                      >
                        <ItalicIcon />
                      </ToggleButton>
                    </ToggleButtonGroup>
                  </Box>

                  <Box>
                    <Typography variant="caption" gutterBottom>
                      Allineamento
                    </Typography>
                    <ToggleButtonGroup
                      value={element.style.textAlign}
                      exclusive
                      onChange={(_, value) =>
                        value && updateStyle("textAlign", value)
                      }
                      size="small"
                      fullWidth
                    >
                      <ToggleButton value="left">
                        <AlignLeftIcon />
                      </ToggleButton>
                      <ToggleButton value="center">
                        <AlignCenterIcon />
                      </ToggleButton>
                      <ToggleButton value="right">
                        <AlignRightIcon />
                      </ToggleButton>
                      <ToggleButton value="justify">
                        <JustifyIcon />
                      </ToggleButton>
                    </ToggleButtonGroup>
                  </Box>
                </>
              )}

              <Box display="flex" gap={1}>
                <Box flex={1}>
                  <Typography variant="caption">Colore</Typography>
                  <input
                    type="color"
                    value={element.style.color}
                    onChange={(e) => updateStyle("color", e.target.value)}
                    style={{
                      width: "100%",
                      height: 32,
                      border: "none",
                      cursor: "pointer",
                    }}
                  />
                </Box>
                <Box flex={1}>
                  <Typography variant="caption">Sfondo</Typography>
                  <input
                    type="color"
                    value={element.style.backgroundColor || "#ffffff"}
                    onChange={(e) =>
                      updateStyle("backgroundColor", e.target.value)
                    }
                    style={{
                      width: "100%",
                      height: 32,
                      border: "none",
                      cursor: "pointer",
                    }}
                  />
                </Box>
              </Box>

              <Box>
                <Typography variant="caption">
                  Opacità: {Math.round(element.style.opacity * 100)}%
                </Typography>
                <Slider
                  value={element.style.opacity}
                  min={0}
                  max={1}
                  step={0.1}
                  onChange={(_, value) => updateStyle("opacity", value)}
                  size="small"
                />
              </Box>

              <Box display="flex" gap={1} flexWrap="wrap">
                <TextField
                  label="Bordo"
                  type="number"
                  size="small"
                  value={element.style.borderWidth}
                  onChange={(e) =>
                    updateStyle("borderWidth", Number(e.target.value))
                  }
                  sx={{ width: 80 }}
                />
                <Box flex={1} minWidth={80}>
                  <Typography variant="caption">Colore Bordo</Typography>
                  <input
                    type="color"
                    value={element.style.borderColor}
                    onChange={(e) => updateStyle("borderColor", e.target.value)}
                    style={{
                      width: "100%",
                      height: 32,
                      border: "none",
                      cursor: "pointer",
                    }}
                  />
                </Box>
              </Box>
            </Box>
          </AccordionDetails>
        </Accordion>
      )}

      {/* Image Settings */}
      {element.type === "image" && (
        <Accordion
          expanded={expanded.includes("image")}
          onChange={handleAccordion("image")}
          disableGutters
          sx={{ "&:before": { display: "none" } }}
        >
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography variant="subtitle2">Immagine</Typography>
          </AccordionSummary>
          <AccordionDetails sx={{ pt: 0 }}>
            <Box display="flex" flexDirection="column" gap={2}>
              {/* Image Preview or Upload Button */}
              {element.imageSettings?.src ? (
                <Box>
                  <Box
                    sx={{
                      width: "100%",
                      height: isMobile ? 100 : 120,
                      bgcolor: "grey.100",
                      borderRadius: 1,
                      overflow: "hidden",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      mb: 1,
                    }}
                  >
                    <img
                      src={element.imageSettings.src}
                      alt="Preview"
                      style={{
                        maxWidth: "100%",
                        maxHeight: "100%",
                        objectFit: "contain",
                      }}
                    />
                  </Box>
                  <Box display="flex" gap={1}>
                    <Button
                      variant="outlined"
                      size="small"
                      fullWidth
                      startIcon={<UploadIcon />}
                      onClick={onOpenImageUpload}
                    >
                      Cambia
                    </Button>
                    <Button
                      variant="outlined"
                      size="small"
                      color="error"
                      onClick={() => updateImageSettings("src", undefined)}
                    >
                      <DeleteIcon fontSize="small" />
                    </Button>
                  </Box>
                  {element.imageSettings.originalWidth && (
                    <Typography variant="caption" color="text.secondary" mt={1}>
                      Originale: {element.imageSettings.originalWidth} ×{" "}
                      {element.imageSettings.originalHeight} px
                    </Typography>
                  )}
                </Box>
              ) : (
                <Button
                  variant="outlined"
                  fullWidth
                  startIcon={<ImageIcon />}
                  onClick={onOpenImageUpload}
                  sx={{ py: 2 }}
                >
                  Seleziona Immagine
                </Button>
              )}

              <Divider />

              {/* Fit Mode */}
              <FormControl fullWidth size="small">
                <InputLabel>Adattamento</InputLabel>
                <Select
                  value={element.imageSettings?.fitMode || "contain"}
                  label="Adattamento"
                  onChange={(e) =>
                    updateImageSettings("fitMode", e.target.value)
                  }
                >
                  <MenuItem value="contain">Adatta (contain)</MenuItem>
                  <MenuItem value="cover">Riempi (cover)</MenuItem>
                  <MenuItem value="fill">Stretch (fill)</MenuItem>
                  <MenuItem value="none">Nessuno (none)</MenuItem>
                </Select>
              </FormControl>

              {/* Maintain Aspect Ratio */}
              <Box
                display="flex"
                alignItems="center"
                justifyContent="space-between"
                flexWrap="wrap"
                gap={1}
              >
                <Box display="flex" alignItems="center" gap={1}>
                  <AspectRatioIcon fontSize="small" color="action" />
                  <Typography variant="body2">Proporzioni</Typography>
                </Box>
                <ToggleButtonGroup
                  size="small"
                  value={
                    element.imageSettings?.maintainAspectRatio !== false
                      ? "yes"
                      : "no"
                  }
                  exclusive
                  onChange={(_, value) =>
                    value && handleMaintainAspectRatioChange(value === "yes")
                  }
                >
                  <ToggleButton value="yes" sx={{ px: 1.5 }}>
                    Sì
                  </ToggleButton>
                  <ToggleButton value="no" sx={{ px: 1.5 }}>
                    No
                  </ToggleButton>
                </ToggleButtonGroup>
              </Box>

              {/* Opacity */}
              <Box>
                <Typography variant="caption">
                  Opacità:{" "}
                  {Math.round((element.imageSettings?.opacity ?? 1) * 100)}%
                </Typography>
                <Slider
                  value={element.imageSettings?.opacity ?? 1}
                  min={0}
                  max={1}
                  step={0.05}
                  onChange={(_, value) => updateImageSettings("opacity", value)}
                  size="small"
                />
              </Box>

              {/* Border Radius */}
              <Box>
                <Typography variant="caption">
                  Angoli arrotondati: {element.imageSettings?.borderRadius || 0}
                  px
                </Typography>
                <Slider
                  value={element.imageSettings?.borderRadius || 0}
                  min={0}
                  max={50}
                  step={1}
                  onChange={(_, value) =>
                    updateImageSettings("borderRadius", value)
                  }
                  size="small"
                />
              </Box>

              {/* Flip Options */}
              <Box display="flex" gap={1}>
                <Button
                  variant={
                    element.imageSettings?.flipHorizontal
                      ? "contained"
                      : "outlined"
                  }
                  size="small"
                  startIcon={<FlipHIcon />}
                  onClick={() =>
                    updateImageSettings(
                      "flipHorizontal",
                      !element.imageSettings?.flipHorizontal,
                    )
                  }
                  sx={{ flex: 1 }}
                >
                  Flip H
                </Button>
                <Button
                  variant={
                    element.imageSettings?.flipVertical
                      ? "contained"
                      : "outlined"
                  }
                  size="small"
                  startIcon={<FlipVIcon />}
                  onClick={() =>
                    updateImageSettings(
                      "flipVertical",
                      !element.imageSettings?.flipVertical,
                    )
                  }
                  sx={{ flex: 1 }}
                >
                  Flip V
                </Button>
              </Box>
            </Box>
          </AccordionDetails>
        </Accordion>
      )}

      {/* Content */}
      {element.type === "text" && (
        <Accordion
          expanded={expanded.includes("content")}
          onChange={handleAccordion("content")}
          disableGutters
          sx={{ "&:before": { display: "none" } }}
        >
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography variant="subtitle2">Contenuto</Typography>
          </AccordionSummary>
          <AccordionDetails sx={{ pt: 0 }}>
            <Box display="flex" flexDirection="column" gap={2}>
              <FormControl fullWidth size="small">
                <InputLabel>Tipo</InputLabel>
                <Select
                  value={element.content?.type || "static"}
                  label="Tipo"
                  onChange={(e) => updateContent("type", e.target.value)}
                >
                  <MenuItem value="static">Testo Statico</MenuItem>
                  <MenuItem value="binding">Campo Dati</MenuItem>
                  <MenuItem value="expression">Espressione</MenuItem>
                </Select>
              </FormControl>

              {element.content?.type === "static" && (
                <TextField
                  label="Testo"
                  multiline
                  rows={3}
                  size="small"
                  value={element.content?.value || ""}
                  onChange={(e) => updateContent("value", e.target.value)}
                />
              )}

              {element.content?.type === "binding" && (
                <TextField
                  label="Campo"
                  size="small"
                  placeholder="{{evento.codice}}"
                  value={element.content?.expression || ""}
                  onChange={(e) => updateContent("expression", e.target.value)}
                  helperText={isMobile ? undefined : "Es: {{evento.codice}}"}
                />
              )}

              {element.content?.type === "expression" && (
                <TextField
                  label="Espressione"
                  multiline
                  rows={2}
                  size="small"
                  placeholder="Pagina {{$pageNumber}} di {{$totalPages}}"
                  value={element.content?.value || ""}
                  onChange={(e) => updateContent("value", e.target.value)}
                />
              )}

              {element.content?.type === "binding" && (
                <FormControl fullWidth size="small">
                  <InputLabel>Formato</InputLabel>
                  <Select
                    value={element.content?.format || ""}
                    label="Formato"
                    onChange={(e) =>
                      updateContent("format", e.target.value || undefined)
                    }
                  >
                    <MenuItem value="">Nessuno</MenuItem>
                    <MenuItem value="currency">Valuta (€)</MenuItem>
                    <MenuItem value="date">Data</MenuItem>
                    <MenuItem value="datetime">Data e Ora</MenuItem>
                    <MenuItem value="number">Numero</MenuItem>
                    <MenuItem value="percent">Percentuale</MenuItem>
                  </Select>
                </FormControl>
              )}
            </Box>
          </AccordionDetails>
        </Accordion>
      )}

      {/* Section */}
      <Accordion
        expanded={expanded.includes("section")}
        onChange={handleAccordion("section")}
        disableGutters
        sx={{ "&:before": { display: "none" } }}
      >
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Typography variant="subtitle2">Sezione</Typography>
        </AccordionSummary>
        <AccordionDetails sx={{ pt: 0 }}>
          <FormControl fullWidth size="small">
            <InputLabel>Sezione</InputLabel>
            <Select
              value={element.section || "body"}
              label="Sezione"
              onChange={(e) =>
                onUpdateElement({
                  section: e.target.value as "header" | "body" | "footer",
                })
              }
            >
              <MenuItem value="header">Intestazione</MenuItem>
              <MenuItem value="body">Corpo</MenuItem>
              <MenuItem value="footer">Piè di pagina</MenuItem>
            </Select>
          </FormControl>
        </AccordionDetails>
      </Accordion>

      {/* Table Configuration - only for table elements */}
      {element.type === "table" && (
        <Accordion
          expanded={expanded.includes("table")}
          onChange={handleAccordion("table")}
          disableGutters
          sx={{ "&:before": { display: "none" } }}
        >
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography variant="subtitle2">Configurazione Tabella</Typography>
          </AccordionSummary>
          <AccordionDetails sx={{ pt: 0 }}>
            <Box display="flex" flexDirection="column" gap={2}>
              {/* Data Source Selection */}
              <FormControl fullWidth size="small">
                <InputLabel>Sorgente Dati</InputLabel>
                <Select
                  value={element.dataSource || ""}
                  label="Sorgente Dati"
                  onChange={(e) =>
                    onUpdateElement({ dataSource: e.target.value || undefined })
                  }
                >
                  <MenuItem value="">
                    <em>Nessuna (tabella statica)</em>
                  </MenuItem>
                  {availableDatasets.map((ds) => (
                    <MenuItem key={ds.id} value={ds.id}>
                      <Box display="flex" alignItems="center" gap={1}>
                        {ds.name}
                        {ds.isVirtual && (
                          <Chip
                            label="Virtual"
                            size="small"
                            color="info"
                            sx={{ height: 16, fontSize: "0.6rem" }}
                          />
                        )}
                      </Box>
                    </MenuItem>
                  ))}
                  {/* Add collection fields from schemas */}
                  {Object.entries(dataSchemas).map(([datasetId, schema]) =>
                    schema.fields
                      .filter((f) => f.type === "collection")
                      .map((field) => (
                        <MenuItem
                          key={`${datasetId}.${field.name}`}
                          value={`${datasetId}.${field.name}`}
                        >
                          <Box display="flex" alignItems="center" gap={1}>
                            {schema.datasetName || datasetId}:{" "}
                            {field.displayName || field.label}
                            <Chip
                              label="Collection"
                              size="small"
                              color="secondary"
                              sx={{ height: 16, fontSize: "0.6rem" }}
                            />
                          </Box>
                        </MenuItem>
                      )),
                  )}
                </Select>
              </FormControl>

              {/* Columns Configuration */}
              <Box>
                <Box
                  display="flex"
                  justifyContent="space-between"
                  alignItems="center"
                  mb={1}
                >
                  <Typography variant="caption" color="text.secondary">
                    Colonne ({element.columns?.length || 0})
                  </Typography>
                  <IconButton
                    size="small"
                    onClick={() => {
                      const newColumn: AprtTableColumn = {
                        field: "",
                        header: "Nuova Colonna",
                        width: 50,
                        align: "left",
                      };
                      onUpdateElement({
                        columns: [...(element.columns || []), newColumn],
                      });
                    }}
                  >
                    <AddIcon fontSize="small" />
                  </IconButton>
                </Box>

                <List dense sx={{ bgcolor: "grey.50", borderRadius: 1 }}>
                  {(element.columns || []).map((col, idx) => (
                    <ListItem
                      key={idx}
                      sx={{
                        borderBottom:
                          idx < (element.columns?.length || 0) - 1 ? 1 : 0,
                        borderColor: "divider",
                      }}
                    >
                      <DragIcon
                        fontSize="small"
                        sx={{ color: "text.disabled", mr: 1, cursor: "grab" }}
                      />
                      <ListItemText
                        primary={col.header || "(senza nome)"}
                        secondary={col.field || "(nessun campo)"}
                        primaryTypographyProps={{ variant: "body2" }}
                        secondaryTypographyProps={{ variant: "caption" }}
                      />
                      <ListItemSecondaryAction>
                        <IconButton
                          edge="end"
                          size="small"
                          onClick={() => {
                            const newColumns = [...(element.columns || [])];
                            newColumns.splice(idx, 1);
                            onUpdateElement({ columns: newColumns });
                          }}
                        >
                          <DeleteIcon fontSize="small" />
                        </IconButton>
                      </ListItemSecondaryAction>
                    </ListItem>
                  ))}
                  {(!element.columns || element.columns.length === 0) && (
                    <ListItem>
                      <ListItemText
                        primary="Nessuna colonna"
                        secondary="Clicca + per aggiungere"
                        primaryTypographyProps={{
                          variant: "body2",
                          color: "text.secondary",
                        }}
                      />
                    </ListItem>
                  )}
                </List>
              </Box>

              {/* Column Editor - show when a column exists */}
              {element.columns && element.columns.length > 0 && (
                <Box>
                  <Typography variant="caption" color="text.secondary" mb={1}>
                    Modifica Colonne
                  </Typography>
                  {element.columns.map((col, idx) => (
                    <Box
                      key={idx}
                      sx={{
                        p: 1,
                        mb: 1,
                        border: 1,
                        borderColor: "divider",
                        borderRadius: 1,
                      }}
                    >
                      <Typography
                        variant="caption"
                        fontWeight="bold"
                        color="primary"
                      >
                        Colonna {idx + 1}
                      </Typography>
                      <Box
                        display="grid"
                        gridTemplateColumns="1fr 1fr"
                        gap={1}
                        mt={1}
                      >
                        <TextField
                          label="Intestazione"
                          size="small"
                          value={col.header}
                          onChange={(e) => {
                            const newColumns = [...element.columns!];
                            newColumns[idx] = {
                              ...newColumns[idx],
                              header: e.target.value,
                            };
                            onUpdateElement({ columns: newColumns });
                          }}
                        />
                        <TextField
                          label="Campo"
                          size="small"
                          placeholder="{{campo}}"
                          value={col.field}
                          onChange={(e) => {
                            const newColumns = [...element.columns!];
                            newColumns[idx] = {
                              ...newColumns[idx],
                              field: e.target.value,
                            };
                            onUpdateElement({ columns: newColumns });
                          }}
                        />
                        <TextField
                          label="Larghezza"
                          size="small"
                          type="number"
                          value={col.width}
                          onChange={(e) => {
                            const newColumns = [...element.columns!];
                            newColumns[idx] = {
                              ...newColumns[idx],
                              width: Number(e.target.value),
                            };
                            onUpdateElement({ columns: newColumns });
                          }}
                          InputProps={{
                            endAdornment: (
                              <InputAdornment position="end">mm</InputAdornment>
                            ),
                          }}
                        />
                        <FormControl size="small">
                          <InputLabel>Allineamento</InputLabel>
                          <Select
                            value={col.align || "left"}
                            label="Allineamento"
                            onChange={(e) => {
                              const newColumns = [...element.columns!];
                              newColumns[idx] = {
                                ...newColumns[idx],
                                align: e.target.value as
                                  | "left"
                                  | "center"
                                  | "right",
                              };
                              onUpdateElement({ columns: newColumns });
                            }}
                          >
                            <MenuItem value="left">Sinistra</MenuItem>
                            <MenuItem value="center">Centro</MenuItem>
                            <MenuItem value="right">Destra</MenuItem>
                          </Select>
                        </FormControl>
                        <FormControl size="small" sx={{ gridColumn: "span 2" }}>
                          <InputLabel>Formato</InputLabel>
                          <Select
                            value={col.format || ""}
                            label="Formato"
                            onChange={(e) => {
                              const newColumns = [...element.columns!];
                              newColumns[idx] = {
                                ...newColumns[idx],
                                format: e.target.value || undefined,
                              };
                              onUpdateElement({ columns: newColumns });
                            }}
                          >
                            <MenuItem value="">Nessuno</MenuItem>
                            <MenuItem value="currency">Valuta (€)</MenuItem>
                            <MenuItem value="date">Data</MenuItem>
                            <MenuItem value="datetime">Data e Ora</MenuItem>
                            <MenuItem value="number">Numero</MenuItem>
                            <MenuItem value="percent">Percentuale</MenuItem>
                          </Select>
                        </FormControl>
                      </Box>
                    </Box>
                  ))}
                </Box>
              )}

              {/* Auto-populate columns from schema */}
              {element.dataSource && (
                <Button
                  variant="outlined"
                  size="small"
                  startIcon={<AddIcon />}
                  onClick={() => {
                    // Parse dataSource to get schema fields
                    const [datasetId, collectionField] =
                      element.dataSource?.includes(".")
                        ? element.dataSource.split(".")
                        : [element.dataSource, null];

                    const schema = dataSchemas[datasetId!];
                    if (!schema) return;

                    let fields = schema.fields;
                    if (collectionField) {
                      // Find the collection field and use its nested fields
                      const collection = schema.fields.find(
                        (f) => f.name === collectionField,
                      );
                      if (collection?.nestedFields) {
                        fields = collection.nestedFields;
                      } else {
                        // Try childCollections as fallback
                        const childCollection = schema.childCollections?.find(
                          (c) => c.name === collectionField,
                        );
                        if (childCollection?.fields) {
                          fields = childCollection.fields;
                        }
                      }
                    }

                    // Create columns from non-collection fields
                    const newColumns: AprtTableColumn[] = fields
                      .filter(
                        (f) => f.type !== "collection" && f.type !== "object",
                      )
                      .slice(0, 6) // Limit to 6 columns initially
                      .map((f) => ({
                        field: `{{${f.name}}}`,
                        header: f.displayName || f.label,
                        width: f.type === "string" ? 60 : 40,
                        align:
                          f.type === "number" || f.type === "decimal"
                            ? ("right" as const)
                            : ("left" as const),
                        format:
                          f.type === "decimal"
                            ? "number"
                            : f.type === "date"
                              ? "date"
                              : undefined,
                      }));

                    onUpdateElement({ columns: newColumns });
                  }}
                >
                  Auto-genera Colonne
                </Button>
              )}
            </Box>
          </AccordionDetails>
        </Accordion>
      )}
    </Box>
  );
}
