import React, { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Link, Outlet, useNavigate, Navigate } from 'react-router-dom';
import { SidebarComponent } from '@syncfusion/ej2-react-navigations';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
import { DropDownButtonComponent } from '@syncfusion/ej2-react-splitbuttons';
import type { MenuEventArgs } from '@syncfusion/ej2-splitbuttons';
import { TooltipComponent, DialogComponent } from '@syncfusion/ej2-react-popups';
import { TextBoxComponent } from '@syncfusion/ej2-react-inputs';
import logo from './assets/logo.png';
import './App.css';

// Lucide Icons importieren
import {
  LayoutDashboard,
  Calendar,
  Boxes,
  Image,
  User,
  Settings,
  Monitor,
  MonitorDotIcon,
  Activity,
  LogOut,
  Wrench,
  Info,
} from 'lucide-react';
import { ToastProvider } from './components/ToastProvider';

const sidebarItems = [
  { name: 'Dashboard', path: '/', icon: LayoutDashboard, minRole: 'user' },
  { name: 'Termine', path: '/termine', icon: Calendar, minRole: 'user' },
  { name: 'Ressourcen', path: '/ressourcen', icon: Boxes, minRole: 'editor' },
  { name: 'Raumgruppen', path: '/infoscr_groups', icon: MonitorDotIcon, minRole: 'admin' },
  { name: 'Infoscreen-Clients', path: '/clients', icon: Monitor, minRole: 'admin' },
  { name: 'Monitor-Dashboard', path: '/monitoring', icon: Activity, minRole: 'superadmin' },
  { name: 'Erweiterungsmodus', path: '/setup', icon: Wrench, minRole: 'admin' },
  { name: 'Medien', path: '/medien', icon: Image, minRole: 'editor' },
  { name: 'Benutzer', path: '/benutzer', icon: User, minRole: 'admin' },
  { name: 'Einstellungen', path: '/einstellungen', icon: Settings, minRole: 'admin' },
  { name: 'Programminfo', path: '/programminfo', icon: Info, minRole: 'user' },
];

// Dummy Components (können in eigene Dateien ausgelagert werden)
import Dashboard from './dashboard';
import Appointments from './appointments';
import Ressourcen from './ressourcen';
import Infoscreens from './clients';
import Infoscreen_groups from './infoscreen_groups';
import Media from './media';
import Benutzer from './users';
import Einstellungen from './settings';
import SetupMode from './SetupMode';
import Programminfo from './programminfo';
import MonitoringDashboard from './monitoring';
import Logout from './logout';
import Login from './login';
import { useAuth } from './useAuth';
import { changePassword } from './apiAuth';
import { useToast } from './components/ToastProvider';

// ENV aus .env holen (Platzhalter, im echten Projekt über process.env oder API)
// const ENV = import.meta.env.VITE_ENV || 'development';

