import { useEffect, useMemo, useState } from 'react';
import {
  Alert,
  Box,
  Button,
  LinearProgress,
  Stack,
  Typography,
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import { useAppStore } from '../store/useAppStore';
import { applyCropToImages } from '../utils/cropUtils';

const BulkCropStep = () => {
  const navigate = useNavigate();
  const uploadedImages = useAppStore((state) => state.uploadedImages);
  const cropConfig = useAppStore((state) => state.cropConfig);
  const coverImageId = useAppStore((state) => state.coverImageId);
  const setCroppedImages = useAppStore((state) => state.setCroppedImages);
  const setError = useAppStore((state) => state.setError);
  const croppedImages = useAppStore((state) => state.croppedImages);
  const [processing, setProcessing] = useState(false);

  const targetImages = useMemo(
    () => uploadedImages.filter((img) => img.id !== coverImageId),
    [coverImageId, uploadedImages],
  );

  useEffect(() => {
    let cancelled = false;
    const shouldCrop = targetImages.length && cropConfig?.imageWidth;
    if (!shouldCrop) {
      setProcessing(false);
      setCroppedImages([]);
      return undefined;
    }
    const runCrop = async () => {
      setProcessing(true);
      try {
        const results = await applyCropToImages(targetImages, cropConfig);
        if (!cancelled) {
          setCroppedImages(results);
        }
      } catch (error) {
        if (!cancelled) {
          setError(error.message);
        }
      } finally {
        if (!cancelled) {
          setProcessing(false);
        }
      }
    };
    if (!croppedImages.length) {
      runCrop();
    }
    return () => {
      cancelled = true;
    };
  }, [
    cropConfig,
    croppedImages.length,
    setCroppedImages,
    setError,
    targetImages,
  ]);

  if (!uploadedImages.length) {
    return (
      <Stack spacing={2}>
        <Alert severity="info">Önce görselleri yükle ve crop alanını belirle.</Alert>
        <Button variant="contained" onClick={() => navigate('/')}>
          Başlangıca dön
        </Button>
      </Stack>
    );
  }

  if (targetImages.length && !cropConfig?.imageWidth) {
    return (
      <Stack spacing={2}>
        <Alert severity="warning">Crop ayarını kaydetmeden bu adıma geçemezsin.</Alert>
        <Button variant="contained" onClick={() => navigate('/crop')}>
          Crop adımına dön
        </Button>
      </Stack>
    );
  }

  if (!targetImages.length) {
    return (
      <Stack spacing={2}>
        <Alert severity="info">Kapak dışında crop uygulanacak görsel bulunmuyor. Bu adımı geçebilirsin.</Alert>
        <Button variant="contained" onClick={() => navigate('/ocr')}>
          OCR&apos;ye geç
        </Button>
      </Stack>
    );
  }

  return (
    <Stack spacing={4}>
      <Box textAlign="center">
        <Typography variant="h5" gutterBottom>
          Toplu crop işlemi
        </Typography>
        <Typography color="text.secondary">
          Tüm görsellere referans crop ayarı uygulanıyor.
        </Typography>
      </Box>
      <Box>
        <LinearProgress
          variant={processing ? 'indeterminate' : 'determinate'}
          value={processing ? 0 : 100}
          sx={{ height: 10, borderRadius: 5 }}
        />
        <Typography mt={2} align="center">
          {processing
            ? 'İşlem yapılıyor...'
            : `${croppedImages.length} görsel hazır.`}
        </Typography>
      </Box>
      <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} justifyContent="space-between">
        <Button variant="contained" onClick={() => navigate('/crop')}>
          Geri dön
        </Button>
        <Button
          variant="contained"
          onClick={() => navigate('/ocr')}
          disabled={!croppedImages.length || processing}
        >
          OCR&apos;ye geç
        </Button>
      </Stack>
    </Stack>
  );
};

export default BulkCropStep;
