"use client"

import { useState, useCallback } from "react"
import {
  Box,
  Paper,
  Grid,
  Typography,
  Stack,
  IconButton,
  Button,
  MenuItem,
  TextField,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Select,
  FormControl,
  InputLabel,
  SelectChangeEvent,
} from "@mui/material"
import { DragDropContext, Droppable, Draggable, type DropResult } from "react-beautiful-dnd"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import {
  faTrash,
  faCopy,
  faWrench,
  faEye,
  faArrowUp,
  faArrowDown,
  faPen,
  faLayerGroup,
} from "@fortawesome/free-solid-svg-icons"
import { nanoid } from "nanoid"
import { type IFormulaire, type FormulaireChamp, FieldType, FieldCategory } from "@/shared/types/formulaire"
import FieldLibrary from "./field-library"
import FieldEditor from "./field-editor"
import FormPreview from "./form-preview"
import FieldSettings from "./field-settings"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import { AddButton } from "@/shared/components/table/styles"
import FontAwesome from "@/shared/components/fontawesome"
import { ActionsIconButton, StyledInputLabel, StyledMenuItem, StyledSelect, StyledTextField } from "@/shared/theme/css"
import { StyledDialogTitle } from "../../../styles"

interface FormBuilderProps {
  formulaire: IFormulaire
  onChange: (formulaire: IFormulaire) => void
  onSave: () => void
  readOnly?: boolean
}

