import { useEffect, useMemo, useState } from 'react';
import { Box, Button, Chip, Grid, Paper, Stack, Typography } from '@mui/material';
import { createSocketClient } from '../lib/socketClient';
import { useAppStore } from '../store/useAppStore';
import { fetchTranslationModelsAdmin, setActiveTranslationModelAdmin } from '../utils/adminApi';

const AdminPage = () => {
  const authToken = useAppStore((state) => state.authToken);
  const currentUser = useAppStore((state) => state.currentUser);
  const [stats, setStats] = useState({ activeUsers: 0, totalUsers: 0 });
  const [models, setModels] = useState([]);
  const [loadingModel, setLoadingModel] = useState(false);
  const [logs, setLogs] = useState([]);

  const activeModel = useMemo(() => models.find((m) => m.active)?.id || null, [models]);

  useEffect(() => {
    if (!authToken) return undefined;
    const loadModels = async () => {
      try {
        const response = await fetchTranslationModelsAdmin(authToken);
        setModels(response.models || []);
      } catch (error) {
        console.warn('Modeller alınamadı:', error.message);
      }
    };
    loadModels();
  }, [authToken]);

  useEffect(() => {
    if (!authToken) return undefined;
    const client = createSocketClient(authToken);
    client.connect();
    const off = client.subscribeAdminEvents({
      onStatsUpdate: (payload) => {
        setStats({
          activeUsers: payload?.activeUsers ?? 0,
          totalUsers: payload?.totalUsers ?? 0,
        });
      },
      onModelChanged: (payload) => {
        setModels((prev) =>
          prev.map((model) => ({
            ...model,
            active: model.id === payload?.active,
          })),
        );
      },
      onEpubGenerated: (payload) => {
        pushLog('EPUB', `EPUB üretildi: ${payload?.filename || '-'} (${payload?.email || 'kullanıcı'})`);
      },
      onEpubFailed: (payload) => {
        pushLog('EPUB', `EPUB başarısız: ${payload?.message || 'bilinmiyor'} (${payload?.email || 'kullanıcı'})`, true);
      },
      onTranslateCompleted: (payload) => {
        pushLog('ÇEVİRİ', `Çeviri tamamlandı (${payload?.model || 'aktif'}) - ${payload?.email || 'kullanıcı'}`);
      },
      onTranslateFailed: (payload) => {
        pushLog('ÇEVİRİ', `Çeviri hatası: ${payload?.message || 'bilinmiyor'} (${payload?.email || 'kullanıcı'})`, true);
      },
      onUserRegistered: (payload) => {
        const name = payload?.name || '';
        const info = name ? `${payload?.email || 'bilinmiyor'} | ${name}` : payload?.email || 'bilinmiyor';
        pushLog('KAYIT', `Yeni kullanıcı: ${info}`);
      },
      onPresenceUpdate: (payload) => {
        if (payload?.email && currentUser?.email && payload.email === currentUser.email) {
          return;
        }
        const action = payload?.active ? 'Aktif oldu' : 'Çıkış yaptı';
        const namePart = payload?.name ? ` | ${payload.name}` : '';
        pushLog('OTURUM', `${action}: ${payload?.email || 'kullanıcı'}${namePart}`);
      },
    });
    return () => {
      off?.();
      client.disconnect();
    };
  }, [authToken, currentUser]);

  const pushLog = (tag, message, isError = false) => {
    setLogs((prev) => [
      {
        id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
        ts: new Date(),
        tag,
        message,
        isError,
      },
      ...prev.slice(0, 49),
    ]);
  };

  const handleModelSwitch = async (modelId) => {
    setLoadingModel(true);
    try {
      const response = await setActiveTranslationModelAdmin(modelId, authToken);
      setModels(response.models || []);
    } catch (error) {
      console.warn('Model değiştirilemedi:', error.message);
    } finally {
      setLoadingModel(false);
    }
  };

  const displayLogs = useMemo(() => {
    if (logs.length >= 5) return logs;
    const base = [...logs];
    while (base.length < 5) {
      const idx = base.length;
      base.push({
        id: `placeholder-${idx}`,
        ts: null,
        tag: '',
        message: idx === 0 ? 'Log bekleniyor...' : '',
        isError: false,
        placeholder: true,
      });
    }
    return base;
  }, [logs]);

  return (
    <Box sx={{ mt: 10, display: 'flex', justifyContent: 'center' }}>
      <Paper
        sx={{
          p: 4,
          minWidth: 360,
          display: 'flex',
          flexDirection: 'column',
          gap: 2,
          alignItems: 'center',
        }}
      >
        <Chip label="Yönetim Alanı" color="secondary" size="small" />
        <Stack spacing={1} sx={{ alignItems: 'center' }}>
          <Typography variant="body1" color="text.secondary" align="center">
            Canlı veriler soket bağlantısı alanları
          </Typography>
        </Stack>
        <Grid container spacing={2} sx={{ mt: 2 }}>
          <Grid item xs={12} sm={6}>
            <Paper
              variant="outlined"
              sx={{
                p: 2,
                textAlign: 'center',
                borderColor: '#E7C179',
              }}
            >
              <Typography variant="subtitle2" color="text.secondary">
                Toplam Kullanıcı
              </Typography>
              <Typography variant="h4" sx={{ fontWeight: 700, mt: 0.5 }}>
                {stats.totalUsers}
              </Typography>
            </Paper>
          </Grid>
          <Grid item xs={12} sm={6}>
            <Paper
              variant="outlined"
              sx={{
                p: 2,
                textAlign: 'center',
                borderColor: '#29615D',
              }}
            >
              <Typography variant="subtitle2" color="text.secondary">
                Aktif Kullanıcı (canlı)
              </Typography>
              <Typography variant="h4" sx={{ fontWeight: 700, mt: 0.5 }}>
                {stats.activeUsers}
              </Typography>
            </Paper>
          </Grid>
        </Grid>
        <Paper
          variant="outlined"
          sx={{
            mt: 3,
            p: 2,
            width: '100%',
          }}
        >
          <Typography variant="subtitle1" sx={{ fontWeight: 700, mb: 1 }}>
            Çeviri Modelleri
          </Typography>
          <Grid container spacing={2}>
            {models.map((model) => (
              <Grid item xs={12} sm={6} md={4} key={model.id}>
                <Paper
                  variant="outlined"
                  sx={{
                    p: 2,
                    height: '100%',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: 1,
                    borderColor: model.active ? '#29615D' : '#E0DFDC',
                  }}
                >
                  <Stack direction="row" spacing={1} alignItems="center" justifyContent="space-between">
                    <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
                      {model.label}
                    </Typography>
                    {model.active && <Chip label="Aktif" color="success" size="small" />}
                  </Stack>
                  <Typography variant="body2" color="text.secondary">
                    {model.configured ? 'API anahtarı tanımlı' : 'API anahtarı eksik (.env)'}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    Env: {model.requiredEnv?.join(', ') || '-'}
                  </Typography>
                  <Box sx={{ flexGrow: 1 }} />
                  <Button
                    variant="contained"
                    color="secondary"
                    size="small"
                    disabled={!model.configured || model.active || loadingModel}
                    onClick={() => handleModelSwitch(model.id)}
                    sx={{ mt: 1 }}
                  >
                    Bu modeli kullan
                  </Button>
                </Paper>
              </Grid>
            ))}
          </Grid>
        </Paper>
        <Paper
          variant="outlined"
          sx={{
            mt: 3,
            p: 0,
            width: '100%',
            bgcolor: '#0c0d10',
            color: '#d1d5db',
            borderRadius: '1.2rem',
            borderColor: '#1f2937',
            boxShadow: '0 12px 24px rgba(0,0,0,0.28)',
            overflow: 'hidden',
          }}
        >
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 1.5,
              px: 2,
              py: 1.1,
              borderBottom: '1px solid #1f2937',
              bgcolor: '#111318',
              borderTopLeftRadius: '1.2rem',
              borderTopRightRadius: '1.2rem',
            }}
          >
            <Box
              component="i"
              className="fa-solid fa-terminal"
              sx={{ color: '#10b981', fontSize: '1rem' }}
            />
            <Typography variant="subtitle1" sx={{ fontWeight: 700, color: '#e5e7eb' }}>
              Canlı Log
            </Typography>
            <Chip
              label={`Aktif: ${stats.activeUsers}`}
              size="small"
              icon={<Box component="i" className="fa-solid fa-plug" sx={{ fontSize: '0.75rem', color: '#10b981' }} />}
              sx={{
                bgcolor: '#112019',
                color: '#a7f3d0',
                '& .MuiChip-icon': { ml: 0.5 },
              }}
            />
            <Chip
              label={`Toplam: ${stats.totalUsers}`}
              size="small"
              icon={<Box component="i" className="fa-solid fa-users" sx={{ fontSize: '0.75rem', color: '#93c5fd' }} />}
              sx={{
                bgcolor: '#111827',
                color: '#dbeafe',
                '& .MuiChip-icon': { ml: 0.5 },
              }}
            />
          </Box>
          <Box
            sx={{
              maxHeight: 200,
              minHeight: 200,
              overflowY: 'auto',
              fontFamily: 'SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
              px: 2,
              py: 1.2,
              my: '3px',
              '&::-webkit-scrollbar': {
                width: 8,
              },
              '&::-webkit-scrollbar-thumb': {
                background: 'rgba(17,19,24,0.5)',
                borderRadius: 999,
              },
              '&::-webkit-scrollbar-track': {
                background: 'rgba(0,0,0,0.15)',
                marginTop: 3,
                marginBottom: 3,
              },
            }}
          >
            {displayLogs.map((log) => {
              const isPlaceholder = Boolean(log.placeholder);
              const chipStyles = (() => {
                if (log.tag === 'KAYIT') {
                  return { bg: '#0f3d2e', color: '#b9f6ca' };
                }
                if (log.tag === 'OTURUM') {
                  if (log.message?.toLowerCase().includes('aktif oldu')) {
                    return { bg: '#5a3200', color: '#ffd7a3' };
                  }
                  if (log.message?.toLowerCase().includes('çıkış yaptı')) {
                    return { bg: '#4a0f0f', color: '#fecdd3' };
                  }
                }
                return { bg: log.isError ? '#7f1d1d' : '#1f2937', color: log.isError ? '#fecaca' : '#9ca3af' };
              })();

              return (
                <Stack
                  key={log.id}
                  direction="row"
                  spacing={isPlaceholder ? 0.25 : 0.5}
                  alignItems="center"
                  sx={{
                    color: log.isError ? '#fca5a5' : '#d1d5db',
                    fontSize: '0.95rem',
                    py: 0.5,
                    borderBottom: '1px solid #111318',
                  }}
                >
                  <Typography variant="caption" sx={{ color: '#6b7280', minWidth: isPlaceholder ? 0 : 60 }}>
                    {log.ts ? log.ts.toLocaleTimeString() : ''}
                  </Typography>
                  {log.tag ? (
                    <Chip
                      label={log.tag}
                      size="small"
                      sx={{
                        bgcolor: chipStyles.bg,
                        color: chipStyles.color,
                      }}
                    />
                  ) : (
                    <Box
                      sx={{
                        minWidth: isPlaceholder ? 0 : 4,
                        height: 24,
                      }}
                    />
                  )}
                  <Typography
                    component="span"
                    variant="body2"
                    sx={{
                      color: log.placeholder ? '#6b7280' : 'inherit',
                      display: 'block',
                      width: '100%',
                    }}
                  >
                    {log.message}
                  </Typography>
                </Stack>
              );
            })}
          </Box>
        </Paper>
      </Paper>
    </Box>
  );
};

export default AdminPage;
