/**
 * Document Picture-in-Picture Component
 *
 * Uses the Document Picture-in-Picture API to create a true floating
 * overlay that stays on top of all windows, like Spotify's Canvas PiP.
 *
 * Falls back to popup window for unsupported browsers.
 */
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { CacheProvider } from '@emotion/react';
import createCache, { EmotionCache } from '@emotion/cache';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import Avatar from '@mui/material/Avatar';
import LinearProgress from '@mui/material/LinearProgress';
import Chip from '@mui/material/Chip';
import CloseIcon from '@mui/icons-material/Close';
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 OpenInFullIcon from '@mui/icons-material/OpenInFull';
import VolumeUpIcon from '@mui/icons-material/VolumeUp';
import VolumeOffIcon from '@mui/icons-material/VolumeOff';
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;
}

// Theme for PiP window
const pipTheme = createTheme({
  palette: {
    mode: 'dark',
    primary: { main: '#1db954' }, // Spotify green style
    background: {
      default: 'transparent',
      paper: 'rgba(18, 18, 18, 0.95)',
    },
  },
  typography: {
    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
  },
});

// Check if Document PiP is supported
export const isDocumentPipSupported = (): boolean => {
  return 'documentPictureInPicture' in window;
};

// PiP Content Component
interface PipContentProps {
  sessions: ActiveSession[];
  loading: boolean;
  onRefresh: () => void;
  onClose: () => void;
  onExpand: () => void;
  onToggleSound: () => void;
  soundEnabled: boolean;
  lastUpdate: Date | null;
}

