/**
 * Standalone PiP Page
 *
 * A minimal page designed to be opened as a popup window.
 * Shows active sessions and upcoming shifts in real-time.
 * Can be kept visible while browsing other sites.
 */
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import Chip from '@mui/material/Chip';
import Avatar from '@mui/material/Avatar';
import Tooltip from '@mui/material/Tooltip';
import Collapse from '@mui/material/Collapse';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import CssBaseline from '@mui/material/CssBaseline';
import LinearProgress from '@mui/material/LinearProgress';
import MinimizeIcon from '@mui/icons-material/Minimize';
import RefreshIcon from '@mui/icons-material/Refresh';
import WorkIcon from '@mui/icons-material/Work';
import CoffeeIcon from '@mui/icons-material/Coffee';
import ScheduleIcon from '@mui/icons-material/Schedule';
import GroupsIcon from '@mui/icons-material/Groups';
import VolumeUpIcon from '@mui/icons-material/VolumeUp';
import VolumeOffIcon from '@mui/icons-material/VolumeOff';
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
import axios from 'axios';
import { format } from 'date-fns';
import { de } from 'date-fns/locale';

// Types
interface ActiveSession {
  sessionId: number;
  userId: number;
  userName: string;
  userInitials: string;
  userPhoto: string | null;
  clockInTime: string;
  isOnBreak: boolean;
  shiftName?: string;
}

interface UpcomingShift {
  shiftId: number;
  shiftName: string;
  shiftStartTime: string;
  assignedCount: number;
  maxWorkers: number;
  isUserAssigned: boolean;
}

// Storage key
const STORAGE_KEY = 'zeiterfassung_standalone_pip';

// Theme - darker for popup window
const theme = createTheme({
  palette: {
    mode: 'light',
    primary: { main: '#1976d2' },
    success: { main: '#2e7d32' },
    warning: { main: '#ed6c02' },
    info: { main: '#0288d1' },
    background: {
      default: '#f5f5f5',
      paper: '#ffffff',
    },
  },
  typography: {
    fontSize: 13,
  },
  components: {
    MuiCssBaseline: {
      styleOverrides: {
        body: {
          margin: 0,
          padding: 0,
          overflow: 'hidden',
        },
      },
    },
  },
});

// Load settings
const loadSettings = () => {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) {
      return JSON.parse(saved);
    }
  } catch {}
  return { collapsed: false, soundEnabled: true };
};

// Save settings
const saveSettings = (settings: any) => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
  } catch {}
};

