import type React from "react"
import { Grid, Box, Button, SxProps, Theme } from "@mui/material"
import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType } from "@/shared/types/common"
import FontAwesome from "../fontawesome"
import { IAvenantUsager, IPreparationUsager } from "@/shared/types/usager"
import { FieldType } from "@/hooks/use-multiple-fields"
import { PassengerContact } from "@/shared/types/passenger"
import { AmendmentPassengerDetails } from "@/shared/types/ammendment-passenger"

interface DuplicableFieldProps {
  fieldType: FieldType
  field:
    | FormFieldType<IPreparationUsager>
    | FormFieldType<PassengerContact>
    | FormFieldType<AmendmentPassengerDetails>
  index: number
  value: string
  isReadOnly: boolean
  onChange: (type: FieldType, index: number, value: string) => void
  onAdd: (type: FieldType) => void
  onDelete: (type: FieldType, index: number) => void
  sx?: SxProps<Theme>
  formData: any
  error?: string
  onBlur?: (e: React.FocusEvent) => void;
}

const DuplicableField: React.FC<DuplicableFieldProps> = ({
  field,
  fieldType,
  index,
  value,
  isReadOnly,
  onChange,
  onAdd,
  onDelete,
  sx,
  formData,
  error,
  onBlur
}) => {
  return (
    <Grid item xs={12} sx={sx} sm={4} key={`${field.name}-${index}`}>
      <Box>
        <FormField
          formData={formData}
          field={{
            ...field,
            label: `${field.label} ${index + 1}`,
          }}
          value={value}
          onChange={(_, value) => onChange(fieldType, index, value)}
          isReadOnly={isReadOnly}
          error={error}
          onBlur={onBlur}
        />
        {index === 0 ? (
          <Button
            startIcon={<FontAwesome icon={faPlus} width={12} />}
            onClick={() => onAdd(fieldType)}
            disabled={isReadOnly}
            variant="text"
            sx={{
              textTransform: "none",
            }}
          >
            {`Ajouter un ${field.label}`}
          </Button>
        ) : (
          <Button
            startIcon={<FontAwesome icon={faTrash} width={12} />}
            onClick={() => onDelete(fieldType, index)}
            disabled={isReadOnly}
            variant="text"
            sx={{
              textTransform: "none",
              color: "error.main",
            }}
          >
            {`Supprimer ${field.label}`}
          </Button>
        )}
      </Box>
    </Grid>
  )
}

export default DuplicableField

