'use client';

import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  Stack,
  Tabs,
  Tab,
  TextField,
  Chip,
  Alert,
  CircularProgress,
  IconButton,
} from '@mui/material';
import { useState, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faFileWord,
  faFileExcel,
  faSave,
  faUpload,
  faTimes,
  faHistory,
  faLock,
  faUnlock,
  faExternalLinkAlt,
  faDownload,
} from '@fortawesome/free-solid-svg-icons';
import { formatDate } from '@/utils/format-time';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface DocumentEditorDialogProps {
  open: boolean;
  onClose: () => void;
  document: any;
  onUpdate: (file: File, metadata: any) => Promise<void>;
}

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`editor-tabpanel-${index}`}
      aria-labelledby={`editor-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ py: 3 }}>{children}</Box>}
    </div>
  );
}

export default function DocumentEditorDialog({
  open,
  onClose,
  document,
  onUpdate,
}: DocumentEditorDialogProps) {
  const [currentTab, setCurrentTab] = useState(0);
  const [isLocked, setIsLocked] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [updating, setUpdating] = useState(false);
  const [versionComment, setVersionComment] = useState('');
  const [documentHistory] = useState([
    {
      version: 'v2.0',
      date: new Date(),
      user: 'John Doe',
      comment: 'Mise à jour des données Q4',
    },
    {
      version: 'v1.5',
      date: new Date(Date.now() - 86400000 * 7),
      user: 'Jane Smith',
      comment: 'Corrections mineures',
    },
    {
      version: 'v1.0',
      date: new Date(Date.now() - 86400000 * 30),
      user: 'Admin',
      comment: 'Version initiale',
    },
  ]);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      setSelectedFile(event.target.files[0]);
    }
  };

  const handleUpdate = async () => {
    if (!selectedFile) {
      alert('Veuillez sélectionner un fichier');
      return;
    }

    if (!versionComment.trim()) {
      alert('Veuillez ajouter un commentaire de version');
      return;
    }

    setUpdating(true);
    try {
      await onUpdate(selectedFile, {
        versionComment,
        previousVersion: document.version || 'v1.0',
      });
      
      alert('✅ Document mis à jour avec succès !');
      setSelectedFile(null);
      setVersionComment('');
      onClose();
    } catch (error) {
      console.error('Erreur lors de la mise à jour:', error);
      alert('❌ Erreur lors de la mise à jour du document');
    } finally {
      setUpdating(false);
    }
  };

  const handleDownloadForEdit = () => {
    if (document?.downloadUrl) {
      window.open(document.downloadUrl, '_blank');
    }
  };

  const handleOpenInOffice = () => {
    // Intégration Microsoft Office 365 / Google Workspace
    const fileType = document?.fileType;
    
    if (fileType === 'word') {
      // Office 365 Word Online
      alert('🚀 Ouverture dans Microsoft Word Online...\n\nNote: Cette fonctionnalité nécessite une intégration Microsoft 365.');
    } else if (fileType === 'excel') {
      // Office 365 Excel Online
      alert('🚀 Ouverture dans Microsoft Excel Online...\n\nNote: Cette fonctionnalité nécessite une intégration Microsoft 365.');
    }
  };

  const getFileIcon = () => {
    if (document?.fileType === 'word') return faFileWord;
    if (document?.fileType === 'excel') return faFileExcel;
    return faFileWord;
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: {
          borderRadius: 3,
          minHeight: '600px',
        },
      }}
    >
      <DialogTitle
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          borderBottom: 1,
          borderColor: 'divider',
          pb: 2,
        }}
      >
        <Stack direction="row" alignItems="center" spacing={2}>
          <FontAwesomeIcon
            icon={getFileIcon()}
            style={{ fontSize: '28px', color: '#2196F3' }}
          />
          <Box>
            <Typography variant="h6" sx={{ fontWeight: 600 }}>
              {document?.name}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              Dernière modification: {document?.lastModified ? formatDate(document.lastModified) : 'N/A'}
            </Typography>
          </Box>
        </Stack>
        <Stack direction="row" spacing={1}>
          <ConditionalComponent isValid={isLocked}>
            <Chip
              icon={<FontAwesomeIcon icon={faLock} />}
              label="Verrouillé"
              color="error"
              size="small"
            />
          </ConditionalComponent>
          <ConditionalComponent isValid={!isLocked}>
            <Chip
              icon={<FontAwesomeIcon icon={faUnlock} />}
              label="Déverrouillé"
              color="success"
              size="small"
            />
          </ConditionalComponent>
          <IconButton onClick={onClose}>
            <FontAwesomeIcon icon={faTimes} />
          </IconButton>
        </Stack>
      </DialogTitle>

      <DialogContent sx={{ p: 0 }}>
        <Tabs
          value={currentTab}
          onChange={(_, newValue) => setCurrentTab(newValue)}
          sx={{
            borderBottom: 1,
            borderColor: 'divider',
            px: 3,
            pt: 2,
          }}
        >
          <Tab label="📝 Éditer" />
          <Tab label="📜 Historique" />
          <Tab label="ℹ️ Informations" />
        </Tabs>

        <Box sx={{ px: 3, minHeight: 400 }}>
          {/* Tab 1: Édition */}
          <TabPanel value={currentTab} index={0}>
            <Stack spacing={3}>
              <Alert severity="info" sx={{ borderRadius: 2 }}>
                <Typography variant="body2" sx={{ fontWeight: 500, mb: 1 }}>
                  💡 Options d&apos;édition disponibles:
                </Typography>
                <Typography variant="caption" component="div">
                  1. Éditer en ligne avec Office 365 (recommandé)<br />
                  2. Télécharger, modifier localement et ré-uploader<br />
                  3. Upload d&apos;une nouvelle version directement
                </Typography>
              </Alert>

              {/* Option 1: Office Online */}
              <Box
                sx={{
                  p: 3,
                  border: 2,
                  borderColor: 'primary.main',
                  borderRadius: 2,
                  bgcolor: 'primary.lighter',
                }}
              >
                <Stack spacing={2}>
                  <Stack direction="row" alignItems="center" spacing={2}>
                    <FontAwesomeIcon
                      icon={faExternalLinkAlt}
                      style={{ fontSize: '24px', color: '#2196F3' }}
                    />
                    <Box>
                      <Typography variant="h6" sx={{ fontWeight: 600 }}>
                        Éditer en ligne (Office 365)
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        Édition collaborative en temps réel
                      </Typography>
                    </Box>
                  </Stack>
                  <Button
                    variant="contained"
                    size="large"
                    startIcon={<FontAwesomeIcon icon={faExternalLinkAlt} />}
                    onClick={handleOpenInOffice}
                    fullWidth
                    sx={{ borderRadius: 2 }}
                  >
                    <ConditionalComponent isValid={document?.fileType === 'word'}>
                      Ouvrir dans Word Online
                    </ConditionalComponent>
                    <ConditionalComponent isValid={document?.fileType !== 'word'}>
                      Ouvrir dans Excel Online
                    </ConditionalComponent>
                  </Button>
                </Stack>
              </Box>

              {/* Option 2: Download & Re-upload */}
              <Box
                sx={{
                  p: 3,
                  border: 1,
                  borderColor: 'divider',
                  borderRadius: 2,
                }}
              >
                <Stack spacing={2}>
                  <Typography variant="h6" sx={{ fontWeight: 600 }}>
                    Télécharger et modifier localement
                  </Typography>
                  <Button
                    variant="outlined"
                    size="large"
                    startIcon={<FontAwesomeIcon icon={faDownload} />}
                    onClick={handleDownloadForEdit}
                    fullWidth
                    sx={{ borderRadius: 2 }}
                  >
                    Télécharger le document
                  </Button>
                </Stack>
              </Box>

              {/* Option 3: Direct Upload */}
              <Box
                sx={{
                  p: 3,
                  border: 1,
                  borderColor: 'divider',
                  borderRadius: 2,
                  bgcolor: 'background.neutral',
                }}
              >
                <Stack spacing={2}>
                  <Typography variant="h6" sx={{ fontWeight: 600 }}>
                    Uploader une nouvelle version
                  </Typography>
                  
                  <TextField
                    label="Commentaire de version"
                    multiline
                    rows={2}
                    fullWidth
                    value={versionComment}
                    onChange={(e) => setVersionComment(e.target.value)}
                    placeholder="Ex: Mise à jour des données Q4 2025"
                    sx={{ borderRadius: 2 }}
                  />

                  <Button
                    variant="contained"
                    component="label"
                    startIcon={<FontAwesomeIcon icon={faUpload} />}
                    fullWidth
                    sx={{ borderRadius: 2, py: 1.5 }}
                  >
                    Sélectionner le fichier modifié
                    <input
                      type="file"
                      hidden
                      accept={document?.fileType === 'word' ? '.doc,.docx' : '.xls,.xlsx,.csv'}
                      onChange={handleFileSelect}
                    />
                  </Button>

                  <ConditionalComponent isValid={!!selectedFile}>
                    <Alert severity="success" sx={{ borderRadius: 2 }}>
                      ✅ Fichier sélectionné: <strong>{selectedFile?.name}</strong>
                      <br />
                      Taille: {selectedFile ? (selectedFile.size / 1024).toFixed(2) : 0} KB
                    </Alert>
                  </ConditionalComponent>

                  <ConditionalComponent isValid={!!selectedFile && !!versionComment}>
                    <Button
                      variant="contained"
                      color="success"
                      size="large"
                      startIcon={
                        updating ? (
                          <CircularProgress size={20} color="inherit" />
                        ) : (
                          <FontAwesomeIcon icon={faSave} />
                        )
                      }
                      onClick={handleUpdate}
                      disabled={updating}
                      fullWidth
                      sx={{ borderRadius: 2, py: 1.5 }}
                    >
                      <ConditionalComponent isValid={updating}>
                        Mise à jour en cours...
                      </ConditionalComponent>
                      <ConditionalComponent isValid={!updating}>
                        Mettre à jour le document
                      </ConditionalComponent>
                    </Button>
                  </ConditionalComponent>
                </Stack>
              </Box>
            </Stack>
          </TabPanel>

          {/* Tab 2: Historique */}
          <TabPanel value={currentTab} index={1}>
            <Stack spacing={2}>
              <Typography variant="h6" sx={{ fontWeight: 600, mb: 2 }}>
                📜 Historique des versions
              </Typography>

              {documentHistory.map((version, index) => (
                <Box
                  key={index}
                  sx={{
                    p: 2.5,
                    border: 1,
                    borderColor: index === 0 ? 'primary.main' : 'divider',
                    borderRadius: 2,
                    bgcolor: index === 0 ? 'primary.lighter' : 'background.paper',
                  }}
                >
                  <Stack direction="row" justifyContent="space-between" alignItems="flex-start">
                    <Box>
                      <Stack direction="row" spacing={1} alignItems="center" sx={{ mb: 1 }}>
                        <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
                          {version.version}
                        </Typography>
                        <ConditionalComponent isValid={index === 0}>
                          <Chip label="Actuelle" size="small" color="primary" />
                        </ConditionalComponent>
                      </Stack>
                      <Typography variant="body2" color="text.secondary">
                        👤 {version.user}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        📅 {formatDate(version.date)}
                      </Typography>
                      <Typography variant="body2" sx={{ mt: 1, fontStyle: 'italic' }}>
                        💬 {version.comment}
                      </Typography>
                    </Box>
                    <ConditionalComponent isValid={index !== 0}>
                      <Button
                        size="small"
                        variant="outlined"
                        startIcon={<FontAwesomeIcon icon={faDownload} />}
                        sx={{ borderRadius: 2 }}
                      >
                        Restaurer
                      </Button>
                    </ConditionalComponent>
                  </Stack>
                </Box>
              ))}
            </Stack>
          </TabPanel>

          {/* Tab 3: Informations */}
          <TabPanel value={currentTab} index={2}>
            <Stack spacing={2}>
              <Typography variant="h6" sx={{ fontWeight: 600, mb: 2 }}>
                ℹ️ Informations du document
              </Typography>

              <Box
                sx={{
                  p: 3,
                  border: 1,
                  borderColor: 'divider',
                  borderRadius: 2,
                  bgcolor: 'background.neutral',
                }}
              >
                <Stack spacing={2}>
                  <Stack direction="row" justifyContent="space-between">
                    <Typography color="text.secondary">Nom:</Typography>
                    <Typography fontWeight={600}>{document?.name}</Typography>
                  </Stack>
                  <Stack direction="row" justifyContent="space-between">
                    <Typography color="text.secondary">Type:</Typography>
                    <ConditionalComponent isValid={document?.fileType === 'word'}>
                      <Typography fontWeight={600}>Microsoft Word</Typography>
                    </ConditionalComponent>
                    <ConditionalComponent isValid={document?.fileType !== 'word'}>
                      <Typography fontWeight={600}>Microsoft Excel</Typography>
                    </ConditionalComponent>
                  </Stack>
                  <Stack direction="row" justifyContent="space-between">
                    <Typography color="text.secondary">Taille:</Typography>
                    <Typography fontWeight={600}>{document?.size}</Typography>
                  </Stack>
                  <Stack direction="row" justifyContent="space-between">
                    <Typography color="text.secondary">Créé par:</Typography>
                    <Typography fontWeight={600}>{document?.addedBy}</Typography>
                  </Stack>
                  <Stack direction="row" justifyContent="space-between">
                    <Typography color="text.secondary">Date de création:</Typography>
                    <ConditionalComponent isValid={!!document?.addedDate}>
                      <Typography fontWeight={600}>{formatDate(document.addedDate)}</Typography>
                    </ConditionalComponent>
                    <ConditionalComponent isValid={!document?.addedDate}>
                      <Typography fontWeight={600}>N/A</Typography>
                    </ConditionalComponent>
                  </Stack>
                  <Stack direction="row" justifyContent="space-between">
                    <Typography color="text.secondary">Véhicule:</Typography>
                    <Typography fontWeight={600}>{document?.vehicleId || 'Non associé'}</Typography>
                  </Stack>
                  <Stack direction="row" justifyContent="space-between">
                    <Typography color="text.secondary">Type de document:</Typography>
                    <Typography fontWeight={600}>
                      {document?.documentType || 'Non spécifié'}
                    </Typography>
                  </Stack>
                </Stack>
              </Box>

              <Alert severity="warning" sx={{ borderRadius: 2 }}>
                <Typography variant="body2">
                  ⚠️ <strong>Note importante:</strong> Les modifications apportées à ce document
                  créeront une nouvelle version. L&apos;ancienne version sera conservée dans l&apos;historique.
                </Typography>
              </Alert>
            </Stack>
          </TabPanel>
        </Box>
      </DialogContent>

      <DialogActions sx={{ px: 3, py: 2, borderTop: 1, borderColor: 'divider' }}>
        <Button
          onClick={onClose}
          variant="outlined"
          sx={{ borderRadius: 2, px: 3 }}
        >
          Fermer
        </Button>
      </DialogActions>
    </Dialog>
  );
}