const Layout: React.FC = () => {
  const [version, setVersion] = useState('');
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [organizationName, setOrganizationName] = useState('');
  let sidebarRef: SidebarComponent | null;
  const { user } = useAuth();
  const toast = useToast();
  const navigate = useNavigate();

  // Change password dialog state
  const [showPwdDialog, setShowPwdDialog] = useState(false);
  const [pwdCurrent, setPwdCurrent] = useState('');
  const [pwdNew, setPwdNew] = useState('');
  const [pwdConfirm, setPwdConfirm] = useState('');
  const [pwdBusy, setPwdBusy] = useState(false);

  React.useEffect(() => {
    fetch('/program-info.json')
      .then(res => res.json())
      .then(data => setVersion(data.version))
      .catch(err => console.error('Failed to load version info:', err));
  }, []);

  // Load organization name
  React.useEffect(() => {
    const loadOrgName = async () => {
      try {
        const { getOrganizationName } = await import('./apiSystemSettings');
        const data = await getOrganizationName();
        setOrganizationName(data.name || '');
      } catch (err) {
        console.error('Failed to load organization name:', err);
      }
    };
    loadOrgName();
    
    // Listen for organization name updates from Settings page
    const handleUpdate = () => loadOrgName();
    window.addEventListener('organizationNameUpdated', handleUpdate);
    return () => window.removeEventListener('organizationNameUpdated', handleUpdate);
  }, []);

  const toggleSidebar = () => {
    if (sidebarRef) {
      sidebarRef.toggle();
    }
  };

  const onSidebarChange = () => {
    // Syncfusion unterscheidet zwischen isOpen (true/false) und dem Dock-Modus
    // Im Dock-Modus ist isOpen=true, aber die Sidebar ist kollabiert
    const sidebar = sidebarRef?.element;
    if (sidebar) {
      const currentWidth = sidebar.style.width;
      const newCollapsedState = currentWidth === '60px' || currentWidth.includes('60');

      setIsCollapsed(newCollapsedState);
    }
  };

  const submitPasswordChange = async () => {
    if (!pwdCurrent || !pwdNew || !pwdConfirm) {
      toast.show({ content: 'Bitte alle Felder ausfüllen', cssClass: 'e-toast-warning' });
      return;
    }
    if (pwdNew.length < 6) {
      toast.show({ content: 'Neues Passwort muss mindestens 6 Zeichen haben', cssClass: 'e-toast-warning' });
      return;
    }
    if (pwdNew !== pwdConfirm) {
      toast.show({ content: 'Passwörter stimmen nicht überein', cssClass: 'e-toast-warning' });
      return;
    }

    setPwdBusy(true);
    try {
      await changePassword(pwdCurrent, pwdNew);
      toast.show({ content: 'Passwort erfolgreich geändert', cssClass: 'e-toast-success' });
      setShowPwdDialog(false);
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Ändern des Passworts';
      toast.show({ content: msg, cssClass: 'e-toast-danger' });
    } finally {
      setPwdBusy(false);
    }
  };

  const sidebarTemplate = () => (
    <div
      className={`sidebar-theme ${isCollapsed ? 'collapsed' : 'expanded'}`}
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100vh',
        minHeight: '100vh',
        overflow: 'hidden',
      }}
    >
      <div
        style={{
          borderColor: 'var(--sidebar-border)',
          height: '68px',
          flexShrink: 0,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          borderBottom: '1px solid var(--sidebar-border)',
          margin: 0,
          padding: 0,
        }}
      >
        <img
          src={logo}
          alt="Logo"
          style={{
            height: '64px',
            maxHeight: '60px',
            display: 'block',
            margin: '0 auto',
          }}
        />
      </div>
      <nav
        style={{
          flex: '1 1 auto',
          display: 'flex',
          flexDirection: 'column',
          marginTop: '1rem',
          overflowY: 'auto',
          minHeight: 0, // Wichtig für Flex-Shrinking
        }}
      >
        {sidebarItems
          .filter(item => {
            // Only show items the current user is allowed to see
            if (!user) return false;
            const roleHierarchy = ['user', 'editor', 'admin', 'superadmin'];
            const userRoleIndex = roleHierarchy.indexOf(user.role);
            const itemRoleIndex = roleHierarchy.indexOf(item.minRole || 'user');
            return userRoleIndex >= itemRoleIndex;
          })
          .map(item => {
          const Icon = item.icon;
          const linkContent = (
            <Link
              key={item.path}
              to={item.path}
              className="sidebar-link no-underline w-full"
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'flex-start',
                gap: '8px',
                padding: '12px 24px',
                transition: 'background 0.2s, color 0.2s, justify-content 0.3s',
                textDecoration: 'none',
                color: 'var(--sidebar-fg)',
                backgroundColor: 'var(--sidebar-bg)',
              }}
            >
              <Icon size={22} style={{ flexShrink: 0, marginRight: 0 }} />
              <span className="sidebar-text" style={{ marginLeft: 0, transition: 'opacity 0.3s' }}>
                {item.name}
              </span>
            </Link>
          );

          // Syncfusion Tooltip nur im collapsed state
          return isCollapsed ? (
            <TooltipComponent
              key={item.path}
              content={item.name}
              position="RightCenter"
              opensOn="Hover"
              showTipPointer={true}
              animation={{
                open: { effect: 'FadeIn', duration: 200 },
                close: { effect: 'FadeOut', duration: 200 },
              }}
            >
              {linkContent}
            </TooltipComponent>
          ) : (
            linkContent
          );
        })}
      </nav>
      <div
        style={{
          flexShrink: 0,
          marginTop: 'auto',
          display: 'flex',
          flexDirection: 'column',
          minHeight: 'auto',
        }}
      >
        {(() => {
          const logoutContent = (
            <Link
              to="/logout"
              className="sidebar-logout no-underline w-full"
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'flex-start',
                gap: '8px',
                padding: '12px 24px',
                transition: 'background 0.2s, color 0.2s, justify-content 0.3s',
                textDecoration: 'none',
                color: 'var(--sidebar-fg)',
                backgroundColor: 'var(--sidebar-bg)',
                border: 'none',
                cursor: 'pointer',
                fontSize: '1.15rem',
              }}
            >
              <LogOut size={22} style={{ flexShrink: 0, marginRight: 0 }} />
              <span className="sidebar-text" style={{ marginLeft: 0, transition: 'opacity 0.3s' }}>
                Abmelden
              </span>
            </Link>
          );

          // Syncfusion Tooltip nur im collapsed state
          return isCollapsed ? (
            <TooltipComponent
              content="Abmelden"
              position="RightCenter"
              opensOn="Hover"
              showTipPointer={true}
              animation={{
                open: { effect: 'FadeIn', duration: 200 },
                close: { effect: 'FadeOut', duration: 200 },
              }}
            >
              {logoutContent}
            </TooltipComponent>
          ) : (
            logoutContent
          );
        })()}
        {version && (
          <div
            className="version-info px-6 py-2 text-xs text-center opacity-70 border-t"
            style={{ borderColor: 'var(--sidebar-border)' }}
          >
            Version {version}
          </div>
        )}
      </div>
    </div>
  );

  return (
    <div className="layout-container">
      <SidebarComponent
        id="sidebar"
        ref={(sidebar: SidebarComponent | null) => {
          sidebarRef = sidebar;
        }}
        width="256px"
        target=".layout-container"
        isOpen={true}
        closeOnDocumentClick={false}
        enableGestures={false}
        type="Auto"
        enableDock={true}
        dockSize="60px"
        change={onSidebarChange}
      >
        {sidebarTemplate()}
      </SidebarComponent>

      <div className="content-area">
        <header
          className="content-header flex items-center shadow"
          style={{
            backgroundColor: '#e5d8c7',
            color: '#78591c',
            height: '68px', // Exakt gleiche Höhe wie Sidebar-Header
            fontSize: '1.15rem',
            fontFamily:
              'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif',
            margin: 0,
            padding: '0 2rem 0 0', // Nur rechts Padding, links kein Padding
            boxSizing: 'border-box',
            display: 'flex',
            alignItems: 'center',
          }}
        >
          <ButtonComponent
            cssClass="e-inherit"
            iconCss="e-icons e-menu"
            onClick={toggleSidebar}
            isToggle={true}
            style={{
              margin: '0 1rem 0 0', // Nur rechts Margin für Abstand zum Logo
              padding: '8px 12px',
              minWidth: '44px',
              height: '44px',
              flexShrink: 0,
            }}
          />
          <img src={logo} alt="Logo" className="h-16 mr-4" style={{ maxHeight: '60px' }} />
          <span className="text-2xl font-bold mr-8" style={{ color: '#78591c' }}>
            Infoscreen-Management
          </span>
          <div style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 16 }}>
            {organizationName && (
              <span className="text-lg font-medium" style={{ color: '#78591c' }}>
                {organizationName}
              </span>
            )}
            {user && (
              <DropDownButtonComponent
                items={[
                  { text: 'Passwort ändern', id: 'change-password', iconCss: 'e-icons e-lock' },
                  { separator: true },
                  { text: 'Abmelden', id: 'logout', iconCss: 'e-icons e-logout' },
                ]}
                select={(args: MenuEventArgs) => {
                  if (args.item.id === 'change-password') {
                    setPwdCurrent('');
                    setPwdNew('');
                    setPwdConfirm('');
                    setShowPwdDialog(true);
                  } else if (args.item.id === 'logout') {
                    navigate('/logout');
                  }
                }}
                cssClass="e-inherit"
              >
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <User size={18} />
                  <span style={{ fontWeight: 600 }}>{user.username}</span>
                  <span
                    style={{
                      fontSize: '0.8rem',
                      textTransform: 'uppercase',
                      opacity: 0.85,
                      border: '1px solid rgba(120, 89, 28, 0.25)',
                      borderRadius: 6,
                      padding: '2px 6px',
                      backgroundColor: 'rgba(255, 255, 255, 0.6)',
                    }}
                  >
                    {user.role}
                  </span>
                </div>
              </DropDownButtonComponent>
            )}
          </div>
        </header>
        <DialogComponent
          isModal={true}
          visible={showPwdDialog}
          width="480px"
          header="Passwort ändern"
          showCloseIcon={true}
          close={() => setShowPwdDialog(false)}
          footerTemplate={() => (
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
              <ButtonComponent cssClass="e-flat" onClick={() => setShowPwdDialog(false)} disabled={pwdBusy}>
                Abbrechen
              </ButtonComponent>
              <ButtonComponent cssClass="e-primary" onClick={submitPasswordChange} disabled={pwdBusy}>
                {pwdBusy ? 'Speichere...' : 'Speichern'}
              </ButtonComponent>
            </div>
          )}
        >
          <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <label style={{ display: 'block', marginBottom: 6, fontWeight: 500 }}>Aktuelles Passwort *</label>
              <TextBoxComponent
                type="password"
                placeholder="Aktuelles Passwort"
                value={pwdCurrent}
                input={(e: { value?: string }) => setPwdCurrent(e.value ?? '')}
                disabled={pwdBusy}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: 6, fontWeight: 500 }}>Neues Passwort *</label>
              <TextBoxComponent
                type="password"
                placeholder="Mindestens 6 Zeichen"
                value={pwdNew}
                input={(e: { value?: string }) => setPwdNew(e.value ?? '')}
                disabled={pwdBusy}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: 6, fontWeight: 500 }}>Neues Passwort bestätigen *</label>
              <TextBoxComponent
                type="password"
                placeholder="Wiederholen"
                value={pwdConfirm}
                input={(e: { value?: string }) => setPwdConfirm(e.value ?? '')}
                disabled={pwdBusy}
              />
            </div>
          </div>
        </DialogComponent>
        <main className="page-content">
          <Outlet />
        </main>
      </div>
    </div>
  );
};

