"use client"

import { useState, useEffect } from "react"
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  Box,
} from "@mui/material"

interface RenameDocumentDialogProps {
  open: boolean
  onClose: () => void
  onRename: (newName: string) => void
  initialName: string
}

export default function RenameDocumentDialog({
  open,
  onClose,
  onRename,
  initialName,
}: RenameDocumentDialogProps) {
  const [name, setName] = useState(initialName)

  useEffect(() => {
    setName(initialName)
  }, [initialName])

  const handleSubmit = () => {
    if (name.trim() && name !== initialName) {
      onRename(name.trim())
    }
    onClose()
  }

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === "Enter") {
      handleSubmit()
    }
  }

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>Renommer le document</DialogTitle>
      <DialogContent>
        <Box sx={{ pt: 1 }}>
          <TextField
            autoFocus
            fullWidth
            label="Nom du document"
            value={name}
            onChange={(e) => setName(e.target.value)}
            onKeyPress={handleKeyPress}
            variant="outlined"
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} color="inherit">
          Annuler
        </Button>
        <Button 
          onClick={handleSubmit} 
          variant="contained" 
          disabled={!name.trim() || name === initialName}
        >
          Renommer
        </Button>
      </DialogActions>
    </Dialog>
  )
}