export default function FormBuilder({ formulaire, onChange, onSave, readOnly = false }: FormBuilderProps) {
  const [selectedFieldId, setSelectedFieldId] = useState<string | null>(null)
  const [showPreview, setShowPreview] = useState(false)
  const [showSettings, setShowSettings] = useState(false)
  const [sectionDialogOpen, setSectionDialogOpen] = useState(false)
  const [newSectionData, setNewSectionData] = useState({
    title: "",
    description: "",
    style: "default",
    collapsible: false,
  })

  const selectedField = selectedFieldId ? formulaire.fields.find((field) => field.id === selectedFieldId) : null

  const handleAddField = useCallback(
    (fieldType: FieldType, category: string) => {
      if (readOnly) return

      const newField: FormulaireChamp = {
        id: nanoid(),
        label: `Nouveau champ ${fieldType}`,
        type: fieldType,
        required: false,
        category: category as any,
      }

      // Add options for select, radio, checkbox types
      if (fieldType === FieldType.SELECT || fieldType === FieldType.RADIO || fieldType === FieldType.CHECKBOX) {
        newField.options = [
          { value: "option1", label: "Option 1" },
          { value: "option2", label: "Option 2" },
        ]
      }

      // Add validation for email type
      if (fieldType === FieldType.EMAIL) {
        newField.validations = {
          pattern: "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$",
        }
      }

      const updatedFormulaire = {
        ...formulaire,
        fields: [...formulaire.fields, newField],
      }

      onChange(updatedFormulaire)
      setSelectedFieldId(newField.id)
    },
    [formulaire, onChange, readOnly],
  )

  // Add a helper function at the top to parse draggableId
  // This should match the format in field-library.tsx
  const parseDraggableId = (draggableId: string) => {
    // Format: library_type_category_index
    const parts = draggableId.split("_")
    if (parts.length >= 3 && parts[0] === "library") {
      return {
        source: parts[0],
        type: parts[1] as FieldType,
        category: parts[2] as FieldCategory,
      }
    }
    return null
  }

  // Update the handleDragEnd function to use the parser
  const handleDragEnd = useCallback(
    (result: DropResult) => {
      const { source, destination } = result

      console.log("Drag end result:", result) // Add logging to debug drag events

      // Dropped outside a valid droppable
      if (!destination) return

      // Exclude drags within the library
      if (source.droppableId === "library-all-fields" && destination.droppableId === "library-all-fields") {
        return
      }

      // Reordering within the form canvas
      if (source.droppableId === "form-fields" && destination.droppableId === "form-fields") {
        const fields = Array.from(formulaire.fields)
        const [removed] = fields.splice(source.index, 1)
        fields.splice(destination.index, 0, removed)

        const updatedFormulaire = {
          ...formulaire,
          fields,
        }

        onChange(updatedFormulaire)
        return
      }

      // Dragging from main form to a section
      if (source.droppableId === "form-fields" && destination.droppableId.startsWith("section-")) {
        const sectionId = destination.droppableId.replace("section-", "")
        const section = formulaire.fields.find((field) => field.id === sectionId)

        if (!section) return

        const fieldToMove = formulaire.fields[source.index]

        // Update section with the new field
        const updatedfields = formulaire.fields.map((field) => {
          if (field.id === sectionId) {
            return {
              ...field,
              childFields: [...(field.childFields || []), fieldToMove.id],
            }
          }
          return field
        })

        onChange({
          ...formulaire,
          fields: updatedfields,
        })

        return
      }

      // Dragging from a section to main form
      if (source.droppableId.startsWith("section-") && destination.droppableId === "form-fields") {
        const sectionId = source.droppableId.replace("section-", "")
        const section = formulaire.fields.find((field) => field.id === sectionId)

        if (!section || !section.childFields) return

        // Get the field ID to move
        const fieldId = section.childFields[source.index]

        // Remove field from section
        const updatedfields = formulaire.fields.map((field) => {
          if (field.id === sectionId) {
            return {
              ...field,
              childFields: field.childFields?.filter((id) => id !== fieldId) || [],
            }
          }
          return field
        })

        onChange({
          ...formulaire,
          fields: updatedfields,
        })

        return
      }

      // Dragging between sections
      if (source.droppableId.startsWith("section-") && destination.droppableId.startsWith("section-")) {
        const sourceSectionId = source.droppableId.replace("section-", "")
        const destSectionId = destination.droppableId.replace("section-", "")

        const sourceSection = formulaire.fields.find((field) => field.id === sourceSectionId)
        const destSection = formulaire.fields.find((field) => field.id === destSectionId)

        if (!sourceSection || !sourceSection.childFields || !destSection) return

        // Get the field ID to move
        const fieldId = sourceSection.childFields[source.index]

        // Update both sections
        const updatedfields = formulaire.fields.map((field) => {
          if (field.id === sourceSectionId) {
            return {
              ...field,
              childFields: field.childFields?.filter((id) => id !== fieldId) || [],
            }
          }
          if (field.id === destSectionId) {
            const destChildFields = [...(field.childFields || [])]
            destChildFields.splice(destination.index, 0, fieldId)
            return {
              ...field,
              childFields: destChildFields,
            }
          }
          return field
        })

        onChange({
          ...formulaire,
          fields: updatedfields,
        })

        return
      }

      // Dragging from library to form canvas
      if (source.droppableId === "library-all-fields" && destination.droppableId === "form-fields") {
        // Parse the draggable ID to get the field type and category
        const parsedData = parseDraggableId(result.draggableId)

        if (parsedData) {
          const { type: fieldType, category } = parsedData

          // Create new field
          const newField: FormulaireChamp = {
            id: nanoid(),
            label: `Nouveau champ ${fieldType}`,
            type: fieldType,
            required: false,
            category: category,
          }

          // Add options for select, radio, checkbox types
          if (fieldType === FieldType.SELECT || fieldType === FieldType.RADIO || fieldType === FieldType.CHECKBOX) {
            newField.options = [
              { value: "option1", label: "Option 1" },
              { value: "option2", label: "Option 2" },
            ]
          }

          // Add validation for email type
          if (fieldType === FieldType.EMAIL) {
            newField.validations = {
              pattern: "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$",
            }
          }

          // Insert the new field at the destination index
          const updatedfields = [...formulaire.fields]
          updatedfields.splice(destination.index, 0, newField)

          const updatedFormulaire = {
            ...formulaire,
            fields: updatedfields,
          }

          onChange(updatedFormulaire)
          setSelectedFieldId(newField.id)
        }
        return
      }

      // Dragging from library to a section
      if (source.droppableId === "library-all-fields" && destination.droppableId.startsWith("section-")) {
        const sectionId = destination.droppableId.replace("section-", "")
        const section = formulaire.fields.find((field) => field.id === sectionId)

        if (!section) return

        // Parse the draggable ID to get the field type and category
        const parsedData = parseDraggableId(result.draggableId)

        if (parsedData) {
          const { type: fieldType, category } = parsedData

          // Create new field
          const newField: FormulaireChamp = {
            id: nanoid(),
            label: `Nouveau champ ${fieldType}`,
            type: fieldType,
            required: false,
            category: category,
          }

          // Add options for select, radio, checkbox types
          if (fieldType === FieldType.SELECT || fieldType === FieldType.RADIO || fieldType === FieldType.CHECKBOX) {
            newField.options = [
              { value: "option1", label: "Option 1" },
              { value: "option2", label: "Option 2" },
            ]
          }

          // Add validation for email type
          if (fieldType === FieldType.EMAIL) {
            newField.validations = {
              pattern: "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$",
            }
          }

          // Add the new field to the form
          const updatedfields = [...formulaire.fields, newField]

          // Update section to include this field
          const updatedfieldsWithSection = updatedfields.map((field) => {
            if (field.id === sectionId) {
              return {
                ...field,
                childFields: [...(field.childFields || []), newField.id],
              }
            }
            return field
          })

          const updatedFormulaire = {
            ...formulaire,
            fields: updatedfieldsWithSection,
          }

          onChange(updatedFormulaire)
          setSelectedFieldId(newField.id)
        }
      }
    },
    [formulaire, onChange, readOnly],
  )

  const handleUpdateField = useCallback(
    (updatedField: FormulaireChamp) => {
      if (readOnly) return

      const updatedfields = formulaire.fields.map((field) => (field.id === updatedField.id ? updatedField : field))

      const updatedFormulaire = {
        ...formulaire,
        fields: updatedfields,
      }

      onChange(updatedFormulaire)
    },
    [formulaire, onChange, readOnly],
  )

  const handleDeleteField = useCallback(
    (fieldId: string) => {
      if (readOnly) return

      const updatedfields = formulaire.fields.filter((field) => field.id !== fieldId)

      const updatedFormulaire = {
        ...formulaire,
        fields: updatedfields,
      }

      onChange(updatedFormulaire)
      setSelectedFieldId(null)
    },
    [formulaire, onChange, readOnly],
  )

  const handleDuplicateField = useCallback(
    (fieldId: string) => {
      if (readOnly) return

      const fieldToDuplicate = formulaire.fields.find((field) => field.id === fieldId)
      if (!fieldToDuplicate) return

      const duplicatedField = {
        ...fieldToDuplicate,
        id: nanoid(),
        label: `${fieldToDuplicate.label} (copie)`,
      }

      const updatedFormulaire = {
        ...formulaire,
        fields: [...formulaire.fields, duplicatedField],
      }

      onChange(updatedFormulaire)
    },
    [formulaire, onChange, readOnly],
  )

  const handleMoveField = useCallback(
    (fieldId: string, direction: "up" | "down") => {
      if (readOnly) return

      const fieldIndex = formulaire.fields.findIndex((f) => f.id === fieldId)
      if (fieldIndex === -1) return

      // Can't move up if already at the top
      if (direction === "up" && fieldIndex === 0) return

      // Can't move down if already at the bottom
      if (direction === "down" && fieldIndex === formulaire.fields.length - 1) return

      const newIndex = direction === "up" ? fieldIndex - 1 : fieldIndex + 1

      const newfields = [...formulaire.fields]
      const field = newfields[fieldIndex]

      // Remove field from old position
      newfields.splice(fieldIndex, 1)
      // Insert at new position
      newfields.splice(newIndex, 0, field)

      const updatedFormulaire = {
        ...formulaire,
        fields: newfields,
      }

      onChange(updatedFormulaire)
    },
    [formulaire, onChange, readOnly],
  )

  const handleUpdateFormulaireSettings = useCallback(
    (settings: Partial<IFormulaire>) => {
      if (readOnly) return

      const updatedFormulaire = {
        ...formulaire,
        ...settings,
      }

      onChange(updatedFormulaire)
    },
    [formulaire, onChange, readOnly],
  )

  const handleAddSection = useCallback(() => {
    if (readOnly) return
    setSectionDialogOpen(true)
  }, [readOnly])

  const handleSectionDialogClose = () => {
    setSectionDialogOpen(false)
    setNewSectionData({
      title: "",
      description: "",
      style: "default",
      collapsible: false,
    })
  }

  const handleCreateSection = () => {
    if (readOnly) return

    const newSection: FormulaireChamp = {
      id: nanoid(),
      label: newSectionData.title,
      type: FieldType.SECTION,
      required: false,
      sectionTitle: newSectionData.title,
      sectionDescription: newSectionData.description,
      sectionStyle: newSectionData.style as "default" | "card" | "outlined" | "filled",
      sectionCollapsible: newSectionData.collapsible,
      sectionCollapsed: false,
      childFields: [],
      category: FieldCategory.Other,
    }

    const updatedFormulaire = {
      ...formulaire,
      fields: [...formulaire.fields, newSection],
    }

    onChange(updatedFormulaire)
    setSelectedFieldId(newSection.id)
    handleSectionDialogClose()
  }

  const handleMoveToSection = useCallback(
    (fieldId: string, sectionId: string) => {
      if (readOnly) return

      const updatedfields = [...formulaire.fields]

      // Find the field and section
      const fieldIndex = updatedfields.findIndex((f) => f.id === fieldId)
      const sectionIndex = updatedfields.findIndex((f) => f.id === sectionId)

      if (fieldIndex === -1 || sectionIndex === -1) return

      const field = updatedfields[fieldIndex]
      const section = updatedfields[sectionIndex]

      // Make sure the section is of type 'section'
      if (section.type !== FieldType.SECTION) return

      // Add field to section's childFields array
      const updatedSection = {
        ...section,
        childFields: [...(section.childFields || []), fieldId],
      }

      // Update the section
      updatedfields[sectionIndex] = updatedSection

      const updatedFormulaire = {
        ...formulaire,
        fields: updatedfields,
      }

      onChange(updatedFormulaire)
    },
    [formulaire, onChange, readOnly],
  )

  const handleRemoveFromSection = useCallback(
    (fieldId: string | undefined, sectionId: string) => {
      if (readOnly || !fieldId) return

      const updatedfields = [...formulaire.fields]

      // Find the section
      const sectionIndex = updatedfields.findIndex((f) => f.id === sectionId)
      if (sectionIndex === -1) return

      const section = updatedfields[sectionIndex]

      // Remove field from section's childFields array
      const updatedSection = {
        ...section,
        childFields: (section.childFields || []).filter((id) => id !== fieldId),
      }

      // Update the section
      updatedfields[sectionIndex] = updatedSection

      const updatedFormulaire = {
        ...formulaire,
        fields: updatedfields,
      }

      onChange(updatedFormulaire)
    },
    [formulaire, onChange, readOnly],
  )
  const handleSelectChange = (event: SelectChangeEvent<unknown>) => {
      const selectedValue = event.target.value as string;
      setNewSectionData((prev) => ({ ...prev, style: selectedValue }))
  };
  // Helper to get fields that are not in any section
  const getUnsectionedFields = useCallback(() => {
    // Collect all field IDs that are part of a section
    const sectionedFieldIds = formulaire.fields
      .filter((field) => field.type === FieldType.SECTION)
      .flatMap((section) => section.childFields || [])

    // Return fields that are not in any section and are not sections themselves
    return formulaire.fields.filter(
      (field) => field.type !== FieldType.SECTION && !sectionedFieldIds.includes(field.id),
    )
  }, [formulaire.fields])

  // Get all section fields
  const getSections = useCallback(() => {
    return formulaire.fields.filter((field) => field.type === FieldType.SECTION)
  }, [formulaire.fields])

  // Helper to get fields that belong to a specific section
  const getSectionFields = useCallback(
    (sectionId: string) => {
      const section = formulaire.fields.find((field) => field.id === sectionId)
      if (!section || !section.childFields) return []

      return section.childFields
        .map((fieldId) => formulaire.fields.find((field) => field.id === fieldId))
        .filter(Boolean)
    },
    [formulaire.fields],
  )

  // Render a section with its fields
  const renderSection = useCallback(
    (section: FormulaireChamp, index: number) => {
      const sectionFields = getSectionFields(section.id)
      const sectionStyle = section.sectionStyle || "default"

      return (
        <Draggable key={section.id} draggableId={section.id} index={index} isDragDisabled={readOnly}>
          {(provided, snapshot) => (
            <div
              ref={provided.innerRef}
              {...provided.draggableProps}
              style={{
                ...provided.draggableProps.style,
                marginBottom: "16px",
              }}
            >
              <Paper
                elevation={snapshot.isDragging ? 6 : 1}
                sx={{
                  p: 2,
                  mb: 2,
                  border: "1px solid",
                  borderColor: snapshot.isDragging ? "primary.main" : "divider",
                  borderRadius: 1,
                  bgcolor: snapshot.isDragging
                    ? "primary.lighter"
                    : sectionStyle === "filled"
                      ? "primary.lighter"
                      : "background.paper",
                  ...(sectionStyle === "outlined" && {
                    borderWidth: "2px",
                    borderColor: "primary.main",
                  }),
                  ...(sectionStyle === "card" && {
                    boxShadow: 3,
                    borderColor: "transparent",
                  }),
                }}
              >
                <Box
                  {...provided.dragHandleProps}
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    mb: 1,
                    borderBottom: "1px dashed",
                    borderColor: "divider",
                    pb: 1,
                  }}
                >
                  <Typography variant="h6" sx={{ fontWeight: "bold" }}>
                    {section.sectionTitle || section.label}
                  </Typography>

                  <Stack direction="row" spacing={1}>
                    {!readOnly ? (
                      <>
                        <CustomTooltip arrow title="Déplacer vers le haut">
                          <IconButton size="small" onClick={() => handleMoveField(section.id, "up")}>
                            <FontAwesomeIcon icon={faArrowUp} />
                          </IconButton>
                        </CustomTooltip>

                        <CustomTooltip arrow title="Déplacer vers le bas">
                          <IconButton size="small" onClick={() => handleMoveField(section.id, "down")}>
                            <FontAwesomeIcon icon={faArrowDown} />
                          </IconButton>
                        </CustomTooltip>

                        <CustomTooltip arrow title="Modifier">
                          <IconButton size="small" onClick={() => setSelectedFieldId(section.id)}>
                            <FontAwesomeIcon icon={faPen} />
                          </IconButton>
                        </CustomTooltip>

                        <CustomTooltip arrow title="Dupliquer">
                          <IconButton size="small" onClick={() => handleDuplicateField(section.id)}>
                            <FontAwesomeIcon icon={faCopy} />
                          </IconButton>
                        </CustomTooltip>

                        <CustomTooltip arrow title="Supprimer">
                          <IconButton size="small" color="error" onClick={() => handleDeleteField(section.id)}>
                            <FontAwesomeIcon icon={faTrash} />
                          </IconButton>
                        </CustomTooltip>
                      </>
                    ):<></>}
                  </Stack>
                </Box>

                {section.sectionDescription ? (
                  <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                    {section.sectionDescription}
                  </Typography>
                ):<></>}

                {/* Droppable area for section fields */}
                <Droppable droppableId={`section-${section.id}`} type="FIELD">
                  {(sectionProvided) => (
                    <Box
                      ref={sectionProvided.innerRef}
                      {...sectionProvided.droppableProps}
                      sx={{
                        minHeight: "50px",
                        p: 1,
                        bgcolor: "background.default",
                        borderRadius: 1,
                        border: "1px dashed",
                        borderColor: "divider",
                      }}
                    >
                      <ConditionalComponent
                        isValid={sectionFields.length > 0}
                        defaultComponent={
                          <Typography variant="body2" color="text.secondary" sx={{ p: 2, textAlign: "center" }}>
                            Glissez des fields ici
                          </Typography>
                        }
                      >
                        {sectionFields.map((field, fieldIndex) => (
                          <Draggable
                            key={field?.id}
                            draggableId={field?.id || ""}
                            index={fieldIndex}
                            isDragDisabled={readOnly}
                          >
                            {(fieldProvided) => (
                              <div
                                ref={fieldProvided.innerRef}
                                {...fieldProvided.draggableProps}
                                {...fieldProvided.dragHandleProps}
                              >
                                <Paper
                                  sx={{
                                    p: 2,
                                    mb: 1,
                                    display: "flex",
                                    justifyContent: "space-between",
                                    alignItems: "center",
                                    border: "1px solid",
                                    borderColor: snapshot.isDragging
                                      ? "primary.main"
                                      : selectedFieldId === field?.id
                                        ? "primary.main"
                                        : "divider",
                                    bgcolor: snapshot.isDragging
                                      ? "primary.lighter"
                                      : selectedFieldId === field?.id
                                        ? "primary.lighter"
                                        : "background.paper",
                                  }}
                                >
                                  <Typography>{field?.label}</Typography>

                                  <Stack direction="row" spacing={1}>
                                    <ConditionalComponent isValid={!readOnly}>
                                      <>
                                        <CustomTooltip arrow title="Modifier">
                                          <IconButton
                                            size="small"
                                            onClick={() => setSelectedFieldId(field?.id || null)}
                                          >
                                            <FontAwesomeIcon icon={faPen} />
                                          </IconButton>
                                        </CustomTooltip>

                                        <CustomTooltip arrow title="Supprimer de la section">
                                          <IconButton
                                            size="small"
                                            color="warning"
                                            onClick={() => handleRemoveFromSection(field?.id, section.id)}
                                          >
                                            <FontAwesomeIcon icon={faArrowUp} />
                                          </IconButton>
                                        </CustomTooltip>
                                      </>
                                    </ConditionalComponent>
                                  </Stack>
                                </Paper>
                              </div>
                            )}
                          </Draggable>
                        ))}
                      </ConditionalComponent>
                      {sectionProvided.placeholder}
                    </Box>
                  )}
                </Droppable>
              </Paper>
            </div>
          )}
        </Draggable>
      )
    },
    [
      formulaire.fields,
      getSectionFields,
      handleDeleteField,
      handleDuplicateField,
      handleMoveField,
      handleRemoveFromSection,
      readOnly,
      selectedFieldId,
    ],
  )

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Box
        sx={{
          width: "100%",
          display: "flex",
          flexDirection: "column",
          bgcolor: "background.default",
          height: "100%",
          overflow: "hidden",
        }}
      >
        <Stack
          direction="row"
          spacing={2}
          sx={{
            p: 2,
            borderBottom: 1,
            borderColor: "divider",
            bgcolor: "background.paper",
            position: "sticky",
            top: 0,
            zIndex: 8,
            flexShrink: 0,
          }}
          justifyContent="flex-end"
          alignItems="center"
        >
            <Button
              startIcon={<FontAwesomeIcon icon={faWrench} />}
              variant={showSettings ? "contained" : "outlined"}
              color="primary"
              onClick={() => {
                setShowSettings(!showSettings)
                setShowPreview(false)
              }}
              size="small"
              sx={{
                bgcolor: showSettings ? "primary.main" : "transparent",
                borderColor: "primary.main",
                "&:hover": {
                  bgcolor: showSettings ? "primary.dark" : "primary.lighter",
                },
              }}
            >
              Paramètres
            </Button>
            <Button
              startIcon={<FontAwesomeIcon icon={faEye} />}
              variant={showPreview ? "contained" : "outlined"}
              onClick={() => {
                setShowPreview(!showPreview)
                setShowSettings(false)
              }}
              size="small"
            >
              Aperçu
            </Button>
        </Stack>

        {showSettings ? (
          <Box sx={{ p: 3 }}>
            <FieldSettings formulaire={formulaire} onChange={handleUpdateFormulaireSettings} />
          </Box>
        ) : showPreview ? (
          <Box
            sx={{
              height: "calc(100% - 48px)",
              overflowY: "auto",
              "&::-webkit-scrollbar": {
                width: "8px",
              },
              "&::-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)",
                },
              },
            }}
          >
            <FormPreview formulaire={formulaire} />
          </Box>
        ) : (
          <Grid
            container
            spacing={2}
            sx={{
              flex: 1,
              overflow: "hidden",
              height: "calc(100% - 64px)",
            }}
          >
            {/* Left sidebar - Field library */}
            <Grid
              item
              xs={3}
              sx={{
                height: "100%",
                borderRight: 1,
                borderColor: "divider",
                bgcolor: "background.paper",
                display: "flex",
                flexDirection: "column",
                overflow: "hidden",
              }}
            >
              <FieldLibrary onAddField={handleAddField} disabled={readOnly} />
            </Grid>

            {/* Form Canvas */}
            <Grid
              item
              xs={12}
              md={6}
              sx={{
                height: "100%",
                display: "flex",
                flexDirection: "column",
                overflow: "hidden",
                borderRadius:'8px'
              }}
            >
             
                <Box
                  sx={{
                    p: 2,
                    borderBottom: 1,
                    borderColor: "divider",
                    bgcolor: "grey.100",
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    flexShrink: 0,

                  }}
                >
                  <Typography variant="h6" sx={{ fontWeight: "bold", color:'primary.main' }}>
                    {formulaire.title || "Prévisualisation du formulaire"}
                  </Typography>

                  <ConditionalComponent isValid={!readOnly}>
                  <AddButton
                      variant="contained"
                      startIcon={<FontAwesome width={16} icon={faLayerGroup} />}
                      onClick={handleAddSection}
                    >
                      Ajouter une section
                    </AddButton>
                  </ConditionalComponent>
                </Box>

                <Box
                  sx={{
                    p: 2,
                    backgroundColor:'primary.lighter',
                    overflowY: "auto",
                    overflowX: "hidden",
                    flexGrow: 1,
                    height: "calc(100% - 60px)",
                    "&::-webkit-scrollbar": {
                      width: "8px",
                    },
                    "&::-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)",
                      },
                    },
                  }}
                >
                  <Droppable droppableId="form-fields" type="FIELD">
                    {(provided, snapshot) => (
                      <Box
                        ref={provided.innerRef}
                        {...provided.droppableProps}
                        sx={{
                          minHeight: "100%",
                          padding: 2,
                          border: "2px dashed",
                          borderColor: snapshot.isDraggingOver ? "primary.main" : "divider",
                          borderRadius: 1,
                          backgroundColor: snapshot.isDraggingOver ? "primary.lighter" : "transparent",
                          transition: "all 0.2s ease",
                        }}
                      >
                        <ConditionalComponent
                          isValid={getUnsectionedFields().length === 0 && getSections().length === 0}
                          defaultComponent={null}
                        >
                          <Box
                            sx={{
                              height: "200px",
                              display: "flex",
                              flexDirection: "column",
                              alignItems: "center",
                              justifyContent: "center",
                              color: "text.secondary",
                              textAlign: "center",
                              p: 2,
                            }}
                          >
                            <Typography variant="body1" sx={{ mb: 1 }}>
                              {snapshot.isDraggingOver
                                ? "Déposez le champ ici"
                                : "Glissez des fields depuis la bibliothèque pour créer votre formulaire"}
                            </Typography>
                            <Typography variant="caption" color="text.secondary">
                              Ou utilisez le bouton + pour ajouter une section
                            </Typography>
                          </Box>
                        </ConditionalComponent>
                        {/* Render sections first */}
                        {getSections().map((section, index) => renderSection(section, index))}

                        {/* Then render fields that don't belong to a section */}
                        {getUnsectionedFields().map((field, index) => (
                          <Draggable
                            key={field.id}
                            draggableId={field.id}
                            index={index + getSections().length}
                            isDragDisabled={readOnly}
                          >
                            {(provided, snapshot) => (
                              <div
                                ref={provided.innerRef}
                                {...provided.draggableProps}
                                {...provided.dragHandleProps}
                                style={{
                                  ...provided.draggableProps.style,
                                  marginBottom: "8px",
                                }}
                              >
                                <Paper
                                  elevation={snapshot.isDragging ? 6 : 1}
                                  sx={{
                                    p: 2,
                                    mb: 1,
                                    display: "flex",
                                    justifyContent: "space-between",
                                    alignItems: "center",
                                    border: "1px solid",
                                    borderColor: snapshot.isDragging
                                      ? "primary.main"
                                      : selectedFieldId === field.id
                                        ? "primary.main"
                                        : "divider",
                                    bgcolor: snapshot.isDragging
                                      ? "primary.lighter"
                                      : selectedFieldId === field.id
                                        ? "primary.lighter"
                                        : "background.paper",
                                  }}
                                >
                                  <Typography>{field.label}</Typography>

                                  <Stack direction="row" spacing={1}>
                                    <ConditionalComponent isValid={!readOnly}>
                                      <>
                                        <CustomTooltip arrow title="Déplacer vers le haut">
                                          <IconButton size="small" sx={ActionsIconButton} onClick={() => handleMoveField(field.id, "up")}>
                                            <FontAwesomeIcon size="sm"  icon={faArrowUp} />
                                          </IconButton>
                                        </CustomTooltip>

                                        <CustomTooltip arrow title="Déplacer vers le bas">
                                          <IconButton size="small" sx={ActionsIconButton} onClick={() => handleMoveField(field.id, "down")}>
                                            <FontAwesomeIcon size="sm" icon={faArrowDown} />
                                          </IconButton>
                                        </CustomTooltip>

                                        <CustomTooltip arrow title="Modifier">
                                          <IconButton size="small" sx={ActionsIconButton} onClick={() => setSelectedFieldId(field.id)}>
                                            <FontAwesomeIcon size="sm" icon={faPen} />
                                          </IconButton>
                                        </CustomTooltip>

                                        <CustomTooltip arrow title="Dupliquer">
                                          <IconButton size="small" sx={ActionsIconButton} onClick={() => handleDuplicateField(field.id)}>
                                            <FontAwesomeIcon size="sm" icon={faCopy} />
                                          </IconButton>
                                        </CustomTooltip>

                                        <CustomTooltip arrow title="Supprimer">
                                          <IconButton
                                            size="small"
                                            sx={ActionsIconButton}
                                            onClick={() => handleDeleteField(field.id)}
                                          >
                                            <FontAwesomeIcon size="sm" icon={faTrash} />
                                          </IconButton>
                                        </CustomTooltip>
                                      </>
                                    </ConditionalComponent>
                                  </Stack>
                                </Paper>
                              </div>
                            )}
                          </Draggable>
                        ))}
                        {provided.placeholder}
                      </Box>
                    )}
                  </Droppable>
                </Box>
            </Grid>

            {/* Right sidebar - Field properties */}
            <Grid
              item
              xs={3}
              sx={{
                height: "100%",
                borderLeft: 1,
                borderColor: "divider",
                bgcolor: "background.paper",
                display: "flex",
                flexDirection: "column",
                overflow: "hidden",
                
              }}
            >
              <ConditionalComponent
                isValid={!!selectedField}
                defaultComponent={
                  <Box
                    sx={{
                      m: 2,
                      p: 2,
                      display: "flex",
                      border:"1px dashed",
                      borderColor:"primary.main",
                      borderRadius:2,
                      flexDirection: "column",
                      justifyContent: "center",
                      alignItems: "center",
                      height: "100%",
                      gap: 2,
                      color: "primary.main",
                    }}
                  >
                    <FontAwesome icon={faPen} width={28} />
                    <Typography align="center" variant="body2" sx={{ maxWidth: "80%" }}>
                      Sélectionnez un champ pour modifier ses propriétés
                    </Typography>
                  </Box>
                }
              >
                {selectedField ? (
                  <FieldEditor
                    field={selectedField}
                    onUpdateField={handleUpdateField}
                    onDeleteField={handleDeleteField}
                    readOnly={readOnly}
                    availableFieldIds={formulaire.fields.filter((f) => f.id !== selectedField.id).map((f) => f.id)}
                  />
                ):<></>}
              </ConditionalComponent>
            </Grid>
          </Grid>
        )}
      </Box>

      {/* Section Dialog */}
      <Dialog open={sectionDialogOpen} onClose={handleSectionDialogClose} maxWidth="sm" fullWidth>
      <StyledDialogTitle>
          Ajouter une nouvelle section
        </StyledDialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2, display: "flex", flexDirection: "column", gap: 2 }}>
            <StyledTextField
              label="Titre de la section"
              fullWidth
              value={newSectionData.title}
              onChange={(e) => setNewSectionData((prev) => ({ ...prev, title: e.target.value }))}
              required
            />

            <StyledTextField
              label="Description (optionnelle)"
              fullWidth
              multiline
              rows={3}
              value={newSectionData.description}
              onChange={(e) => setNewSectionData((prev) => ({ ...prev, description: e.target.value }))}
            />

            <FormControl fullWidth>
              <StyledInputLabel>Style de la section</StyledInputLabel>
              <StyledSelect
                value={newSectionData.style}
                label="Style de la section"
                displayEmpty
                onChange={(e) => handleSelectChange(e)}
              >
                <StyledMenuItem value="default">Standard</StyledMenuItem>
                <StyledMenuItem value="card">Carte</StyledMenuItem>
                <StyledMenuItem value="outlined">Bordure</StyledMenuItem>
                <StyledMenuItem value="filled">Rempli</StyledMenuItem>
              </StyledSelect>
            </FormControl>
          </Box>
        </DialogContent>
        <DialogActions>
          <AddButton variant="outlined" onClick={handleSectionDialogClose}>Annuler</AddButton>
          <AddButton onClick={handleCreateSection} variant="contained" disabled={!newSectionData.title}>
            Créer
          </AddButton>
        </DialogActions>
      </Dialog>
    </DragDropContext>
  )
}
