/**
 * @ai-summary Desktop dialog for requesting account deletion with 30-day grace period
 */

import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  Alert,
  CircularProgress,
  Typography,
  Box,
} from '@mui/material';
import { useRequestDeletion } from '../hooks/useDeletion';

interface DeleteAccountDialogProps {
  open: boolean;
  onClose: () => void;
}

export const DeleteAccountDialog: React.FC<DeleteAccountDialogProps> = ({ open, onClose }) => {
  const [confirmationText, setConfirmationText] = useState('');
  const requestDeletionMutation = useRequestDeletion();

  // Clear form when dialog closes
  useEffect(() => {
    if (!open) {
      setConfirmationText('');
    }
  }, [open]);

  const handleSubmit = async () => {
    if (confirmationText !== 'DELETE') {
      return;
    }

    await requestDeletionMutation.mutateAsync({ confirmationText });
    onClose();
  };

  const isValid = confirmationText === 'DELETE';

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>Delete Account</DialogTitle>
      <DialogContent>
        <Alert severity="warning" sx={{ mb: 3 }}>
          <Typography variant="body2" sx={{ fontWeight: 600, mb: 1 }}>
            30-Day Grace Period
          </Typography>
          <Typography variant="body2">
            Your account will be scheduled for deletion in 30 days. You can cancel this request at any time during
            the grace period by logging back in.
          </Typography>
        </Alert>

        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <TextField
            label="Type DELETE to confirm"
            value={confirmationText}
            onChange={(e) => setConfirmationText(e.target.value)}
            fullWidth
            required
            helperText='Type the word "DELETE" (all caps) to confirm'
            error={confirmationText.length > 0 && confirmationText !== 'DELETE'}
          />
        </Box>
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button onClick={onClose} disabled={requestDeletionMutation.isPending}>
          Cancel
        </Button>
        <Button
          onClick={handleSubmit}
          color="error"
          variant="contained"
          disabled={!isValid || requestDeletionMutation.isPending}
          startIcon={requestDeletionMutation.isPending ? <CircularProgress size={20} /> : null}
        >
          {requestDeletionMutation.isPending ? 'Deleting...' : 'Delete Account'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};