const PipContent: React.FC<PipContentProps> = ({
  sessions,
  loading,
  onRefresh,
  onClose,
  onExpand,
  onToggleSound,
  soundEnabled,
  lastUpdate,
}) => {
  const workingCount = sessions.filter((s) => !s.isOnBreak).length;
  const breakCount = sessions.filter((s) => s.isOnBreak).length;

  return (
    <Box
      sx={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        background: 'linear-gradient(180deg, rgba(29,185,84,0.3) 0%, rgba(18,18,18,0.98) 30%)',
        color: 'white',
        overflow: 'hidden',
        borderRadius: 2,
      }}
    >
      {/* Header */}
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          px: 1.5,
          py: 1,
          borderBottom: '1px solid rgba(255,255,255,0.1)',
        }}
      >
        <Typography variant="caption" sx={{ opacity: 0.7, fontSize: '10px' }}>
          zeiterfassung
        </Typography>
        <Box sx={{ display: 'flex', gap: 0.5 }}>
          <IconButton size="small" onClick={onRefresh} sx={{ color: 'white', p: 0.5 }}>
            <RefreshIcon sx={{ fontSize: 16, animation: loading ? 'spin 1s linear infinite' : 'none' }} />
          </IconButton>
          <IconButton size="small" onClick={onToggleSound} sx={{ color: 'white', p: 0.5 }}>
            {soundEnabled ? <VolumeUpIcon sx={{ fontSize: 16 }} /> : <VolumeOffIcon sx={{ fontSize: 16 }} />}
          </IconButton>
          <IconButton size="small" onClick={onExpand} sx={{ color: 'white', p: 0.5 }}>
            <OpenInFullIcon sx={{ fontSize: 16 }} />
          </IconButton>
          <IconButton size="small" onClick={onClose} sx={{ color: 'white', p: 0.5 }}>
            <CloseIcon sx={{ fontSize: 16 }} />
          </IconButton>
        </Box>
      </Box>

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

      {/* Stats Summary */}
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'center',
          gap: 3,
          py: 2,
          borderBottom: '1px solid rgba(255,255,255,0.1)',
        }}
      >
        <Box sx={{ textAlign: 'center' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 0.5 }}>
            <WorkIcon sx={{ fontSize: 20, color: '#1db954' }} />
            <Typography variant="h5" fontWeight="bold">
              {workingCount}
            </Typography>
          </Box>
          <Typography variant="caption" sx={{ opacity: 0.6, fontSize: '10px' }}>
            Arbeiten
          </Typography>
        </Box>
        <Box sx={{ textAlign: 'center' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 0.5 }}>
            <CoffeeIcon sx={{ fontSize: 20, color: '#f59e0b' }} />
            <Typography variant="h5" fontWeight="bold">
              {breakCount}
            </Typography>
          </Box>
          <Typography variant="caption" sx={{ opacity: 0.6, fontSize: '10px' }}>
            Pause
          </Typography>
        </Box>
      </Box>

      {/* Sessions List */}
      <Box sx={{ flex: 1, overflow: 'auto', px: 1, py: 1 }}>
        {sessions.length === 0 ? (
          <Box sx={{ textAlign: 'center', py: 4, opacity: 0.5 }}>
            <ScheduleIcon sx={{ fontSize: 32, mb: 1 }} />
            <Typography variant="body2">Keine aktiven Sitzungen</Typography>
          </Box>
        ) : (
          sessions.slice(0, 8).map((session) => (
            <Box
              key={session.sessionId}
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 1,
                py: 0.75,
                px: 1,
                borderRadius: 1,
                mb: 0.5,
                bgcolor: session.isOnBreak ? 'rgba(245,158,11,0.15)' : 'rgba(29,185,84,0.15)',
                '&:hover': {
                  bgcolor: session.isOnBreak ? 'rgba(245,158,11,0.25)' : 'rgba(29,185,84,0.25)',
                },
              }}
            >
              <Avatar
                src={session.userPhoto || undefined}
                sx={{
                  width: 28,
                  height: 28,
                  fontSize: '0.7rem',
                  bgcolor: session.isOnBreak ? '#f59e0b' : '#1db954',
                }}
              >
                {session.userInitials}
              </Avatar>
              <Box sx={{ flex: 1, minWidth: 0 }}>
                <Typography variant="body2" fontWeight="medium" noWrap sx={{ fontSize: '12px' }}>
                  {session.userName}
                </Typography>
                {session.shiftName && (
                  <Typography variant="caption" sx={{ opacity: 0.6, fontSize: '10px' }} noWrap>
                    {session.shiftName}
                  </Typography>
                )}
              </Box>
              <Box sx={{ textAlign: 'right' }}>
                {session.isOnBreak ? (
                  <Chip
                    size="small"
                    label="Pause"
                    sx={{
                      height: 18,
                      fontSize: '9px',
                      bgcolor: 'rgba(245,158,11,0.3)',
                      color: '#f59e0b',
                    }}
                  />
                ) : (
                  <Typography variant="caption" sx={{ opacity: 0.6, fontSize: '10px' }}>
                    {format(new Date(session.clockInTime), 'HH:mm', { locale: de })}
                  </Typography>
                )}
              </Box>
            </Box>
          ))
        )}
        {sessions.length > 8 && (
          <Typography variant="caption" sx={{ opacity: 0.5, textAlign: 'center', display: 'block', mt: 1 }}>
            +{sessions.length - 8} weitere
          </Typography>
        )}
      </Box>

      {/* Footer */}
      <Box
        sx={{
          px: 1.5,
          py: 1,
          borderTop: '1px solid rgba(255,255,255,0.1)',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <Typography variant="caption" sx={{ opacity: 0.5, fontSize: '9px' }}>
          {lastUpdate ? `Aktualisiert ${format(lastUpdate, 'HH:mm:ss')}` : 'Lädt...'}
        </Typography>
        <Typography variant="caption" sx={{ opacity: 0.5, fontSize: '9px' }}>
          Live-Übersicht
        </Typography>
      </Box>

      <style>{`
        @keyframes spin {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
      `}</style>
    </Box>
  );
};

// Storage key for sound settings
const SOUND_STORAGE_KEY = 'zeiterfassung_document_pip_sound';
const DASHBOARD_LAYOUT_KEY = 'zeiterfassung_dashboard_layout';

