"use client"
import { Box, Typography, List, ListItem, ListItemIcon, ListItemText, Paper, IconButton } from "@mui/material"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import {
  faFont,
  faList,
  faCheckSquare,
  faCalendarAlt,
  faFile,
  faStar,
  faShieldAlt,
  faAlignLeft,
  faHashtag,
  faEnvelope,
  faPhone,
  faLayerGroup,
  faPlus,
} from "@fortawesome/free-solid-svg-icons"
import { FieldType, FieldCategory } from "@/shared/types/formulaire"
import { Draggable, Droppable } from "react-beautiful-dnd"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"

interface FieldLibraryProps {
  onAddField: (fieldType: FieldType, category: string) => void
  disabled?: boolean
}

export interface FieldTypeDefinition {
  type: FieldType
  label: string
  icon: any
  category: FieldCategory
  description: string
}

// Format draggableId to ensure it's a simple string without special characters
const formatDraggableId = (type: string, category: string, index: number): string => {
  return `library_${type}_${category}_${index}`
}

export default function FieldLibrary({ onAddField, disabled = false }: FieldLibraryProps) {
  const fieldTypes: FieldTypeDefinition[] = [
    // Personal data fields
    {
      type: FieldType.TEXT,
      label: "Texte court",
      icon: faFont,
      category: FieldCategory.Personal,
      description: "Champ de texte court pour saisir du texte sur une ligne",
    },
    {
      type: FieldType.TEXTAREA,
      label: "Texte long",
      icon: faAlignLeft,
      category: FieldCategory.Personal,
      description: "Zone de texte pour saisir du texte sur plusieurs lignes",
    },
    {
      type: FieldType.EMAIL,
      label: "Email",
      icon: faEnvelope,
      category: FieldCategory.Personal,
      description: "Champ pour saisir une adresse email valide",
    },
    {
      type: FieldType.PHONE,
      label: "Téléphone",
      icon: faPhone,
      category: FieldCategory.Personal,
      description: "Champ pour saisir un numéro de téléphone",
    },

    // Administrative fields
    {
      type: FieldType.DATE,
      label: "Date",
      icon: faCalendarAlt,
      category: FieldCategory.Administrative,
      description: "Champ pour sélectionner une date",
    },
    {
      type: FieldType.NUMBER,
      label: "Nombre",
      icon: faHashtag,
      category: FieldCategory.Administrative,
      description: "Champ pour saisir un nombre",
    },
    {
      type: FieldType.FILE,
      label: "Fichier",
      icon: faFile,
      category: FieldCategory.Administrative,
      description: "Téléversement de fichiers (PDF, images, etc.)",
    },

    // HR specific
    {
      type: FieldType.SELECT,
      label: "Liste déroulante",
      icon: faList,
      category: FieldCategory.HR,
      description: "Menu déroulant pour sélectionner une option",
    },
    {
      type: FieldType.RADIO,
      label: "Boutons radio",
      icon: faList,
      category: FieldCategory.HR,
      description: "Groupe de boutons radio pour sélection unique",
    },
    {
      type: FieldType.CHECKBOX,
      label: "Cases à cocher",
      icon: faCheckSquare,
      category: FieldCategory.HR,
      description: "Cases à cocher pour sélection multiple",
    },
    {
      type: FieldType.RATING,
      label: "Notation",
      icon: faStar,
      category: FieldCategory.HR,
      description: "Système de notation par étoiles ou points",
    },

    // Other categories
    {
      type: FieldType.CONSENT,
      label: "Consentement RGPD",
      icon: faShieldAlt,
      category: FieldCategory.Other,
      description: "Case à cocher pour acceptation d'une politique ou consentement",
    },
    {
      type: FieldType.SECTION,
      label: "Section",
      icon: faLayerGroup,
      category: FieldCategory.Other,
      description: "Groupe de champs avec titre et description",
    },
  ]

  return (
    <Box
      sx={{
        width: "100%",
        display: "flex",
        flexDirection: "column",
        height: "100%",
        overflow: "hidden",
        bgcolor: "primary.lighter",
      }}
    >
      <Box
        sx={{
          p: 1.5,
          pb: 1,
          borderBottom: 1,
          borderColor: "divider",
          position: "sticky",
          top: 0,
          bgcolor: "grey.100",
          zIndex: 5,
          flexShrink: 0,
        }}
      >
        <Typography
          variant="h6"
          sx={{
            fontWeight: "bold",
            mb: 0.5,
            fontSize: "1rem",
            color: "primary.main",
          }}
        >
          Bibliothèque de composants
        </Typography>
        <Typography
          variant="body2"
          sx={{
            color: "text.secondary",
            display: "flex",
            alignItems: "center",
            gap: 1,
            fontSize: "0.75rem",
          }}
        >
          <Box component="span" sx={{ color: "primary.main", fontSize: "1rem", lineHeight: 1 }}>
            ↓
          </Box>
          Glissez les composants vers le formulaire ou cliquez sur{" "}
          <FontAwesomeIcon icon={faPlus} style={{ marginLeft: 4, marginRight: 4, color: "var(--primary-main)" }} /> pour
          ajouter
        </Typography>
      </Box>

      <Box
        sx={{
          pt: 0.5,
          px: 1,
          flexGrow: 1,
          overflow: "hidden",
          display: "flex",
          flexDirection: "column",
        }}
      >
        <Droppable droppableId="library-all-fields" isDropDisabled={true} type="FIELD">
          {(provided) => (
            <List
              dense
              disablePadding
              ref={provided.innerRef}
              {...provided.droppableProps}
              sx={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fill, minmax(100%, 1fr))",
                gap: 0.5,
                overflow: "auto",
                pr: 1,
                flexGrow: 1,
                height: "100%",
                "&::-webkit-scrollbar": {
                  width: "6px",
                },
                "&::-webkit-scrollbar-track": {
                  background: "rgba(0,0,0,0.05)",
                  borderRadius: "4px",
                },
                "&::-webkit-scrollbar-thumb": {
                  background: "rgba(0,0,0,0.2)",
                  borderRadius: "4px",
                  "&:hover": {
                    background: "rgba(0,0,0,0.3)",
                  },
                },
              }}
            >
              {fieldTypes.map((field, index) => {
                const draggableId = formatDraggableId(field.type, field.category, index)

                return (
                  <Draggable key={draggableId} draggableId={draggableId} index={index} isDragDisabled={disabled}>
                    {(provided, snapshot) => (
                      <div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
                        <ListItem disablePadding sx={{ mb: 0.5 }}>
                          <Paper
                            elevation={snapshot.isDragging ? 8 : 0}
                            sx={{
                              py: 0.75,
                              px: 1.25,
                              width: "100%",
                              cursor: disabled ? "not-allowed" : "grab",
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "space-between",
                              bgcolor: snapshot.isDragging ? "primary.lighter" : "background.paper",
                              border: "1px solid",
                              borderColor: snapshot.isDragging ? "primary.main" : "divider",
                              borderRadius: 1,
                              position: "relative",
                              overflow: "hidden",
                              transition: "all 0.2s ease",
                              transform: snapshot.isDragging ? "scale(1.05)" : "scale(1)",
                              "&:hover": {
                                borderColor: "primary.main",
                                bgcolor: "primary.lighter",
                                "& .MuiListItemIcon-root": {
                                  color: "primary.main",
                                },
                                "& .MuiTypography-root.MuiTypography-body2": {
                                  color: "primary.main",
                                },
                              },
                              "&::after": snapshot.isDragging
                                ? {
                                    content: '"✓"',
                                    position: "absolute",
                                    top: -10,
                                    right: -10,
                                    width: 20,
                                    height: 20,
                                    borderRadius: "50%",
                                    backgroundColor: "primary.main",
                                    color: "white",
                                    display: "flex",
                                    alignItems: "center",
                                    justifyContent: "center",
                                    fontSize: "0.75rem",
                                    fontWeight: "bold",
                                    zIndex: 2,
                                    boxShadow: "0 2px 4px rgba(0,0,0,0.2)",
                                  }
                                : {},
                            }}
                          >
                            <Box
                              sx={{
                                display: "flex",
                                alignItems: "center",
                                width: "calc(100% - 30px)",
                                overflow: "hidden",
                              }}
                            >
                              <ListItemIcon
                                sx={{
                                  minWidth: 32,
                                  fontSize: "0.9rem",
                                  color: snapshot.isDragging ? "primary.main" : "text.secondary",
                                  transition: "color 0.2s ease",
                                }}
                              >
                                <FontAwesomeIcon icon={field.icon} size="sm" />
                              </ListItemIcon>
                              <ListItemText
                                primary={
                                  <Typography
                                    variant="body2"
                                    noWrap
                                    sx={{
                                      fontWeight: 500,
                                      color: snapshot.isDragging ? "primary.main" : "text.primary",
                                      mb: 0,
                                      lineHeight: 1.2,
                                      overflow: "hidden",
                                      textOverflow: "ellipsis",
                                      transition: "color 0.2s ease",
                                    }}
                                  >
                                    {field.label}
                                  </Typography>
                                }
                                secondary={
                                  <Typography
                                    variant="caption"
                                    color="text.secondary"
                                    sx={{
                                      display: "-webkit-box",
                                      WebkitLineClamp: 1,
                                      WebkitBoxOrient: "vertical",
                                      overflow: "hidden",
                                      fontSize: "0.7rem",
                                      lineHeight: 1.2,
                                    }}
                                  >
                                    {field.description}
                                  </Typography>
                                }
                                sx={{ my: 0, py: 0 }}
                              />
                            </Box>

                            <CustomTooltip arrow title="Ajouter ce champ">
                              <IconButton
                                size="small"
                                color="primary"
                                onClick={(e) => {
                                  e.stopPropagation()
                                  if (!disabled) onAddField(field.type, field.category)
                                }}
                                sx={{
                                  opacity: 0.7,
                                  "&:hover": {
                                    opacity: 1,
                                    bgcolor: "primary.lighter",
                                    color: "primary.main",
                                  },
                                  padding: 0.5,
                                  marginLeft: 0.5,
                                  transition: "all 0.2s ease",
                                }}
                              >
                                <FontAwesomeIcon icon={faPlus} size="xs" />
                              </IconButton>
                            </CustomTooltip>
                          </Paper>
                        </ListItem>
                      </div>
                    )}
                  </Draggable>
                )
              })}
              {provided.placeholder}
            </List>
          )}
        </Droppable>
      </Box>
    </Box>
  )
}
