import { useState, useMemo } from "react";
import {
  Box,
  Typography,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Collapse,
  Chip,
  TextField,
  InputAdornment,
  IconButton,
  Tooltip,
  Divider,
  alpha,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import {
  ExpandLess,
  ExpandMore,
  TextFields as TextIcon,
  Numbers as NumberIcon,
  CalendarMonth as DateIcon,
  AttachMoney as CurrencyIcon,
  Percent as PercentIcon,
  TableChart as TableIcon,
  Search as SearchIcon,
  Delete as DeleteIcon,
  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,
  List as ListIcon,
  ContentCopy as CopyIcon,
  CheckCircle as CheckIcon,
} from "@mui/icons-material";
import type {
  DataSchemaDto,
  DataFieldDto,
  DatasetTypeDto,
} from "../../types/report";

interface DataBindingPanelProps {
  schemas: DataSchemaDto[];
  selectedDatasets: DatasetTypeDto[];
  onInsertBinding: (binding: string) => void;
  onRemoveDataset: (datasetId: string) => void;
  /** When true, hides borders (used inside CollapsiblePanel) */
  embedded?: boolean;
}

export default function DataBindingPanel({
  schemas,
  selectedDatasets,
  onInsertBinding,
  onRemoveDataset,
  embedded = false,
}: DataBindingPanelProps) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

  const [expanded, setExpanded] = useState<string[]>(["special"]);
  const [search, setSearch] = useState("");
  const [copiedField, setCopiedField] = useState<string | null>(null);

  const toggleExpand = (key: string) => {
    setExpanded((prev) =>
      prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],
    );
  };

  const getFieldIcon = (type: string) => {
    switch (type) {
      case "currency":
        return <CurrencyIcon fontSize="small" />;
      case "number":
        return <NumberIcon fontSize="small" />;
      case "date":
      case "datetime":
      case "time":
        return <DateIcon fontSize="small" />;
      case "percent":
        return <PercentIcon fontSize="small" />;
      case "boolean":
        return <CheckIcon fontSize="small" />;
      default:
        return <TextIcon fontSize="small" />;
    }
  };

  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" />;
      default:
        return <TableIcon fontSize="small" />;
    }
  };

  const getTypeColor = (
    type: string,
  ): "default" | "primary" | "success" | "warning" | "error" | "info" => {
    switch (type) {
      case "currency":
        return "success";
      case "number":
        return "primary";
      case "date":
      case "datetime":
      case "time":
        return "warning";
      case "percent":
        return "info";
      case "boolean":
        return "error";
      default:
        return "default";
    }
  };

  const filterFields = (fields: DataFieldDto[]) => {
    if (!search) return fields;
    const searchLower = search.toLowerCase();
    return fields.filter(
      (f) =>
        f.name.toLowerCase().includes(searchLower) ||
        f.label.toLowerCase().includes(searchLower),
    );
  };

  // Raggruppa i campi per gruppo
  const groupFields = (fields: DataFieldDto[]) => {
    const filteredFields = filterFields(fields);
    const groups: Record<string, DataFieldDto[]> = {};

    filteredFields.forEach((field) => {
      const group = field.group || "Generale";
      if (!groups[group]) {
        groups[group] = [];
      }
      groups[group].push(field);
    });

    return groups;
  };

  // Create binding with dataset prefix - always include prefix for proper resolution
  const createBinding = (datasetId: string, fieldName: string) => {
    // Always include dataset prefix for proper backend resolution
    return `{{${datasetId}.${fieldName}}}`;
  };

  const handleInsertField = (datasetId: string, fieldName: string) => {
    const binding = createBinding(datasetId, fieldName);
    onInsertBinding(binding);
    setCopiedField(binding);
    setTimeout(() => setCopiedField(null), 1500);
  };

  const handleCopyBinding = (
    e: React.MouseEvent,
    datasetId: string,
    fieldName: string,
  ) => {
    e.stopPropagation();
    const binding = createBinding(datasetId, fieldName);
    navigator.clipboard.writeText(binding);
    setCopiedField(binding);
    setTimeout(() => setCopiedField(null), 1500);
  };

  // Conta i campi filtrati
  const totalFilteredFields = useMemo(() => {
    if (!search) return null;
    let count = 0;
    schemas.forEach((schema) => {
      count += filterFields(schema.fields).length;
      schema.childCollections.forEach((col) => {
        count += filterFields(col.fields).length;
      });
    });
    return count;
  }, [search, schemas]);

  // Panel width based on context (full width when embedded or in mobile drawer)
  const panelWidth = embedded ? "100%" : isMobile ? "100%" : 300;

  if (selectedDatasets.length === 0) {
    return (
      <Box
        sx={{
          width: panelWidth,
          minWidth: embedded ? undefined : isMobile ? undefined : 300,
          borderRight: embedded ? 0 : isMobile ? 0 : 1,
          borderColor: "divider",
          p: 3,
          bgcolor: embedded ? "transparent" : "grey.50",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          textAlign: "center",
          height: "100%",
        }}
      >
        <TableIcon sx={{ fontSize: 48, color: "grey.400", mb: 2 }} />
        <Typography variant="subtitle2" color="text.secondary" gutterBottom>
          Nessun Dataset Selezionato
        </Typography>
        <Typography variant="caption" color="text.secondary">
          Seleziona almeno un dataset dal pannello in alto per vedere i campi
          disponibili da inserire nel report.
        </Typography>
      </Box>
    );
  }

  return (
    <Box
      sx={{
        width: panelWidth,
        minWidth: embedded ? undefined : isMobile ? undefined : 300,
        borderRight: embedded ? 0 : isMobile ? 0 : 1,
        borderColor: "divider",
        display: "flex",
        flexDirection: "column",
        bgcolor: "background.paper",
        height: "100%",
      }}
    >
      {/* Header con ricerca */}
      <Box
        sx={{ p: 2, borderBottom: embedded ? 0 : 1, borderColor: "divider" }}
      >
        {!isMobile && !embedded && (
          <Typography
            variant="subtitle2"
            color="primary"
            gutterBottom
            fontWeight={600}
          >
            Campi Disponibili
          </Typography>
        )}
        <TextField
          placeholder="Cerca campo..."
          size="small"
          fullWidth
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon fontSize="small" />
              </InputAdornment>
            ),
          }}
        />
        {totalFilteredFields !== null && (
          <Typography
            variant="caption"
            color="text.secondary"
            sx={{ mt: 0.5, display: "block" }}
          >
            {totalFilteredFields} campi trovati
          </Typography>
        )}
      </Box>

      {/* Lista campi */}
      <Box
        sx={{
          overflow: "auto",
          flex: 1,
          // Hide scrollbar but keep functionality
          "&::-webkit-scrollbar": {
            width: 0,
            background: "transparent",
          },
          scrollbarWidth: "none", // Firefox
          msOverflowStyle: "none", // IE/Edge
        }}
      >
        {/* Dataset Sections */}
        {schemas.map((schema) => {
          const dataset = selectedDatasets.find(
            (d) => d.id === schema.datasetId,
          );
          const sectionKey = `dataset-${schema.datasetId}`;
          const groupedFields = groupFields(schema.fields);
          const hasFilteredFields = Object.values(groupedFields).some(
            (g) => g.length > 0,
          );

          // Se c'è ricerca e non ci sono risultati, non mostrare il dataset
          if (
            search &&
            !hasFilteredFields &&
            !schema.childCollections.some(
              (c) => filterFields(c.fields).length > 0,
            )
          ) {
            return null;
          }

          return (
            <Box key={schema.datasetId}>
              {/* Dataset Header */}
              <ListItemButton
                onClick={() => toggleExpand(sectionKey)}
                sx={{
                  bgcolor: (theme) => alpha(theme.palette.primary.main, 0.08),
                  "&:hover": {
                    bgcolor: (theme) => alpha(theme.palette.primary.main, 0.12),
                  },
                }}
              >
                <ListItemIcon sx={{ minWidth: 32, color: "primary.main" }}>
                  {dataset && getDatasetIcon(dataset.icon)}
                </ListItemIcon>
                <ListItemText
                  primary={schema.entityType}
                  primaryTypographyProps={{
                    variant: "subtitle2",
                    fontWeight: 600,
                  }}
                />
                <Tooltip title="Rimuovi dataset">
                  <IconButton
                    size="small"
                    onClick={(e) => {
                      e.stopPropagation();
                      onRemoveDataset(schema.datasetId);
                    }}
                    sx={{ mr: 1 }}
                  >
                    <DeleteIcon fontSize="small" />
                  </IconButton>
                </Tooltip>
                {expanded.includes(sectionKey) ? (
                  <ExpandLess />
                ) : (
                  <ExpandMore />
                )}
              </ListItemButton>

              <Collapse
                in={expanded.includes(sectionKey)}
                timeout="auto"
                unmountOnExit
              >
                {/* Campi raggruppati */}
                {Object.entries(groupedFields).map(([groupName, fields]) => {
                  if (fields.length === 0) return null;
                  const groupKey = `${sectionKey}-${groupName}`;

                  return (
                    <List key={groupKey} dense disablePadding>
                      <ListItemButton
                        onClick={() => toggleExpand(groupKey)}
                        sx={{ pl: 2, bgcolor: "grey.50" }}
                      >
                        <ListItemText
                          primary={groupName}
                          primaryTypographyProps={{
                            variant: "body2",
                            fontWeight: 500,
                            color: "text.secondary",
                          }}
                        />
                        <Chip
                          label={fields.length}
                          size="small"
                          sx={{ height: 18, fontSize: 10, mr: 1 }}
                        />
                        {expanded.includes(groupKey) ? (
                          <ExpandLess fontSize="small" />
                        ) : (
                          <ExpandMore fontSize="small" />
                        )}
                      </ListItemButton>
                      <Collapse
                        in={expanded.includes(groupKey)}
                        timeout="auto"
                        unmountOnExit
                      >
                        <List dense disablePadding>
                          {fields.map((field) => {
                            const binding = createBinding(
                              schema.datasetId,
                              field.name,
                            );
                            const isCopied = copiedField === binding;

                            return (
                              <ListItem
                                key={`${schema.datasetId}-${field.name}`}
                                disablePadding
                                secondaryAction={
                                  <Box
                                    sx={{
                                      display: "flex",
                                      alignItems: "center",
                                      gap: 0.5,
                                    }}
                                  >
                                    <Chip
                                      label={field.type}
                                      size="small"
                                      color={getTypeColor(field.type)}
                                      sx={{ height: 18, fontSize: 10 }}
                                    />
                                    <Tooltip title="Copia binding">
                                      <IconButton
                                        size="small"
                                        onClick={(e) =>
                                          handleCopyBinding(
                                            e,
                                            schema.datasetId,
                                            field.name,
                                          )
                                        }
                                        sx={{
                                          opacity: 0.6,
                                          "&:hover": { opacity: 1 },
                                        }}
                                      >
                                        {isCopied ? (
                                          <CheckIcon
                                            fontSize="small"
                                            color="success"
                                          />
                                        ) : (
                                          <CopyIcon fontSize="small" />
                                        )}
                                      </IconButton>
                                    </Tooltip>
                                  </Box>
                                }
                              >
                                <ListItemButton
                                  onClick={() =>
                                    handleInsertField(
                                      schema.datasetId,
                                      field.name,
                                    )
                                  }
                                  sx={{ py: 0.5, pl: 4 }}
                                >
                                  <ListItemIcon sx={{ minWidth: 28 }}>
                                    {getFieldIcon(field.type)}
                                  </ListItemIcon>
                                  <ListItemText
                                    primary={field.label}
                                    secondary={
                                      isMobile ? undefined : field.name
                                    }
                                    primaryTypographyProps={{
                                      variant: "body2",
                                      fontSize: "0.8rem",
                                    }}
                                    secondaryTypographyProps={{
                                      variant: "caption",
                                      sx: {
                                        fontFamily: "monospace",
                                        fontSize: "0.65rem",
                                        color: "text.disabled",
                                      },
                                    }}
                                  />
                                </ListItemButton>
                              </ListItem>
                            );
                          })}
                        </List>
                      </Collapse>
                    </List>
                  );
                })}

                {/* Child Collections */}
                {schema.childCollections.map((collection) => {
                  const filteredCollectionFields = filterFields(
                    collection.fields,
                  );
                  if (search && filteredCollectionFields.length === 0)
                    return null;

                  const collectionKey = `${sectionKey}-col-${collection.name}`;

                  return (
                    <List key={collectionKey} dense disablePadding>
                      <ListItemButton
                        onClick={() => toggleExpand(collectionKey)}
                        sx={{
                          pl: 2,
                          bgcolor: (theme) =>
                            alpha(theme.palette.warning.main, 0.08),
                        }}
                      >
                        <ListItemIcon sx={{ minWidth: 28 }}>
                          <TableIcon fontSize="small" color="warning" />
                        </ListItemIcon>
                        <ListItemText
                          primary={collection.label}
                          secondary={
                            isMobile ? undefined : collection.description
                          }
                          primaryTypographyProps={{
                            variant: "body2",
                            fontWeight: 500,
                          }}
                          secondaryTypographyProps={{
                            variant: "caption",
                            sx: { fontSize: "0.65rem" },
                          }}
                        />
                        <Chip
                          label={filteredCollectionFields.length}
                          size="small"
                          color="warning"
                          sx={{ height: 18, fontSize: 10, mr: 1 }}
                        />
                        {expanded.includes(collectionKey) ? (
                          <ExpandLess fontSize="small" />
                        ) : (
                          <ExpandMore fontSize="small" />
                        )}
                      </ListItemButton>
                      <Collapse
                        in={expanded.includes(collectionKey)}
                        timeout="auto"
                        unmountOnExit
                      >
                        <List dense disablePadding>
                          {filteredCollectionFields.map((field) => {
                            const fieldPath = `${collection.name}.${field.name}`;
                            const binding = createBinding(
                              schema.datasetId,
                              fieldPath,
                            );
                            const isCopied = copiedField === binding;

                            return (
                              <ListItem
                                key={`${schema.datasetId}-${fieldPath}`}
                                disablePadding
                                secondaryAction={
                                  <Box
                                    sx={{
                                      display: "flex",
                                      alignItems: "center",
                                      gap: 0.5,
                                    }}
                                  >
                                    <Chip
                                      label={field.type}
                                      size="small"
                                      color={getTypeColor(field.type)}
                                      sx={{ height: 18, fontSize: 10 }}
                                    />
                                    <Tooltip title="Copia binding">
                                      <IconButton
                                        size="small"
                                        onClick={(e) =>
                                          handleCopyBinding(
                                            e,
                                            schema.datasetId,
                                            fieldPath,
                                          )
                                        }
                                        sx={{
                                          opacity: 0.6,
                                          "&:hover": { opacity: 1 },
                                        }}
                                      >
                                        {isCopied ? (
                                          <CheckIcon
                                            fontSize="small"
                                            color="success"
                                          />
                                        ) : (
                                          <CopyIcon fontSize="small" />
                                        )}
                                      </IconButton>
                                    </Tooltip>
                                  </Box>
                                }
                              >
                                <ListItemButton
                                  onClick={() =>
                                    handleInsertField(
                                      schema.datasetId,
                                      fieldPath,
                                    )
                                  }
                                  sx={{ py: 0.5, pl: 4 }}
                                >
                                  <ListItemIcon sx={{ minWidth: 28 }}>
                                    {getFieldIcon(field.type)}
                                  </ListItemIcon>
                                  <ListItemText
                                    primary={field.label}
                                    secondary={isMobile ? undefined : fieldPath}
                                    primaryTypographyProps={{
                                      variant: "body2",
                                      fontSize: "0.8rem",
                                    }}
                                    secondaryTypographyProps={{
                                      variant: "caption",
                                      sx: {
                                        fontFamily: "monospace",
                                        fontSize: "0.65rem",
                                        color: "text.disabled",
                                      },
                                    }}
                                  />
                                </ListItemButton>
                              </ListItem>
                            );
                          })}
                        </List>
                      </Collapse>
                    </List>
                  );
                })}
              </Collapse>
              <Divider />
            </Box>
          );
        })}

        {/* Special Variables */}
        <List dense disablePadding>
          <ListItemButton
            onClick={() => toggleExpand("special")}
            sx={{ bgcolor: (theme) => alpha(theme.palette.info.main, 0.08) }}
          >
            <ListItemText
              primary="Variabili Speciali"
              primaryTypographyProps={{ variant: "subtitle2", fontWeight: 600 }}
            />
            {expanded.includes("special") ? <ExpandLess /> : <ExpandMore />}
          </ListItemButton>
          <Collapse
            in={expanded.includes("special")}
            timeout="auto"
            unmountOnExit
          >
            <List dense disablePadding sx={{ pl: 2 }}>
              {[
                {
                  binding: "{{$pageNumber}}",
                  label: "Numero Pagina",
                  icon: <NumberIcon fontSize="small" />,
                },
                {
                  binding: "{{$totalPages}}",
                  label: "Totale Pagine",
                  icon: <NumberIcon fontSize="small" />,
                },
                {
                  binding: "{{$date}}",
                  label: "Data Corrente",
                  icon: <DateIcon fontSize="small" />,
                },
                {
                  binding: "{{$datetime}}",
                  label: "Data e Ora Corrente",
                  icon: <DateIcon fontSize="small" />,
                },
                {
                  binding: "{{$time}}",
                  label: "Ora Corrente",
                  icon: <DateIcon fontSize="small" />,
                },
              ].map((item) => {
                const isCopied = copiedField === item.binding;
                return (
                  <ListItem key={item.binding} disablePadding>
                    <ListItemButton
                      onClick={() => {
                        onInsertBinding(item.binding);
                        setCopiedField(item.binding);
                        setTimeout(() => setCopiedField(null), 1500);
                      }}
                      sx={{ py: 0.5 }}
                    >
                      <ListItemIcon sx={{ minWidth: 28 }}>
                        {item.icon}
                      </ListItemIcon>
                      <ListItemText
                        primary={item.label}
                        secondary={
                          isMobile
                            ? undefined
                            : item.binding.replace(/[{}]/g, "")
                        }
                        primaryTypographyProps={{ variant: "body2" }}
                        secondaryTypographyProps={{
                          variant: "caption",
                          sx: { fontFamily: "monospace" },
                        }}
                      />
                      {isCopied && (
                        <CheckIcon fontSize="small" color="success" />
                      )}
                    </ListItemButton>
                  </ListItem>
                );
              })}
            </List>
          </Collapse>
        </List>
      </Box>

      {/* Footer */}
      <Box
        sx={{
          p: 1.5,
          borderTop: 1,
          borderColor: "divider",
          bgcolor: "grey.50",
        }}
      >
        <Typography variant="caption" color="text.secondary">
          {isMobile
            ? "Tocca un campo per inserirlo"
            : "Clicca su un campo per inserirlo nell'elemento selezionato, oppure usa l'icona copia per copiare il binding negli appunti."}
        </Typography>
      </Box>
    </Box>
  );
}
