import React, { useState, useEffect } from 'react';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import CloseIcon from '@mui/icons-material/Close';
import SaveIcon from '@mui/icons-material/Save';

interface PlannerNotesDialogProps {
  open: boolean;
  onClose: () => void;
  assignmentId: number;
  currentNotes: string | null;
  userName: string;
  roleName?: string;
  onSave: (assignmentId: number, notes: string) => Promise<void>;
}

export const PlannerNotesDialog: React.FC<PlannerNotesDialogProps> = ({
  open,
  onClose,
  assignmentId,
  currentNotes,
  userName,
  roleName,
  onSave,
}) => {
  const [notes, setNotes] = useState(currentNotes || '');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    setNotes(currentNotes || '');
  }, [currentNotes, open]);

  const handleSave = async () => {
    setSaving(true);
    try {
      await onSave(assignmentId, notes);
      onClose();
    } catch (error) {
      console.error('Error saving planner notes:', error);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Typography variant="h6">
            Planner Notes
          </Typography>
          <IconButton onClick={onClose} size="small">
            <CloseIcon />
          </IconButton>
        </Box>
        <Typography variant="body2" color="text.secondary">
          {userName} {roleName && `- ${roleName}`}
        </Typography>
      </DialogTitle>

      <DialogContent>
        <TextField
          fullWidth
          multiline
          rows={4}
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          placeholder="Add notes for this worker..."
          variant="outlined"
          autoFocus
        />
      </DialogContent>

      <DialogActions>
        <Button onClick={onClose} disabled={saving}>
          Cancel
        </Button>
        <Button
          onClick={handleSave}
          variant="contained"
          startIcon={<SaveIcon />}
          disabled={saving}
        >
          {saving ? 'Saving...' : 'Save Notes'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};
