import { useEffect, useMemo, useRef, 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 { segmentOcrText, translateChunkToTurkish } from '../utils/translationUtils';

const TranslationStep = () => {
  const navigate = useNavigate();
  const ocrText = useAppStore((state) => state.ocrText);
  const bookMetadata = useAppStore((state) => state.bookMetadata);
  const translatedText = useAppStore((state) => state.translatedText);
  const translationStatus = useAppStore((state) => state.translationStatus);
  const translationError = useAppStore((state) => state.translationError);
  const translationProgress = useAppStore((state) => state.translationProgress);
  const setTranslatedText = useAppStore((state) => state.setTranslatedText);
  const setTranslationStatus = useAppStore((state) => state.setTranslationStatus);
  const setTranslationError = useAppStore((state) => state.setTranslationError);
  const setTranslationProgress = useAppStore((state) => state.setTranslationProgress);
  const clearTranslation = useAppStore((state) => state.clearTranslation);
  const [trigger, setTrigger] = useState(0);
  const previewRef = useRef(null);

  useEffect(() => {
    if (previewRef.current) {
      previewRef.current.scrollTop = previewRef.current.scrollHeight;
    }
  }, [translatedText]);

  useEffect(() => {
    if (!ocrText?.trim()) return;
    if (!trigger) return;
    let cancelled = false;
    const sections = segmentOcrText(ocrText);
    if (!sections.length) {
      setTranslationStatus('error');
      setTranslationError('Çevrilecek metin bulunamadı.');
      return undefined;
    }

    const runTranslation = async () => {
      setTranslationStatus('running');
      setTranslationError(null);
      setTranslationProgress(0);
      setTranslatedText('');
      try {
        const translatedChunks = [];
        for (let index = 0; index < sections.length; index += 1) {
          if (cancelled) return;
          const chunk = sections[index];
          // eslint-disable-next-line no-await-in-loop
          const translated = await translateChunkToTurkish(chunk);
          if (cancelled) return;
          translatedChunks[index] = translated;
          const combined = translatedChunks.filter(Boolean).join('\n\n');
          setTranslatedText(combined);
          setTranslationProgress(Math.round(((index + 1) / sections.length) * 100));
        }
        if (!cancelled) {
          setTranslationStatus('done');
        }
      } catch (error) {
        if (!cancelled) {
          setTranslationStatus('error');
          setTranslationError(error.message || 'Çeviri tamamlanamadı.');
        }
      }
    };

    runTranslation();

    return () => {
      cancelled = true;
    };
  }, [ocrText, setTranslatedText, setTranslationError, setTranslationProgress, setTranslationStatus, trigger]);

  const handleStart = () => {
    if (!ocrText?.trim()) return;
    clearTranslation();
    setTrigger((prev) => prev + 1);
  };

  const handleRetry = () => {
    handleStart();
  };

  const summaryLine = useMemo(() => {
    if (!translationStatus || translationStatus === 'idle') {
      return 'OCR çıktısı Türkçe\'ye çevrilmek üzere parçalanıyor.';
    }
    if (translationStatus === 'running') {
      return 'GLM 4.6 API ile çeviri devam ediyor.';
    }
    if (translationStatus === 'done') {
      return 'Çeviri tamamlandı. EPUB adımına geçebilirsin.';
    }
    if (translationStatus === 'error') {
      return 'Çeviri sırasında bir sorun oluştu.';
    }
    return '';
  }, [translationStatus]);

  if (!ocrText?.trim()) {
    return (
      <Stack spacing={2}>
        <Alert severity="info">Çevrilecek metin bulunamadı. OCR adımını tamamla.</Alert>
        <Button variant="contained" onClick={() => navigate('/ocr')}>
          OCR adımına dön
        </Button>
      </Stack>
    );
  }

  return (
    <Stack spacing={4}>
      {bookMetadata && (
        <Typography variant="body2" color="success.main">
          Seçilen kitap: <strong>{bookMetadata.title}</strong>
          {bookMetadata.authors?.length ? ` • ${bookMetadata.authors.join(', ')}` : ''}
        </Typography>
      )}
      <Box textAlign="center">
        <Typography variant="h5">Çeviri</Typography>
        <Typography color="text.secondary">{summaryLine}</Typography>
        <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} mt={2} justifyContent="center">
          <Button
            variant="contained"
            onClick={handleStart}
            disabled={!ocrText?.trim() || translationStatus === 'running'}
          >
            {translationStatus === 'done' ? 'Çeviriyi Yenile' : 'Çeviriyi Başlat'}
          </Button>
        </Stack>
      </Box>
      {translationStatus === 'running' && (
        <Box>
          <LinearProgress variant="determinate" value={translationProgress} sx={{ height: 10, borderRadius: 5 }} />
          <Typography mt={1} align="center" variant="caption" color="text.secondary">
            %{translationProgress} tamamlandı
          </Typography>
        </Box>
      )}
      {translationStatus === 'error' && translationError && (
        <Alert severity="error">
          {translationError}
          <Button size="small" sx={{ ml: 2 }} variant="outlined" onClick={handleRetry}>
            Tekrar dene
          </Button>
        </Alert>
      )}
      {translationStatus === 'done' && (
        <Alert severity="success">Çeviri tamamlandı. EPUB adımına geçebilirsin.</Alert>
      )}
      <Box sx={{ p: 2, borderRadius: 2, bgcolor: 'background.default' }}>
        <Typography variant="subtitle1">Çeviri önizlemesi</Typography>
        <Box
          ref={previewRef}
          sx={{
            mt: 1,
            maxHeight: '8.5em',
            overflowY: 'auto',
            whiteSpace: 'pre-wrap',
            lineHeight: 1.5,
            fontSize: '0.95rem',
            color: 'text.secondary',
            pr: 1,
            border: '1px solid',
            borderColor: 'divider',
            borderRadius: 1.5,
            p: 1.5,
          }}
        >
          {translationStatus === 'done'
            ? translatedText
            : translatedText
              ? translatedText
              : 'Çeviri bekleniyor...'}
        </Box>
      </Box>

      <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} justifyContent="space-between">
        <Button variant="contained" onClick={() => navigate('/ocr')}>
          OCR&apos;ye dön
        </Button>
        <Button
          variant="contained"
          onClick={() => navigate('/epub')}
          disabled={!ocrText?.trim() || translationStatus === 'running'}
        >
          EPUB adımına geç
        </Button>
      </Stack>
    </Stack>
  );
};

export default TranslationStep;
