import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  Box,
  Divider,
  Chip,
  Paper
} from '@mui/material';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { 
  Person, 
  Assignment, 
  Schedule,
  CheckCircle 
} from '@mui/icons-material';

interface ViewFormResponsesModalProps {
  open: boolean;
  onClose: () => void;
  submissionId: string;
}

interface FormResponse {
  id: string;
  candidateName: string;
  formTitle: string;
  formDescription: string;
  sentDate: string;
  completedDate?: string;
  isCompleted: boolean;
  responses: FieldResponse[];
}

interface FieldResponse {
  fieldId: string;
  fieldLabel: string;
  fieldType: string;
  response: string | string[];
  required: boolean;
}

export default function ViewFormResponsesModal({
  open,
  onClose,
  submissionId
}: ViewFormResponsesModalProps) {
  const [formResponse, setFormResponse] = useState<FormResponse | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (open && submissionId) {
      fetchFormResponse();
    }
  }, [open, submissionId]);

  const fetchFormResponse = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/api/hr/forms/submissions/${submissionId}/responses`);
      const data = await response.json();
      setFormResponse(data);
    } catch (error) {
      console.error('Error fetching form response:', error);
    } finally {
      setLoading(false);
    }
  };

  const renderFieldResponse = (fieldResponse: FieldResponse) => {
    const { fieldType, response, fieldLabel } = fieldResponse;

    const renderValue = () => {
      if (!response || (Array.isArray(response) && response.length === 0)) {
        return <em style={{ color: '#999' }}>Pas de réponse</em>;
      }

      switch (fieldType) {
        case 'SELECT':
        case 'RADIO':
          return <Chip label={response as string} size="small" />;
        
        case 'CHECKBOX':
          const checkboxResponses = Array.isArray(response) ? response : [response];
          return (
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              {checkboxResponses.map((item, index) => (
                <Chip key={index} label={item} size="small" variant="outlined" />
              ))}
            </Box>
          );
        
        case 'FILE':
          return (
            <Button 
              variant="outlined" 
              size="small"
              onClick={() => window.open(response as string, '_blank')}
            >
              📎 Voir le fichier
            </Button>
          );
        
        case 'RATING':
          const rating = parseInt(response as string, 10);
          return (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              {'⭐'.repeat(rating)}
              <Typography variant="body2">({rating}/5)</Typography>
            </Box>
          );
        
        case 'CONSENT':
          return (
            <Chip 
              label={response === 'true' ? 'Accepté' : 'Refusé'} 
              color={response === 'true' ? 'success' : 'error'}
              size="small"
            />
          );
        
        case 'DATE':
          return new Date(response as string).toLocaleDateString();
        
        default:
          return <Typography variant="body2">{response}</Typography>;
      }
    };

    return (
      <Paper key={fieldResponse.fieldId} sx={{ p: 2, mb: 2 }}>
        <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 'bold' }}>
          {fieldLabel}
          {fieldResponse.required && <span style={{ color: 'red' }}> *</span>}
        </Typography>
        {renderValue()}
      </Paper>
    );
  };

  if (loading) {
    return (
      <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
        <DialogContent>
          <Typography>Chargement...</Typography>
        </DialogContent>
      </Dialog>
    );
  }

  if (!formResponse) {
    return (
      <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
        <DialogContent>
          <Typography>Formulaire non trouvé</Typography>
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Assignment />
          <div>
            <Typography variant="h6">{formResponse.formTitle}</Typography>
            <Typography variant="body2" color="text.secondary">
              Réponses de {formResponse.candidateName}
            </Typography>
          </div>
        </Box>
      </DialogTitle>

      <DialogContent>
        {/* Informations générales */}
        <Box sx={{ mb: 3 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
            <Person fontSize="small" />
            <Typography variant="body2">
              <strong>Candidat:</strong> {formResponse.candidateName}
            </Typography>
          </Box>
          
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
            <Schedule fontSize="small" />
            <Typography variant="body2">
              <strong>Envoyé:</strong> {new Date(formResponse.sentDate).toLocaleString()}
            </Typography>
          </Box>
          
          <ConditionalComponent isValid={Boolean(formResponse.isCompleted && formResponse.completedDate)}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
              <CheckCircle fontSize="small" color="success" />
              <Typography variant="body2">
                <strong>Complété:</strong> {formResponse.completedDate && new Date(formResponse.completedDate).toLocaleString()}
              </Typography>
            </Box>
          </ConditionalComponent>

          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            {formResponse.formDescription}
          </Typography>
        </Box>

        <Divider sx={{ mb: 3 }} />

        {/* Réponses */}
        <Typography variant="h6" sx={{ mb: 2 }}>
          Réponses ({formResponse.responses.length} champs)
        </Typography>

        <ConditionalComponent isValid={formResponse.responses.length === 0}>
          <Typography color="text.secondary" sx={{ textAlign: 'center', py: 4 }}>
            Aucune réponse disponible
          </Typography>
        </ConditionalComponent>

        <ConditionalComponent isValid={formResponse.responses.length > 0}>
          <Box>
            {formResponse.responses.map(renderFieldResponse)}
          </Box>
        </ConditionalComponent>
      </DialogContent>

      <DialogActions>
        <Button onClick={onClose}>Fermer</Button>
        <Button 
          variant="contained" 
          onClick={() => {
            // Export PDF ou Excel
            window.print();
          }}
        >
          Exporter PDF
        </Button>
      </DialogActions>
    </Dialog>
  );
}