const App: React.FC = () => {
  // Automatische Navigation zu /clients bei leerer Beschreibung entfernt

  const RequireAuth: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const { isAuthenticated, loading } = useAuth();
    if (loading) return <div style={{ padding: 24 }}>Lade ...</div>;
    if (!isAuthenticated) return <Login />;
    return <>{children}</>;
  };

  const RequireSuperadmin: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const { isAuthenticated, loading, user } = useAuth();
    if (loading) return <div style={{ padding: 24 }}>Lade ...</div>;
    if (!isAuthenticated) return <Login />;
    if (user?.role !== 'superadmin') return <Navigate to="/" replace />;
    return <>{children}</>;
  };

  return (
    <ToastProvider>
      <Routes>
        <Route
          path="/"
          element={
            <RequireAuth>
              <Layout />
            </RequireAuth>
          }
        >
          <Route index element={<Dashboard />} />
          <Route path="termine" element={<Appointments />} />
          <Route path="ressourcen" element={<Ressourcen />} />
          <Route path="infoscr_groups" element={<Infoscreen_groups />} />
          <Route path="medien" element={<Media />} />
          <Route path="benutzer" element={<Benutzer />} />
          <Route path="einstellungen" element={<Einstellungen />} />
          <Route path="clients" element={<Infoscreens />} />
          <Route
            path="monitoring"
            element={
              <RequireSuperadmin>
                <MonitoringDashboard />
              </RequireSuperadmin>
            }
          />
          <Route path="setup" element={<SetupMode />} />
          <Route path="programminfo" element={<Programminfo />} />
        </Route>
        <Route path="/logout" element={<Logout />} />
        <Route path="/login" element={<Login />} />
      </Routes>
    </ToastProvider>
  );
};

const AppWrapper: React.FC = () => (
  <Router>
    <App />
  </Router>
);

export default AppWrapper;