// Standalone PiP Component
const StandalonePip: React.FC = () => {
  const [collapsed, setCollapsed] = useState(() => loadSettings().collapsed);
  const [soundEnabled, setSoundEnabled] = useState(() => loadSettings().soundEnabled);
  const [sessions, setSessions] = useState<ActiveSession[]>([]);
  const [upcomingShifts, setUpcomingShifts] = useState<UpcomingShift[]>([]);
  const [loading, setLoading] = useState(true);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);
  const [error, setError] = useState<string | null>(null);

  const audioRef = useRef<HTMLAudioElement | null>(null);
  const prevSessionsRef = useRef<ActiveSession[]>([]);
  const isFirstFetch = useRef(true);

  // Fetch data
  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const [sessionsRes, shiftsRes] = await Promise.all([
        axios.get('/zeiterfassung/work-sessions/active'),
        axios.get('/zeiterfassung/dashboard/upcoming-shifts', { params: { hours: 6 } }),
      ]);

      // Transform sessions
      const newSessions: ActiveSession[] = sessionsRes.data.map((s: any) => ({
        sessionId: s.session_id,
        userId: s.user_id,
        userName: s.user_name,
        userInitials: s.user_initials,
        userPhoto: s.user_photo,
        clockInTime: s.clock_in_time,
        isOnBreak: s.is_on_break,
        shiftName: s.shift_name,
      }));

      // Play notification sound on status changes (not on initial load)
      if (soundEnabled && !isFirstFetch.current) {
        const prevSessions = prevSessionsRef.current;
        let shouldPlaySound = false;

        // Check for new sessions or break status changes
        for (const session of newSessions) {
          const prevSession = prevSessions.find(p => p.sessionId === session.sessionId);
          if (!prevSession) {
            // New session - someone clocked in
            shouldPlaySound = true;
            break;
          }
          // Check for break status change
          if (prevSession.isOnBreak !== session.isOnBreak) {
            shouldPlaySound = true;
            break;
          }
        }

        if (shouldPlaySound) {
          try {
            if (!audioRef.current) {
              audioRef.current = new Audio('/sounds/notification.mp3');
              audioRef.current.volume = 0.5;
            }
            audioRef.current.currentTime = 0;
            audioRef.current.play().catch(() => {});
          } catch {}
        }
      }

      isFirstFetch.current = false;
      prevSessionsRef.current = newSessions;

      setSessions(newSessions);

      // Transform upcoming shifts
      const newShifts: UpcomingShift[] = (shiftsRes.data || []).map((s: any) => ({
        shiftId: s.shiftId,
        shiftName: s.shiftName,
        shiftStartTime: s.shiftStartTime,
        assignedCount: s.assignedCount,
        maxWorkers: s.maxWorkers,
        isUserAssigned: s.isUserAssigned,
      }));
      setUpcomingShifts(newShifts);
      setLastUpdate(new Date());
    } catch {
      setError('Verbindungsfehler');
    } finally {
      setLoading(false);
    }
  }, [soundEnabled]);

  // Initial fetch and interval
  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 15000); // Faster refresh for popup
    return () => clearInterval(interval);
  }, [fetchData]);

  // Update window title with session count
  useEffect(() => {
    document.title = `(${sessions.length}) Live-Übersicht`;
  }, [sessions.length]);

  // Handle collapse toggle
  const handleToggleCollapse = () => {
    const newCollapsed = !collapsed;
    setCollapsed(newCollapsed);
    saveSettings({ collapsed: newCollapsed, soundEnabled });
  };

  // Handle sound toggle
  const handleToggleSound = () => {
    const newSoundEnabled = !soundEnabled;
    setSoundEnabled(newSoundEnabled);
    saveSettings({ collapsed, soundEnabled: newSoundEnabled });
  };

  // Open main dashboard
  const handleOpenDashboard = () => {
    window.open('/zeiterfassung?tab=dashboard', '_blank');
  };

  const workingCount = sessions.filter((s) => !s.isOnBreak).length;
  const breakCount = sessions.filter((s) => s.isOnBreak).length;

  return (
    <Box sx={{ height: '100vh', display: 'flex', flexDirection: 'column', bgcolor: 'background.default' }}>
      {/* Header */}
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          px: 1.5,
          py: 0.75,
          bgcolor: 'primary.main',
          color: 'white',
          cursor: 'move',
          WebkitAppRegion: 'drag', // For Electron-like dragging
        }}
      >
        <Typography variant="subtitle2" fontWeight="bold">
          Live-Übersicht
        </Typography>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, WebkitAppRegion: 'no-drag' }}>
          {lastUpdate && (
            <Typography variant="caption" sx={{ opacity: 0.7, mr: 1 }}>
              {format(lastUpdate, 'HH:mm:ss')}
            </Typography>
          )}
          <Tooltip title="Aktualisieren">
            <IconButton size="small" onClick={fetchData} sx={{ color: 'white' }}>
              <RefreshIcon
                fontSize="small"
                sx={{
                  animation: loading ? 'spin 1s linear infinite' : 'none',
                  '@keyframes spin': {
                    '0%': { transform: 'rotate(0deg)' },
                    '100%': { transform: 'rotate(360deg)' },
                  },
                }}
              />
            </IconButton>
          </Tooltip>
          <Tooltip title={soundEnabled ? 'Ton aus' : 'Ton an'}>
            <IconButton size="small" onClick={handleToggleSound} sx={{ color: 'white' }}>
              {soundEnabled ? <VolumeUpIcon fontSize="small" /> : <VolumeOffIcon fontSize="small" />}
            </IconButton>
          </Tooltip>
          <Tooltip title={collapsed ? 'Erweitern' : 'Minimieren'}>
            <IconButton size="small" onClick={handleToggleCollapse} sx={{ color: 'white' }}>
              <MinimizeIcon fontSize="small" />
            </IconButton>
          </Tooltip>
          <Tooltip title="Dashboard öffnen">
            <IconButton size="small" onClick={handleOpenDashboard} sx={{ color: 'white' }}>
              <OpenInNewIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      </Box>

      {/* Loading indicator */}
      {loading && <LinearProgress sx={{ height: 2 }} />}

      {/* Error message */}
      {error && (
        <Box sx={{ px: 1.5, py: 0.5, bgcolor: 'error.light', color: 'error.contrastText' }}>
          <Typography variant="caption">{error}</Typography>
        </Box>
      )}

      {/* Collapsed View */}
      {collapsed && (
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-around',
            py: 1.5,
            px: 2,
            bgcolor: 'background.paper',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <WorkIcon fontSize="small" color="success" />
            <Typography variant="h6" fontWeight="bold">
              {workingCount}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <CoffeeIcon fontSize="small" color="warning" />
            <Typography variant="h6" fontWeight="bold">
              {breakCount}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <ScheduleIcon fontSize="small" color="info" />
            <Typography variant="h6" fontWeight="bold">
              {upcomingShifts.length}
            </Typography>
          </Box>
        </Box>
      )}

      {/* Expanded View */}
      <Collapse in={!collapsed} sx={{ flex: 1, overflow: 'auto' }}>
        <Box sx={{ overflow: 'auto', height: '100%' }}>
          {/* Active Sessions */}
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              px: 1.5,
              py: 0.75,
              bgcolor: '#e8f5e9',
              borderBottom: '1px solid',
              borderColor: 'divider',
              position: 'sticky',
              top: 0,
              zIndex: 1,
            }}
          >
            <Typography variant="caption" fontWeight="bold" color="success.dark">
              AKTIV ({sessions.length})
            </Typography>
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Chip
                size="small"
                icon={<WorkIcon sx={{ fontSize: 12 }} />}
                label={workingCount}
                color="success"
                sx={{ height: 20, fontSize: '0.7rem' }}
              />
              {breakCount > 0 && (
                <Chip
                  size="small"
                  icon={<CoffeeIcon sx={{ fontSize: 12 }} />}
                  label={breakCount}
                  color="warning"
                  sx={{ height: 20, fontSize: '0.7rem' }}
                />
              )}
            </Box>
          </Box>

          <List dense disablePadding>
            {sessions.map((session) => (
              <ListItem
                key={session.sessionId}
                sx={{
                  py: 0.75,
                  px: 1.5,
                  borderBottom: '1px solid',
                  borderColor: 'divider',
                  bgcolor: session.isOnBreak ? 'warning.50' : 'transparent',
                }}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, width: '100%' }}>
                  <Avatar
                    src={session.userPhoto || undefined}
                    sx={{
                      width: 28,
                      height: 28,
                      fontSize: '0.7rem',
                      bgcolor: session.isOnBreak ? 'warning.main' : 'success.main',
                    }}
                  >
                    {session.userInitials}
                  </Avatar>
                  <Box sx={{ flex: 1, minWidth: 0 }}>
                    <Typography variant="body2" fontWeight="medium" noWrap>
                      {session.userName}
                    </Typography>
                    {session.shiftName && (
                      <Typography variant="caption" color="text.secondary" noWrap>
                        {session.shiftName}
                      </Typography>
                    )}
                  </Box>
                  {session.isOnBreak ? (
                    <CoffeeIcon sx={{ fontSize: 16, color: 'warning.main' }} />
                  ) : (
                    <WorkIcon sx={{ fontSize: 16, color: 'success.main' }} />
                  )}
                  <Typography variant="caption" color="text.secondary" sx={{ ml: 0.5 }}>
                    {format(new Date(session.clockInTime), 'HH:mm', { locale: de })}
                  </Typography>
                </Box>
              </ListItem>
            ))}
            {sessions.length === 0 && (
              <ListItem sx={{ py: 2, justifyContent: 'center' }}>
                <Typography variant="body2" color="text.secondary">
                  Keine aktiven Sitzungen
                </Typography>
              </ListItem>
            )}
          </List>

          {/* Upcoming Shifts */}
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              px: 1.5,
              py: 0.75,
              bgcolor: '#e3f2fd',
              borderBottom: '1px solid',
              borderColor: 'divider',
              position: 'sticky',
              top: 0,
              zIndex: 1,
            }}
          >
            <Typography variant="caption" fontWeight="bold" color="info.dark">
              KOMMEND ({upcomingShifts.length})
            </Typography>
            <Typography variant="caption" color="text.secondary">
              nächste 6h
            </Typography>
          </Box>

          <List dense disablePadding>
            {upcomingShifts.map((shift) => (
              <ListItem
                key={shift.shiftId}
                sx={{
                  py: 0.75,
                  px: 1.5,
                  borderBottom: '1px solid',
                  borderColor: 'divider',
                  bgcolor: shift.isUserAssigned ? '#e3f2fd' : 'transparent',
                }}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, width: '100%' }}>
                  <Typography variant="body2" fontWeight="bold" sx={{ minWidth: 50 }}>
                    {shift.shiftStartTime}
                  </Typography>
                  <Typography variant="body2" sx={{ flex: 1 }} noWrap>
                    {shift.shiftName}
                  </Typography>
                  <Chip
                    size="small"
                    icon={<GroupsIcon sx={{ fontSize: 10 }} />}
                    label={`${shift.assignedCount}/${shift.maxWorkers}`}
                    color={
                      shift.assignedCount >= shift.maxWorkers
                        ? 'success'
                        : shift.assignedCount >= shift.maxWorkers / 2
                        ? 'warning'
                        : 'error'
                    }
                    sx={{ height: 20, fontSize: '0.65rem' }}
                  />
                  {shift.isUserAssigned && (
                    <Chip
                      size="small"
                      label="DU"
                      color="primary"
                      sx={{ height: 20, fontSize: '0.65rem' }}
                    />
                  )}
                </Box>
              </ListItem>
            ))}
            {upcomingShifts.length === 0 && (
              <ListItem sx={{ py: 2, justifyContent: 'center' }}>
                <Typography variant="body2" color="text.secondary">
                  Keine Schichten in den nächsten 6h
                </Typography>
              </ListItem>
            )}
          </List>
        </Box>
      </Collapse>
    </Box>
  );
};

// App wrapper
const App: React.FC = () => {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <StandalonePip />
    </ThemeProvider>
  );
};

// Mount
const container = document.getElementById('app');
if (container) {
  const root = createRoot(container);
  root.render(<App />);
}
