import React, { useState, useEffect } from 'react';
import { Box, Tab, Tabs } from '@mui/material';
import { useSearchParams } from 'react-router-dom';
import { PageHeader } from './PageHeader';
import { TabPanel } from './TabPanel';

export interface TabDef {
  label: React.ReactNode;
  content: React.ReactNode;
  icon?: React.ReactElement;
  disabled?: boolean;
}

export interface DetailLayoutProps {
  title: string;
  actions?: React.ReactNode;
  tabs: TabDef[];
  backTo?: string;
  isLoading?: boolean;
  skeleton?: React.ReactNode;
}

/** Detail page layout with PageHeader and tab navigation synced to URL. */
export const DetailLayout: React.FC<DetailLayoutProps> = ({
  title,
  actions,
  tabs,
  backTo,
  isLoading = false,
  skeleton,
}) => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [tab, setTab] = useState(() => {
    const t = parseInt(searchParams.get('tab') ?? '0', 10);
    return isNaN(t) || t < 0 || t >= tabs.length ? 0 : t;
  });

  useEffect(() => {
    const newParams = new URLSearchParams(searchParams);
    if (tab === 0) {
      newParams.delete('tab');
    } else {
      newParams.set('tab', String(tab));
    }
    setSearchParams(newParams, { replace: true });
  }, [tab]);

  return (
    <Box>
      <PageHeader title={title} actions={actions} backTo={backTo} />
      {isLoading ? (
        skeleton
      ) : (
        <>
          <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
            <Tabs value={tab} onChange={(_, v) => setTab(v)} variant="scrollable" scrollButtons="auto">
              {tabs.map((t, i) => (
                <Tab key={i} label={t.label} icon={t.icon} disabled={t.disabled} />
              ))}
            </Tabs>
          </Box>
          {tabs.map((t, i) => (
            <TabPanel key={i} value={tab} index={i}>
              {t.content}
            </TabPanel>
          ))}
        </>
      )}
    </Box>
  );
};