// Check if Global PIP is enabled in dashboard settings
const isGlobalPipEnabled = (): boolean => {
  try {
    const saved = localStorage.getItem(DASHBOARD_LAYOUT_KEY);
    if (saved) {
      const parsed = JSON.parse(saved);
      if (parsed?.widgetSettings?.pip?.globalPipEnabled !== undefined) {
        return parsed.widgetSettings.pip.globalPipEnabled;
      }
    }
  } catch {}
  // Default to false (disabled by default)
  return false;
};

// Document PiP Manager
export class DocumentPipManager {
  private pipWindow: Window | null = null;
  private root: Root | null = null;
  private emotionCache: EmotionCache | null = null;
  private refreshInterval: NodeJS.Timeout | null = null;
  private sessions: ActiveSession[] = [];
  private prevSessions: ActiveSession[] = [];
  private loading: boolean = false;
  private lastUpdate: Date | null = null;
  private soundEnabled: boolean = true;
  private audioRef: HTMLAudioElement | null = null;
  private isFirstFetch: boolean = true;

  constructor() {
    // Load sound preference from localStorage
    try {
      const saved = localStorage.getItem(SOUND_STORAGE_KEY);
      if (saved !== null) {
        this.soundEnabled = saved === 'true';
      }
    } catch {}
  }

  private playSound(): void {
    if (!this.soundEnabled) return;
    try {
      if (!this.audioRef) {
        this.audioRef = new Audio('/sounds/notification.mp3');
        this.audioRef.volume = 0.5;
      }
      this.audioRef.currentTime = 0;
      this.audioRef.play().catch(() => {});
    } catch {}
  }

  toggleSound(): void {
    this.soundEnabled = !this.soundEnabled;
    try {
      localStorage.setItem(SOUND_STORAGE_KEY, String(this.soundEnabled));
    } catch {}
    this.render();
  }

  isSoundEnabled(): boolean {
    return this.soundEnabled;
  }

  /**
   * Open the Document PiP window.
   * @param options.bypassGlobalCheck - If true, skip the globalPipEnabled check (used when opening from Dashboard PIP)
   */
  async open(options?: { bypassGlobalCheck?: boolean }): Promise<boolean> {
    // Check if Global PIP is enabled in dashboard settings (unless bypassed)
    if (!options?.bypassGlobalCheck && !isGlobalPipEnabled()) {
      return false;
    }

    if (!isDocumentPipSupported()) {
      return false;
    }

    // Reset state for new session
    this.isFirstFetch = true;
    this.prevSessions = [];

    try {
      // Request Document PiP window
      this.pipWindow = await (window as any).documentPictureInPicture.requestWindow({
        width: 320,
        height: 480,
      });

      // Copy all stylesheets from parent window to PiP window
      // This is needed for MUI CSS-in-JS styles to work
      const parentStyleSheets = [...document.styleSheets];
      for (const sheet of parentStyleSheets) {
        try {
          if (sheet.cssRules) {
            const style = this.pipWindow.document.createElement('style');
            const cssText = [...sheet.cssRules].map(rule => rule.cssText).join('\n');
            style.textContent = cssText;
            this.pipWindow.document.head.appendChild(style);
          }
        } catch (e) {
          // Cross-origin stylesheets can't be accessed, skip them
          if (sheet.href) {
            const link = this.pipWindow.document.createElement('link');
            link.rel = 'stylesheet';
            link.href = sheet.href;
            this.pipWindow.document.head.appendChild(link);
          }
        }
      }

      // Add base styles for PiP window
      const baseStyle = this.pipWindow.document.createElement('style');
      baseStyle.textContent = `
        * {
          margin: 0;
          padding: 0;
          box-sizing: border-box;
        }
        html, body {
          height: 100%;
          overflow: hidden;
          background: linear-gradient(180deg, rgba(29,185,84,0.3) 0%, rgba(18,18,18,0.98) 30%);
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        }
        #pip-root {
          height: 100%;
        }
        ::-webkit-scrollbar {
          width: 4px;
        }
        ::-webkit-scrollbar-track {
          background: transparent;
        }
        ::-webkit-scrollbar-thumb {
          background: rgba(255,255,255,0.2);
          border-radius: 2px;
        }
      `;
      this.pipWindow.document.head.appendChild(baseStyle);

      // Create root element
      const container = this.pipWindow.document.createElement('div');
      container.id = 'pip-root';
      this.pipWindow.document.body.appendChild(container);

      // Create Emotion cache that inserts styles into PiP window
      this.emotionCache = createCache({
        key: 'pip-emotion',
        container: this.pipWindow.document.head,
        prepend: true,
      });

      // Create React root
      this.root = createRoot(container);

      // Start fetching data
      await this.fetchData();
      this.startRefreshInterval();

      // Render
      this.render();

      // Listen for PiP window close
      this.pipWindow.addEventListener('pagehide', () => {
        this.close();
      });

      return true;
    } catch {
      return false;
    }
  }

