"use client"

import type React from "react"
import { useState } from "react"
import {
  Box,
  Typography,
  Stack,
  Switch,
  FormControlLabel,
  Button,
  IconButton,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
} from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete"
import AddIcon from "@mui/icons-material/Add"
import ExpandMoreIcon from "@mui/icons-material/ExpandMore"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons"
import { type FormulaireChamp, FieldType } from "@/shared/types/formulaire"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { WhiteStyledTextField } from "../../../styles"
import { StyledFormControl, StyledInputLabel, StyledMenuItem, StyledSelect } from "@/shared/theme/css"
import { pxToRem } from "@/shared/theme/typography"

interface FieldEditorProps {
  field: FormulaireChamp;
  onUpdateField: (field: FormulaireChamp) => void;
  onDeleteField: (fieldId: string) => void;
  readOnly?: boolean;
  availableFieldIds: string[];
}

export default function FieldEditor({
  field,
  onUpdateField,
  onDeleteField,
  readOnly = false,
  availableFieldIds = [],
}: FieldEditorProps) {
  const [openOptionDialog, setOpenOptionDialog] = useState(false);
  const [newOption, setNewOption] = useState({ value: '', label: '' });

  const handleBasicChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    onUpdateField({
      ...field,
      [name]: value,
    });
  };

  const handleSwitchChange = (name: string) => (e: React.ChangeEvent<HTMLInputElement>) => {
    onUpdateField({
      ...field,
      [name]: e.target.checked,
    });
  };

  const handleValidationChange = (name: string, value: any) => {
    onUpdateField({
      ...field,
      validations: {
        ...field.validations,
        [name]: value,
      },
    });
  };

  const handleAddOption = () => {
    if (!newOption.value || !newOption.label) return;

    const updatedOptions = [...(field.options || []), { value: newOption.value, label: newOption.label }]

    onUpdateField({
      ...field,
      options: updatedOptions,
    })

    setNewOption({ value: "", label: "" })
    setOpenOptionDialog(false)
  }

  const handleDeleteOption = (index: number) => {
    const updatedOptions = [...(field.options || [])]
    updatedOptions.splice(index, 1)

    onUpdateField({
      ...field,
      options: updatedOptions,
    })
  }

  const handleUpdateOption = (index: number, key: "value" | "label", value: string) => {
    if (!field.options) return

    const updatedOptions = [...field.options]
    updatedOptions[index] = {
      ...updatedOptions[index],
      [key]: value,
    }

    onUpdateField({
      ...field,
      options: updatedOptions,
    })
  }

  const handleConditionalLogicChange = (dependsOn: string, operator: string, value: string) => {
    onUpdateField({
      ...field,
      conditionalLogic: {
        dependsOn,
        showWhen: {
          operator: operator as any,
          value,
        },
      },
    })
  }

  return (
    <Box
      sx={{
        height: "100%",
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
      }}
    >
      <Box
        sx={{
          p: 2,
          border: 1,
          borderColor: "divider",
          bgcolor: "grey.100",
          flexShrink: 0,
        }}
      >
        <Typography
          variant="h6"
          sx={{ fontWeight: "bold", display: "flex", alignItems: "center", color: "primary.main" }}
        >
          Propriétés du champ
        </Typography>
      </Box>

      <Box
        sx={{
          p: 2,
          overflow: "auto",
          flexGrow: 1,
          bgcolor: "primary.lighter",
          borderRadius: 2,
          borderTopLeftRadius: 0,
          borderTopRightRadius: 0,
        }}
      >
        <Stack spacing={3}>
          {/* Basic properties */}
          <WhiteStyledTextField
            label="Libellé"
            name="label"
            value={field.label}
            onChange={handleBasicChange}
            fullWidth
            size="small"
            disabled={readOnly}
            required
            InputLabelProps={{
              shrink: true,
            }}
          />

          <ConditionalComponent
            isValid={
              field.type === FieldType.TEXT ||
              field.type === FieldType.TEXTAREA ||
              field.type === FieldType.EMAIL ||
              field.type === FieldType.NUMBER
            }
          >
            <WhiteStyledTextField
              label="Texte d'aide (placeholder)"
              name="placeholder"
              value={field.placeholder || ""}
              onChange={handleBasicChange}
              fullWidth
              size="small"
              disabled={readOnly}
            />
          </ConditionalComponent>

          {/* Required switch */}
          <FormControlLabel
            control={
              <Switch checked={field.required || false} onChange={handleSwitchChange("required")} disabled={readOnly} />
            }
            label="Champ obligatoire"
            sx={{
              "& .MuiFormControlLabel-label": {
                color: "text.disabled",
              },
            }}
          />

          {/* Options for select, checkbox, radio */}
          <ConditionalComponent
            isValid={
              field.type === FieldType.SELECT || field.type === FieldType.CHECKBOX || field.type === FieldType.RADIO
            }
          >
            <Accordion defaultExpanded>
              <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                <Typography>Options</Typography>
              </AccordionSummary>
              <AccordionDetails>
                <Stack spacing={1}>
                  {(field.options || []).map((option, index) => (
                    <Box key={index} sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                      <WhiteStyledTextField
                        label="Valeur"
                        value={option.value}
                        onChange={(e) => handleUpdateOption(index, "value", e.target.value)}
                        size="small"
                        disabled={readOnly}
                        sx={{ flex: 1 }}
                      />
                      <WhiteStyledTextField
                        label="Libellé"
                        value={option.label}
                        onChange={(e) => handleUpdateOption(index, "label", e.target.value)}
                        size="small"
                        disabled={readOnly}
                        sx={{ flex: 1 }}
                      />
                      <ConditionalComponent isValid={!readOnly}>
                        <IconButton size="small" color="error" onClick={() => handleDeleteOption(index)}>
                          <DeleteIcon fontSize="small" />
                        </IconButton>
                      </ConditionalComponent>
                    </Box>
                  ))}

                  <ConditionalComponent isValid={!readOnly}>
                    <Button
                      startIcon={<AddIcon />}
                      onClick={() => setOpenOptionDialog(true)}
                      variant="outlined"
                      size="small"
                      sx={{ mt: 1 }}
                    >
                      Ajouter une option
                    </Button>
                  </ConditionalComponent>
                </Stack>
              </AccordionDetails>
            </Accordion>
          </ConditionalComponent>

          {/* Validation rules */}
          <ConditionalComponent
            isValid={
              field.type === FieldType.TEXT ||
              field.type === FieldType.TEXTAREA ||
              field.type === FieldType.NUMBER ||
              field.type === FieldType.EMAIL
            }
          >
            <Accordion>
              <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                <Typography>Règles de validation</Typography>
              </AccordionSummary>
              <AccordionDetails>
                <Stack spacing={2}>
                  <ConditionalComponent isValid={field.type === FieldType.TEXT}>
                    <>
                      <WhiteStyledTextField
                        label="Longueur minimale"
                        type="number"
                        value={field.validations?.minLength || ""}
                        onChange={(e) => handleValidationChange("minLength", Number.parseInt(e.target.value, 10) || "")}
                        fullWidth
                        size="small"
                        disabled={readOnly}
                      />
                      <WhiteStyledTextField
                        label="Longueur maximale"
                        type="number"
                        value={field.validations?.maxLength || ""}
                        onChange={(e) => handleValidationChange("maxLength", Number.parseInt(e.target.value, 10) || "")}
                        fullWidth
                        size="small"
                        disabled={readOnly}
                      />
                    </>
                  </ConditionalComponent>

                  <ConditionalComponent isValid={field.type === FieldType.NUMBER}>
                    <>
                      <WhiteStyledTextField
                        label="Valeur minimale"
                        type="number"
                        value={field.validations?.min || ""}
                        onChange={(e) => handleValidationChange("min", Number.parseInt(e.target.value, 10) || "")}
                        fullWidth
                        size="small"
                        disabled={readOnly}
                      />
                      <WhiteStyledTextField
                        label="Valeur maximale"
                        type="number"
                        value={field.validations?.max || ""}
                        onChange={(e) => handleValidationChange("max", Number.parseInt(e.target.value, 10) || "")}
                        fullWidth
                        size="small"
                        disabled={readOnly}
                      />
                    </>
                  </ConditionalComponent>

                  <ConditionalComponent isValid={field.type === FieldType.TEXT || field.type === FieldType.EMAIL}>
                    <WhiteStyledTextField
                      label="Expression régulière (pattern)"
                      value={field.validations?.pattern || ""}
                      onChange={(e) => handleValidationChange("pattern", e.target.value)}
                      fullWidth
                      size="small"
                      disabled={readOnly}
                      helperText={field.type === FieldType.EMAIL ? "Pattern par défaut pour les emails" : ""}
                    />
                  </ConditionalComponent>
                </Stack>
              </AccordionDetails>
            </Accordion>
          </ConditionalComponent>

          {/* Conditional logic */}
          <Accordion>
            <AccordionSummary expandIcon={<ExpandMoreIcon />}>
              <Typography>Logique conditionnelle</Typography>
            </AccordionSummary>
            <AccordionDetails>
              <Stack spacing={2}>
                <StyledFormControl fullWidth size="small" disabled={readOnly || availableFieldIds.length === 0}>
                  <StyledInputLabel>Dépend du champ</StyledInputLabel>
                  <StyledSelect
                    sx={{
                      fontSize: pxToRem(13),
                    }}
                    value={field.conditionalLogic?.dependsOn || ""}
                    
                    onChange={(e) =>
                      handleConditionalLogicChange(
                        e.target.value as string,
                        field.conditionalLogic?.showWhen?.operator || "equals",
                        field.conditionalLogic?.showWhen?.value || "",
                      )
                    }
                    labelId="Dépend du champ"
                  >
                    <StyledMenuItem value="">Aucun</StyledMenuItem>
                    {availableFieldIds.map((fieldId) => (
                      <StyledMenuItem key={fieldId} value={fieldId}>
                        {fieldId}
                      </StyledMenuItem>
                    ))}
                  </StyledSelect>
                </StyledFormControl>

                <ConditionalComponent isValid={!!field.conditionalLogic?.dependsOn}>
                  <>
                    <StyledFormControl fullWidth size="small" disabled={readOnly}>
                      <StyledInputLabel>Opérateur</StyledInputLabel>
                      <StyledSelect
                        sx={{
                          fontSize: pxToRem(13),
                        }}
                        value={field.conditionalLogic?.showWhen?.operator || "equals"}
                        onChange={(e) =>
                          handleConditionalLogicChange(
                            field.conditionalLogic?.dependsOn || "",
                            e.target.value as string,
                            field.conditionalLogic?.showWhen?.value || "",
                          )
                        }
                        labelId="Opérateur"
                      >
                        <StyledMenuItem value="equals">Est égal à</StyledMenuItem>
                        <StyledMenuItem value="notEquals">Est différent de</StyledMenuItem>
                        <StyledMenuItem value="contains">Contient</StyledMenuItem>
                        <StyledMenuItem value="greaterThan">Est supérieur à</StyledMenuItem>
                        <StyledMenuItem value="lessThan">Est inférieur à</StyledMenuItem>
                      </StyledSelect>
                    </StyledFormControl>

                    <WhiteStyledTextField
                      label="Valeur"
                      value={field.conditionalLogic?.showWhen?.value || ""}
                      onChange={(e) =>
                        handleConditionalLogicChange(
                          field.conditionalLogic?.dependsOn || "",
                          field.conditionalLogic?.showWhen?.operator || "equals",
                          e.target.value,
                        )
                      }
                      fullWidth
                      size="small"
                      disabled={readOnly}
                    />
                  </>
                </ConditionalComponent>

                <ConditionalComponent isValid={availableFieldIds.length === 0}>
                  <Typography variant="caption" color="text.secondary">
                    <FontAwesomeIcon icon={faInfoCircle} /> Aucun autre champ disponible pour la logique conditionnelle.
                  </Typography>
                </ConditionalComponent>
              </Stack>
            </AccordionDetails>
          </Accordion>
        </Stack>

        {/* Section specific options */}
        <ConditionalComponent isValid={field.type === FieldType.SECTION}>
          <>
            <Typography variant="subtitle2" sx={{ mt: 3, mb: 1 }}>
              Propriétés de la section
            </Typography>

            <Grid container spacing={2}>
              <Grid item xs={12}>
                <WhiteStyledTextField
                  label="Titre de la section"
                  value={field.sectionTitle || field.label}
                  onChange={(e) => {
                    const value = e.target.value
                    onUpdateField({
                      ...field,
                      label: value,
                      sectionTitle: value,
                    })
                  }}
                  fullWidth
                  disabled={readOnly}
                />
              </Grid>

              <Grid item xs={12}>
                <WhiteStyledTextField
                  label="Description de la section"
                  value={field.sectionDescription || ""}
                  onChange={(e) => {
                    onUpdateField({
                      ...field,
                      sectionDescription: e.target.value,
                    })
                  }}
                  fullWidth
                  multiline
                  rows={3}
                  disabled={readOnly}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <StyledFormControl fullWidth>
                  <StyledInputLabel>Style</StyledInputLabel>
                  <StyledSelect
                    value={field.sectionStyle || "default"}
                    onChange={(e) => {
                      onUpdateField({
                        ...field,
                        sectionStyle: e.target.value as "default" | "card" | "outlined" | "filled",
                      })
                    }}
                    labelId="Style"
                    disabled={readOnly}
                  >
                    <StyledMenuItem value="default">Standard</StyledMenuItem>
                    <StyledMenuItem value="card">Carte</StyledMenuItem>
                    <StyledMenuItem value="outlined">Bordure</StyledMenuItem>
                    <StyledMenuItem value="filled">Rempli</StyledMenuItem>
                  </StyledSelect>
                </StyledFormControl>
              </Grid>

              <Grid item xs={12} md={6}>
                <FormControlLabel
                  control={
                    <Switch
                      checked={field.sectionCollapsible || false}
                      onChange={(e) => {
                        onUpdateField({
                          ...field,
                          sectionCollapsible: e.target.checked,
                        })
                      }}
                      disabled={readOnly}
                    />
                  }
                  label="Section repliable"
                />

                <ConditionalComponent isValid={!!field.sectionCollapsible}>
                  <FormControlLabel
                    control={
                      <Switch
                        checked={field.sectionCollapsed || false}
                        onChange={(e) => {
                          onUpdateField({
                            ...field,
                            sectionCollapsed: e.target.checked,
                          })
                        }}
                        disabled={readOnly}
                      />
                    }
                    label="Repliée par défaut"
                  />
                </ConditionalComponent>
              </Grid>

              <Grid item xs={12}>
                <FormControlLabel
                  control={
                    <Switch
                      checked={field.columns === 2}
                      onChange={(e) => {
                        onUpdateField({
                          ...field,
                          columns: e.target.checked ? 2 : 1,
                        })
                      }}
                      disabled={readOnly}
                    />
                  }
                  label="Disposition sur deux colonnes"
                />
              </Grid>
            </Grid>
          </>
        </ConditionalComponent>

        {/* Dialog for adding options */}
        <Dialog open={openOptionDialog} onClose={() => setOpenOptionDialog(false)}>
          <DialogTitle>Ajouter une option</DialogTitle>
          <DialogContent>
            <Stack spacing={2} sx={{ pt: 1 }}>
              <WhiteStyledTextField
                label="Valeur"
                value={newOption.value}
                onChange={(e) => setNewOption({ ...newOption, value: e.target.value })}
                fullWidth
                autoFocus
              />
              <WhiteStyledTextField
                label="Libellé"
                value={newOption.label}
                onChange={(e) => setNewOption({ ...newOption, label: e.target.value })}
                fullWidth
              />
            </Stack>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setOpenOptionDialog(false)}>Annuler</Button>
            <Button onClick={handleAddOption} variant="contained" disabled={!newOption.value || !newOption.label}>
              Ajouter
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    </Box>
  )
}
