import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  TextField,
  Typography,
  SelectChangeEvent,
} from '@mui/material';
import { IFormulaire, ICandidature } from '@/shared/types/candidature';
import { _formulaires } from '@/shared/_mock/_candidature';
import {
  StyledFormControl,
  StyledInputLabel,
  StyledMenuItem,
  StyledSelect,
  StyledTextField,
} from '@/shared/theme/css';
import { pxToRem } from '@/shared/theme/typography';
import ActionButtons from '@/shared/components/form/buttons-action';
import { StyledDialogTitle, StyledDialog } from '../../../styles';
import { enqueueSnackbar } from 'notistack';
import { useCandidatesStore } from '@/shared/api/stores/hr-service/candidatesStore';
import { useFormsStore } from '@/shared/api/stores/hr-service/formsStore';

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

export default function SendFormModal({ 
  open, 
  onClose, 
  candidature,
  onSend,
  useBackend = false
}: SendFormModalProps) {
  const [selectedFormulaire, setSelectedFormulaire] = useState<string>('');
  const [observation, setObservation] = useState<string>('');
  const [selectedFormulaireError, setSelectedFormulaireError] = useState<string | null>(null)

  // Backend integration
  const { sendFormToCandidate, sendingForm } = useCandidatesStore();
  const { forms, fetchForms, loading: formsLoading } = useFormsStore();

  // Mock data fallback
  const [formulaires] = useState<IFormulaire[]>(_formulaires);

  // Fetch forms when modal opens and using backend
  useEffect(() => {
    if (open && useBackend) {
      fetchForms();
    }
  }, [open, useBackend, fetchForms]);

  // Convert backend forms to frontend format for compatibility
  const availableForms = useBackend 
    ? (forms || []).map(form => ({
        id: String(form.id), // Convert numeric ID to string
        nom: form.title, // Backend uses 'title' not 'name'
        description: form.description,
        lien: '', // Backend doesn't have 'link' field, could use description or empty
      }))
    : formulaires;

  const handleFormulaireChange = (event: SelectChangeEvent<unknown>) => {
    setSelectedFormulaire(event.target.value as string);
    setSelectedFormulaireError(null);
  };

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

  const handleSend = async () => {
    if (selectedFormulaire) {
      try {
        // Always use the onSend prop - this will handle both backend and mock
        await onSend(selectedFormulaire, observation);
        
        // Show success message only for mock (backend handles its own success/error messages)
        if (!useBackend) {
          enqueueSnackbar('Formulaire envoyé avec succès', { variant: 'success' });
        }
        
        handleReset();
        onClose();
      } catch (error: any) {
        const backendCode = error?.code ?? error?.response?.data?.code;
        const backendMessage = error?.message ?? error?.response?.data?.message;
        if (backendCode === '001') {
          // Critère d'acceptation: marquer le champ comme invalide
          setSelectedFormulaireError("Ce formulaire a déjà été envoyé à ce candidat");
          return;
        } else {
          const message = backendMessage || "Erreur lors de l'envoi du formulaire";
          enqueueSnackbar(message, { variant: 'error' });
        }
      }
    }
  };

  const handleReset = () => {
    setSelectedFormulaire('');
    setObservation('');
  };

  const isLoading = useBackend ? (sendingForm || formsLoading) : false;

  return (
    <StyledDialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <StyledDialogTitle >
        Envoyer un Formulaire Supplémentaire
      </StyledDialogTitle>
      <DialogContent>
        <Typography
          variant="subtitle2"
          sx={{
            display: 'flex',
            justifyContent: 'center',
            mb: 2,
            fontWeight: (theme) => theme.typography.fontWeightSemiBold,
          }}
        >
          Candidat: {candidature.nom} {candidature.prenom}
        </Typography>

        <StyledFormControl fullWidth sx={{ mb: 2, mt: 1 }}>
          <StyledInputLabel id="formulaire-select-label">
            Formulaire <span style={{ color: '#FF0000' }}> *</span>
          </StyledInputLabel>
          <StyledSelect
            labelId="formulaire-select-label"
            id="formulaire-select"
            value={selectedFormulaire}
            onChange={handleFormulaireChange}
            required
            displayEmpty
            disabled={isLoading}
            error={!!selectedFormulaireError}
          >
            {availableForms?.map((form) => (
              <StyledMenuItem key={form.id} value={form.id}>
                {form.nom}
              </StyledMenuItem>
            ))}
          </StyledSelect>
          {selectedFormulaireError && (
            <Typography variant="caption" color="error" sx={{ mt: 0.5 }}>
              {selectedFormulaireError}
            </Typography>
          )}
        </StyledFormControl>

        <StyledTextField
          fullWidth
          label="Observation"
          InputLabelProps={{
            shrink: true,
          }}
          multiline
          rows={4}
          value={observation}
          onChange={handleObservationChange}
          placeholder="Ajoutez un message explicatif pour le candidat..."
          disabled={isLoading}
        />
      </DialogContent>
      <DialogActions>
        <ActionButtons 
          onSave={handleSend} 
          onCancel={onClose} 
          secoundButtonText="Confirmer" 
          loading={isLoading}
        />
      </DialogActions>
    </StyledDialog>
  );
}
