import { useState, useEffect } from 'react';
import { Box, Tabs, Tab, Typography } from '@mui/material';
import { Navigate, useNavigate, useSearchParams } from 'react-router-dom';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import ServiceManagerTab from '../components/admin/ServiceManagerTab';
import SystemHealthTab from '../components/admin/SystemHealthTab';
import UserOverviewTab from '../components/admin/UserOverviewTab';
import NotificationBroadcastTab from '../components/admin/NotificationBroadcastTab';
import BannerManagementTab from '../components/admin/BannerManagementTab';
import ServiceModeTab from '../components/admin/ServiceModeTab';
import PermissionMatrixTab from '../components/admin/PermissionMatrixTab';
import DataManagementTab from '../components/admin/DataManagementTab';
import FdiskSyncTab from '../components/admin/FdiskSyncTab';
import { usePermissionContext } from '../contexts/PermissionContext';

interface TabPanelProps {
  children: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel({ children, value, index }: TabPanelProps) {
  if (value !== index) return null;
  return <Box sx={{ pt: 3 }}>{children}</Box>;
}

function SubTabs({ labels, children }: { labels: string[]; children: React.ReactNode[] }) {
  const [subTab, setSubTab] = useState(0);
  return (
    <Box>
      <Tabs value={subTab} onChange={(_e, v) => setSubTab(v)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}>
        {labels.map((l) => <Tab key={l} label={l} />)}
      </Tabs>
      {children.map((child, i) => subTab === i ? <Box key={i}>{child}</Box> : null)}
    </Box>
  );
}

const ADMIN_TAB_COUNT = 4;

function AdminDashboard() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [tab, setTab] = useState(() => {
    const t = Number(searchParams.get('tab'));
    return t >= 0 && t < ADMIN_TAB_COUNT ? t : 0;
  });

  useEffect(() => {
    const t = Number(searchParams.get('tab'));
    if (t >= 0 && t < ADMIN_TAB_COUNT) setTab(t);
  }, [searchParams]);
  const { hasPermission } = usePermissionContext();

  if (!hasPermission('admin:view')) {
    return <Navigate to="/dashboard" replace />;
  }

  return (
    <DashboardLayout>
      <Typography variant="h4" sx={{ mb: 3 }}>Administration</Typography>

      <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
        <Tabs value={tab} onChange={(_e, v) => { setTab(v); navigate(`/admin?tab=${v}`, { replace: true }); }} variant="scrollable" scrollButtons="auto">
          <Tab label="Information" />
          <Tab label="System Mitteilungen" />
          <Tab label="Tool Zugriff" />
          <Tab label="Daten" />
        </Tabs>
      </Box>

      <TabPanel value={tab} index={0}>
        <SubTabs labels={['Services', 'System', 'Benutzer']}>
          {[<ServiceManagerTab />, <SystemHealthTab />, <UserOverviewTab />]}
        </SubTabs>
      </TabPanel>
      <TabPanel value={tab} index={1}>
        <SubTabs labels={['Broadcast', 'Banner']}>
          {[<NotificationBroadcastTab />, <BannerManagementTab />]}
        </SubTabs>
      </TabPanel>
      <TabPanel value={tab} index={2}>
        <SubTabs labels={['Wartung', 'Berechtigungen']}>
          {[<ServiceModeTab />, <PermissionMatrixTab />]}
        </SubTabs>
      </TabPanel>
      <TabPanel value={tab} index={3}>
        <SubTabs labels={['Datenverwaltung', 'FDISK Sync']}>
          {[<DataManagementTab />, <FdiskSyncTab />]}
        </SubTabs>
      </TabPanel>
    </DashboardLayout>
  );
}

export default AdminDashboard;
