import React, { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Grid';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import CircularProgress from '@mui/material/CircularProgress';
import Alert from '@mui/material/Alert';

import PhotoCameraRoundedIcon from '@mui/icons-material/PhotoCameraRounded';
import DeleteRoundedIcon from '@mui/icons-material/DeleteRounded';
import CloudUploadRoundedIcon from '@mui/icons-material/CloudUploadRounded';
import NavigateBeforeRoundedIcon from '@mui/icons-material/NavigateBeforeRounded';
import NavigateNextRoundedIcon from '@mui/icons-material/NavigateNextRounded';

import { uploadFile } from '../hooks/useApi';

const MAX_IMAGES = 10;
const MAX_SIZE_MB = 5;
const MAX_SIZE_BYTES = MAX_SIZE_MB * 1024 * 1024;
const ACCEPTED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];

/**
 * Step 6 – Media / Photos.
 *
 * Allows vendors to upload up to 10 images (drag & drop or click).
 * The first image is used as the main product photo.
 *
 * NOTE: The original compiled bundle (Step6Media-DS8wUzgj.js) was missing
 * from the build output. This component has been reconstructed based on
 * the translation keys, the step_6 data schema referenced in Step7Publish,
 * and the uploadFile API.
 */
export default function Step6Media({ wizardData, updateStepData, onNext, onBack, isMobile }) {
  const { t } = useTranslation();
  const stepData = wizardData.step_6 || {};
  const images = stepData.images || [];

  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState(null);

  /* ── Validate and upload ───────────────────────────────────── */
  const handleFiles = useCallback(
    async (files) => {
      setError(null);
      const remaining = MAX_IMAGES - images.length;
      const toUpload = Array.from(files).slice(0, remaining);

      for (const file of toUpload) {
        if (!ACCEPTED_TYPES.includes(file.type)) {
          setError(t('step6.invalidFormat'));
          continue;
        }
        if (file.size > MAX_SIZE_BYTES) {
          setError(t('step6.fileTooLarge'));
          continue;
        }

        setUploading(true);
        try {
          const result = await uploadFile(file);
          const newImages = [...(stepData.images || []), { id: result.id, url: result.url }];
          updateStepData('step_6', { ...stepData, images: newImages });
        } catch (err) {
          setError(err.message || t('common.error'));
        } finally {
          setUploading(false);
        }
      }
    },
    [images, stepData, updateStepData, t],
  );

  const handleDelete = useCallback(
    (index) => {
      const newImages = images.filter((_, i) => i !== index);
      updateStepData('step_6', { ...stepData, images: newImages });
    },
    [images, stepData, updateStepData],
  );

  /* ── Drag & drop handlers ──────────────────────────────────── */
  const [dragging, setDragging] = useState(false);

  const onDragOver = (e) => {
    e.preventDefault();
    setDragging(true);
  };

  const onDragLeave = () => setDragging(false);

  const onDrop = (e) => {
    e.preventDefault();
    setDragging(false);
    if (e.dataTransfer.files.length > 0) {
      handleFiles(e.dataTransfer.files);
    }
  };

  const onFileSelect = (e) => {
    if (e.target.files.length > 0) {
      handleFiles(e.target.files);
    }
  };

  return (
    <Box sx={{ py: { xs: 2, md: 4 } }}>
      <Typography variant="h5" component="h2" fontWeight="bold" textAlign="center" sx={{ mb: 1 }}>
        {t('step6.title')}
      </Typography>
      <Typography variant="body1" color="text.secondary" textAlign="center" sx={{ mb: 4 }}>
        {t('step6.subtitle')}
      </Typography>

      <Box sx={{ maxWidth: 800, mx: 'auto' }}>
        {error && (
          <Alert severity="error" onClose={() => setError(null)} sx={{ mb: 3 }}>
            {error}
          </Alert>
        )}

        {/* ── Drop zone ────────────────────────────────────── */}
        <Card
          variant="outlined"
          onDragOver={onDragOver}
          onDragLeave={onDragLeave}
          onDrop={onDrop}
          sx={{
            mb: 4,
            border: '2px dashed',
            borderColor: dragging ? 'primary.main' : 'grey.300',
            backgroundColor: dragging ? 'primary.50' : 'grey.50',
            transition: 'all 0.2s ease',
            cursor: images.length >= MAX_IMAGES ? 'not-allowed' : 'pointer',
            opacity: images.length >= MAX_IMAGES ? 0.5 : 1,
          }}
        >
          <CardContent
            sx={{ textAlign: 'center', py: 6 }}
            onClick={() => {
              if (images.length < MAX_IMAGES) {
                document.getElementById('wahrb-media-input').click();
              }
            }}
          >
            <input
              id="wahrb-media-input"
              type="file"
              accept={ACCEPTED_TYPES.join(',')}
              multiple
              onChange={onFileSelect}
              style={{ display: 'none' }}
            />
            {uploading ? (
              <>
                <CircularProgress size={48} sx={{ mb: 2 }} />
                <Typography>{t('step6.uploading')}</Typography>
              </>
            ) : (
              <>
                <CloudUploadRoundedIcon sx={{ fontSize: 56, color: 'primary.main', mb: 2 }} />
                <Typography variant="h6" gutterBottom>
                  {t('step6.dropzone')}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  {t('step6.maxSize')}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  {t('step6.formats')}
                </Typography>
              </>
            )}
          </CardContent>
        </Card>

        {/* ── Image grid ───────────────────────────────────── */}
        {images.length > 0 && (
          <>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              {t('step6.reorder')}
            </Typography>
            <Grid container spacing={2}>
              {images.map((img, index) => (
                <Grid item xs={6} sm={4} md={3} key={img.id || index}>
                  <Card sx={{ position: 'relative', overflow: 'hidden' }}>
                    <Box
                      component="img"
                      src={img.url}
                      alt={`Photo ${index + 1}`}
                      sx={{
                        width: '100%',
                        height: 140,
                        objectFit: 'cover',
                        display: 'block',
                      }}
                    />
                    {index === 0 && (
                      <Box
                        sx={{
                          position: 'absolute',
                          top: 4,
                          left: 4,
                          bgcolor: 'primary.main',
                          color: 'white',
                          fontSize: '0.65rem',
                          px: 1,
                          py: 0.25,
                          borderRadius: 1,
                          fontWeight: 'bold',
                        }}
                      >
                        PRINCIPALE
                      </Box>
                    )}
                    <IconButton
                      size="small"
                      onClick={() => handleDelete(index)}
                      sx={{
                        position: 'absolute',
                        top: 4,
                        right: 4,
                        bgcolor: 'rgba(255,255,255,0.85)',
                        '&:hover': { bgcolor: 'error.light', color: 'white' },
                      }}
                    >
                      <DeleteRoundedIcon fontSize="small" />
                    </IconButton>
                  </Card>
                </Grid>
              ))}
            </Grid>
          </>
        )}
      </Box>

      {/* ═══ Navigation ═══ */}
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          mt: 4,
          pt: 3,
          borderTop: '1px solid',
          borderColor: 'divider',
        }}
      >
        <Button variant="outlined" onClick={onBack} startIcon={<NavigateBeforeRoundedIcon />}>
          {t('wizard.buttons.previous')}
        </Button>
        <Button variant="contained" onClick={onNext} endIcon={<NavigateNextRoundedIcon />}>
          {t('wizard.buttons.next')}
        </Button>
      </Box>
    </Box>
  );
}
