import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Typography,
  CircularProgress,
} from '@mui/material';
import { ICandidature } from '@/shared/types/candidature';
import { pxToRem } from '@/shared/theme/typography';
import { StyledTextField } from '@/shared/theme/css';
import ActionButtons from '@/shared/components/form/buttons-action';
import {  StyledDialog, StyledDialogTitle } from '../../../styles';
import { enqueueSnackbar } from 'notistack';
import { useCandidatesStore } from '@/shared/api/stores/hr-service/candidatesStore';

interface SendEmailModalProps {
  open: boolean;
  onClose: () => void;
  candidature: ICandidature;
  onSend: (subject: string, message: string) => void;
  useBackend?: boolean; // Feature flag for backend integration
}

export default function SendEmailModal({ 
  open, 
  onClose, 
  candidature,
  onSend,
  useBackend = false
}: SendEmailModalProps) {
  const [subject, setSubject] = useState<string>('');
  const [message, setMessage] = useState<string>('');

  // Backend integration
  const { sendEmailToCandidate, sendingEmail } = useCandidatesStore();

  const handleSubjectChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSubject(event.target.value);
  };

  const handleMessageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setMessage(event.target.value);
  };

  const handleSend = async () => {
    if (subject && message) {
      try {
        if (useBackend) {
          // Use backend API - use originalId (UUID) not display id
          await sendEmailToCandidate({
            candidateId: candidature.originalId || candidature.id,
            subject,
            message,
          });
        } else {
          // Use original mock function
          onSend(subject, message);
          enqueueSnackbar('Email envoyé avec succès', { variant: 'success' });
        }
        
        handleReset();
        onClose();
      } catch (error) {
        // Error is already handled in the store
        console.error('Error sending email:', error);
      }
    }
  };

  const handleReset = () => {
    setSubject('');
    setMessage('');
  };

  const isLoading = useBackend ? sendingEmail : false;

  return (
    <StyledDialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <StyledDialogTitle>
        Envoi d{"'"}un mail
      </StyledDialogTitle>
      <DialogContent>

        <Typography variant="subtitle2" sx={{ display: 'flex', justifyContent: 'center', mb: 2, fontWeight: (theme) => theme.typography.fontWeightSemiBold, }}>
          Destinataire: {candidature.nom} {candidature.prenom} ({candidature.email})
        </Typography>
        <StyledTextField
          fullWidth
          InputLabelProps={{
            shrink: true,
          }}
          label="Titre"
          value={subject}
          placeholder='Choisissez un titre'
          onChange={handleSubjectChange}
          sx={{ mb: 2, mt: 1 }}
          required
          disabled={isLoading}
        />
        <StyledTextField
          autoFocus
          margin="dense"
          id="description"
          label="Observation"
          InputLabelProps={{
            shrink: true,
          }}
          multiline
          rows={4}
          fullWidth
          value={message}
          onChange={handleMessageChange}
          placeholder="Ajoutez un message explicatif..."
          disabled={isLoading}
        />
      </DialogContent>
      <DialogActions>
        <ActionButtons 
          onSave={handleSend} 
          onCancel={onClose} 
          secoundButtonText="Confirmer"
          loading={isLoading}
        />
      </DialogActions>
    </StyledDialog>
  );
} 