import { useState } from 'react';
import { 
  Dialog, 
  DialogTitle, 
  DialogContent, 
  DialogActions, 
  Button,
  Typography,
  Box,
  CircularProgress,
  Stack,
  useTheme,
  IconButton
} from '@mui/material';
import DownloadIcon from '@mui/icons-material/Download';
import SendIcon from '@mui/icons-material/Send';
import CloseIcon from '@mui/icons-material/Close';
import { AddButton, outlinedColor } from '@/shared/components/table/styles';
import { useContractGeneration } from '../hooks/use-contract-generation';
import type { ContractGenerationRequest } from '@/shared/types/contract';

interface ContractGenerationDialogProps {
  open: boolean;
  onClose: () => void;
  employeeId: number;
  employeeName: string;
  employeeDepartment?: string;
  employeePosition?: string;
  employeeSalary?: number;
}

export default function ContractGenerationDialog({ 
  open, 
  onClose, 
  employeeId,
  employeeName,
  employeeDepartment,
  employeePosition,
  employeeSalary
}: ContractGenerationDialogProps) {
  const theme = useTheme();
  const { isGenerating, isSendingToDocuSign, generateContract, sendToDocuSign, downloadContract } = useContractGeneration();

  const handleGenerate = async () => {
    const request: ContractGenerationRequest = {
      employeeId,
      contractType: 'CDI',
      startDate: new Date().toISOString().split('T')[0],
      salary: employeeSalary,
      position: employeePosition,
      department: employeeDepartment,
    };

    const response = await generateContract(request);
    if (response && response.downloadUrl) {
      await downloadContract(response.contractId);
    }
  };

  const handleSendToDocuSign = async () => {
    const request: ContractGenerationRequest = {
      employeeId,
      contractType: 'CDI',
      startDate: new Date().toISOString().split('T')[0],
      salary: employeeSalary,
      position: employeePosition,
      department: employeeDepartment,
      sendToDocuSign: true,
    };

    const response = await sendToDocuSign(request);
    if (response && response.docusignUrl) {
      // Optionally open DocuSign URL in new tab
      window.open(response.docusignUrl, '_blank');
    }
  };

  return (
    <Dialog 
      open={open} 
      onClose={onClose} 
      maxWidth="sm" 
      fullWidth
      PaperProps={{
        sx: {
          borderRadius: 2,
          boxShadow: theme.shadows[10]
        }
      }}
    >
      <DialogTitle sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        padding: theme.spacing(1, 2, 2)
      }}>
        <Typography variant="h6" fontWeight="medium">
          Générer contrat
        </Typography>
        <IconButton
          onClick={onClose} 
          disabled={isGenerating || isSendingToDocuSign}
        >
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      
      <DialogContent sx={{ padding: theme.spacing(3) }}>
        <Typography variant="body1" color="text.secondary" paragraph>
                 Vous êtes sur le point de générer le contrat pour l&apos;employé{' '}
          <Typography component="span" fontWeight="medium" color="text.primary">
            {employeeName}
          </Typography>.
          Veuillez choisir une action ci-dessous :
        </Typography>
        
        <Stack 
          direction={{ xs: 'column', sm: 'row' }} 
          spacing={2} 
          sx={{ 
            mt: 3,
            justifyContent: 'center',
            alignItems: 'center'
          }}
        >          
          <Button
            variant="outlined"
            size="large"
            color="secondary"
            startIcon={isSendingToDocuSign ? <CircularProgress size={20} color="inherit" /> : <SendIcon />}
            onClick={handleSendToDocuSign}
            disabled={isGenerating || isSendingToDocuSign}
            sx={{
              py: 1.5,
              ...outlinedColor
            }}
            fullWidth
          >
            Envoyer via DocuSign
          </Button>
          <AddButton
            variant="contained"
            size="large"
            startIcon={isGenerating ? <CircularProgress size={20} color="inherit" /> : <DownloadIcon />}
            onClick={handleGenerate}
            disabled={isGenerating || isSendingToDocuSign}
            sx={{py: 1.5}}
            fullWidth
          >
            Télécharger Contrat
          </AddButton>
        </Stack>
      </DialogContent>
      
    </Dialog>
  );
}