import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
  Alert,
  Box,
  Button,
  Container,
  Link,
  Menu,
  MenuItem,
  Paper,
  Snackbar,
  Stack,
  Step,
  StepLabel,
  Stepper,
  Typography,
} from '@mui/material';
import { useEffect, useMemo, useState } from 'react';
import { useAppStore } from './store/useAppStore';
import { fetchCurrentUser, loginWithGoogle, logoutUser } from './utils/authApi';
import { supabaseClient } from './lib/supabaseClient';

export const wizardSteps = [
  { label: 'Yükle', path: '/' },
  { label: 'Crop', path: '/crop' },
  { label: 'Toplu Crop', path: '/bulk-crop' },
  { label: 'OCR', path: '/ocr' },
  { label: 'EPUB Oluştur', path: '/epub' },
  { label: 'İndir', path: '/download' },
];

const App = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const error = useAppStore((state) => state.error);
  const clearError = useAppStore((state) => state.clearError);
  const initializeAuth = useAppStore((state) => state.initializeAuth);
  const updateCurrentUser = useAppStore((state) => state.updateCurrentUser);
  const clearAuthSession = useAppStore((state) => state.clearAuthSession);
  const setAuthSession = useAppStore((state) => state.setAuthSession);
  const setStoreError = useAppStore((state) => state.setError);
  const currentUser = useAppStore((state) => state.currentUser);
  const authToken = useAppStore((state) => state.authToken);
  const [menuAnchor, setMenuAnchor] = useState(null);

  const handleSnackbarClose = (_, reason) => {
    if (reason === 'clickaway') return;
    clearError();
  };

  useEffect(() => {
    initializeAuth();
  }, [initializeAuth]);

  useEffect(() => {
    const syncUser = async () => {
      if (!authToken) return;
      try {
        const response = await fetchCurrentUser(authToken);
        if (response?.user) {
          updateCurrentUser(response.user);
        }
      } catch (error) {
        console.warn('Oturum doğrulanamadı:', error.message);
        clearAuthSession();
      }
    };
    syncUser();
  }, [authToken, clearAuthSession, updateCurrentUser]);

  useEffect(() => {
    if (!supabaseClient) return undefined;

    const exchangeGoogleSession = async (session) => {
      if (!session || !session.access_token || authToken) return;
      try {
        const response = await loginWithGoogle(session.access_token);
        setAuthSession(response);
      } catch (error) {
        setStoreError(error.message);
      } finally {
        await supabaseClient.auth.signOut();
      }
    };

    supabaseClient.auth.getSession().then(({ data }) => {
      exchangeGoogleSession(data.session);
    });

    const { data: subscription } = supabaseClient.auth.onAuthStateChange((event, session) => {
      if (event === 'SIGNED_IN') {
        exchangeGoogleSession(session);
      }
    });

    return () => {
      subscription.subscription.unsubscribe();
    };
  }, [authToken, setAuthSession, setStoreError]);

  const activeStep = useMemo(() => {
    const foundIndex = wizardSteps.findIndex((step) => step.path === location.pathname);
    return foundIndex === -1 ? 0 : foundIndex;
  }, [location.pathname]);

  const handleMenuOpen = (event) => {
    setMenuAnchor(event.currentTarget);
  };

  const handleMenuClose = () => setMenuAnchor(null);

  const handleLogout = async () => {
    try {
      if (authToken) {
        await logoutUser(authToken);
      }
    } catch (error) {
      console.warn('Çıkış işlemi sırasında hata:', error.message);
    } finally {
      clearAuthSession();
      handleMenuClose();
      navigate('/');
    }
  };

  return (
    <>
      <Box
        component="header"
        sx={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          zIndex: 1200,
          backgroundColor: '#FFFFFF',
          borderBottom: '1px solid #E0DFDC',
          boxShadow: '0 6px 12px rgba(0,0,0,0.04)',
        }}
      >
        <Container maxWidth="lg">
          <Stack direction="row" alignItems="center" justifyContent="space-between" py={1.5}>
            <Typography
              variant="h4"
              sx={{
                fontFamily: '"Caudex", serif',
                color: '#1C1815',
                fontWeight: 700,
                letterSpacing: 1,
              }}
            >
              imagepub
            </Typography>
            <Stack direction="row" spacing={3} alignItems="center">
              {currentUser ? (
                <>
                  <Typography
                    component="button"
                    type="button"
                    onClick={handleMenuOpen}
                    sx={{
                      background: 'none',
                      border: 'none',
                      color: '#2F2D28',
                      fontWeight: 600,
                      fontSize: '0.95rem',
                      cursor: 'pointer',
                      textTransform: 'none',
                      letterSpacing: 0.5,
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1,
                      transition: 'color 0.2s ease',
                      '&:hover': { color: '#d7b16a' },
                    }}
                  >
                    {currentUser.username}
                    <Box component="i" className="fa-solid fa-chevron-down" sx={{ fontSize: '0.85rem', color: 'inherit' }} />
                  </Typography>
                  <Menu anchorEl={menuAnchor} open={Boolean(menuAnchor)} onClose={handleMenuClose}>
                    <MenuItem disabled>Hesap Ayarlarım</MenuItem>
                    <MenuItem disabled>EPUB'larım</MenuItem>
                    <MenuItem onClick={handleLogout}>Çıkış</MenuItem>
                  </Menu>
                </>
              ) : (
                <>
                  <Typography
                    component="button"
                    type="button"
                    onClick={() => navigate('/login')}
                    sx={{
                      background: 'none',
                      border: 'none',
                      color: '#2F2D28',
                      fontWeight: 600,
                      fontSize: '0.95rem',
                      cursor: 'pointer',
                      textTransform: 'none',
                      letterSpacing: 0.5,
                      transition: 'color 0.2s ease',
                      '&:hover': { color: '#d7b16a' },
                    }}
                  >
                    Login
                  </Typography>
                  <Button variant="contained" color="primary" size="small" onClick={() => navigate('/register')}>
                    Register
                  </Button>
                </>
              )}
            </Stack>
          </Stack>
        </Container>
      </Box>
      <Container maxWidth="lg" sx={{ pt: 14, pb: 6 }}>
        <Box mb={5} textAlign="center">
          <Typography
            variant="h3"
            sx={{
              fontWeight: 700,
              color: '#1C1815',
              letterSpacing: -0.5,
              fontSize: { xs: '1.9rem', md: '2.6rem' },
            }}
          >
            Tek ekranda görselden EPUB'a kadar tüm sihirbaz adımları
          </Typography>
          <Typography
            sx={{
              mt: 1.5,
              color: '#5A5751',
              fontSize: { xs: '1rem', md: '1.2rem' },
              lineHeight: 1.6,
              maxWidth: 720,
              mx: 'auto',
            }}
          >
            Kapak seç, crop alanını belirle, OCR ile Türkçe metinleri koru ve sonucunu tek tıkla EPUB olarak indir. imgpub tüm işlemleri tek bir akışta toplar, hızlı ve modern bir deneyim sunar.
          </Typography>
        </Box>
        <Paper sx={{ p: { xs: 2, md: 4 }, mb: 4 }} elevation={0}>
          <Stepper activeStep={activeStep} alternativeLabel>
            {wizardSteps.map((step) => (
              <Step key={step.path} onClick={() => navigate(step.path)} sx={{ cursor: 'pointer' }}>
                <StepLabel>{step.label}</StepLabel>
              </Step>
            ))}
          </Stepper>
        </Paper>
        <Paper sx={{ p: { xs: 2, md: 4 }, minHeight: 400 }} elevation={0}>
          <Outlet />
        </Paper>
        <Snackbar open={Boolean(error)} autoHideDuration={4000} onClose={handleSnackbarClose}>
          <Alert onClose={handleSnackbarClose} severity="error" sx={{ width: '100%' }}>
            {error}
          </Alert>
        </Snackbar>
      </Container>
    </>
  );
};

export default App;