  private async fetchData(): Promise<void> {
    try {
      this.loading = true;
      this.render();

      const response = await axios.get('/zeiterfassung/work-sessions/active');
      const newSessions: ActiveSession[] = response.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,
      }));

      // Detect changes and play sound (skip on initial load)
      if (!this.isFirstFetch && this.prevSessions.length > 0) {
        const prevSessionsMap = new Map(this.prevSessions.map((s) => [s.sessionId, s]));
        let shouldPlaySound = false;

        // Calculate working counts
        const prevWorkingCount = this.prevSessions.filter(s => !s.isOnBreak).length;
        const newWorkingCount = newSessions.filter(s => !s.isOnBreak).length;

        // Check if working count changed (covers clock-in, clock-out, break changes)
        if (prevWorkingCount !== newWorkingCount) {
          shouldPlaySound = true;
        } else {
          // Also check for session count change (someone clocked in/out without affecting working count)
          if (this.prevSessions.length !== newSessions.length) {
            shouldPlaySound = true;
          } else {
            // Check for individual status changes
            for (const session of newSessions) {
              const prevSession = prevSessionsMap.get(session.sessionId);
              if (!prevSession) {
                // New session - someone clocked in
                shouldPlaySound = true;
                break;
              } else if (prevSession.isOnBreak !== session.isOnBreak) {
                // Break status changed
                shouldPlaySound = true;
                break;
              }
            }
          }
        }

        if (shouldPlaySound) {
          this.playSound();
        }
      }

      this.isFirstFetch = false;
      this.prevSessions = newSessions;
      this.sessions = newSessions;
      this.lastUpdate = new Date();
    } catch {
      // Silently handle fetch errors
    } finally {
      this.loading = false;
      this.render();
    }
  }

  private startRefreshInterval(): void {
    this.refreshInterval = setInterval(() => {
      this.fetchData();
    }, 15000);
  }

  private render(): void {
    if (!this.root || !this.emotionCache) return;

    this.root.render(
      <CacheProvider value={this.emotionCache}>
        <ThemeProvider theme={pipTheme}>
          <PipContent
            sessions={this.sessions}
            loading={this.loading}
            onRefresh={() => this.fetchData()}
            onClose={() => this.close()}
            onExpand={() => {
              window.location.href = '/zeiterfassung?tab=dashboard';
              this.close();
            }}
            onToggleSound={() => this.toggleSound()}
            soundEnabled={this.soundEnabled}
            lastUpdate={this.lastUpdate}
          />
        </ThemeProvider>
      </CacheProvider>
    );
  }

  close(): void {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
      this.refreshInterval = null;
    }

    if (this.root) {
      this.root.unmount();
      this.root = null;
    }

    this.emotionCache = null;

    if (this.pipWindow && !this.pipWindow.closed) {
      this.pipWindow.close();
    }
    this.pipWindow = null;
  }

  isOpen(): boolean {
    return this.pipWindow !== null && !this.pipWindow.closed;
  }
}

// Singleton instance
let pipManagerInstance: DocumentPipManager | null = null;

export const getDocumentPipManager = (): DocumentPipManager => {
  if (!pipManagerInstance) {
    pipManagerInstance = new DocumentPipManager();
  }
  return pipManagerInstance;
};

export default DocumentPipManager;
