import React from 'react';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import Box from '@mui/material/Box';
import Drawer from '@mui/material/Drawer';
import List from '@mui/material/List';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Collapse from '@mui/material/Collapse';
import useMediaQuery from '@mui/material/useMediaQuery';
import MenuIcon from '@mui/icons-material/Menu';
import CloseIcon from '@mui/icons-material/Close';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import type { SxProps, Theme } from '@mui/material/styles';
import { IconButton } from '../../atoms/IconButton';
import { Link } from '../../atoms/Link';
import { Button } from '../../atoms/Button';
import { Typography } from '../../atoms/Typography';
import { Divider } from '../../atoms/Divider';

// ─── Types ───────────────────────────────────────────────────────────────────

/** A navigation link item. May have children to render as a dropdown. */
export interface NavItem {
  /** Display label */
  label: string;
  /** URL to navigate to (ignored when `children` is provided) */
  href?: string;
  /** Click handler (alternative to href for SPA navigation) */
  onClick?: () => void;
  /** Sub-items rendered as a dropdown (desktop) or collapsible (mobile) */
  children?: NavItem[];
}

/** Props for the FA Navigation organism */
export interface NavigationProps {
  /** Site logo — rendered on the left (desktop) or centre (mobile) */
  logo: React.ReactNode;
  /** Click handler for the logo (navigate to home) */
  onLogoClick?: () => void;
  /** Navigation links displayed in the header */
  items?: NavItem[];
  /** Optional CTA button (e.g. "Start planning") on desktop */
  ctaLabel?: string;
  /** Click handler for the CTA button */
  onCtaClick?: () => void;
  /** MUI sx prop for the root AppBar */
  sx?: SxProps<Theme>;
}

// ─── Desktop dropdown link ───────────────────────────────────────────────────

interface DesktopDropdownProps {
  item: NavItem;
}

const DesktopDropdown: React.FC<DesktopDropdownProps> = ({ item }) => {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);

  const handleOpen = (event: React.MouseEvent<HTMLElement>) => setAnchorEl(event.currentTarget);
  const handleClose = () => setAnchorEl(null);

  return (
    <>
      <Box
        component="button"
        type="button"
        aria-haspopup="menu"
        aria-expanded={open}
        onClick={handleOpen}
        sx={{
          background: 'none',
          border: 'none',
          padding: 0,
          cursor: 'pointer',
          color: 'var(--fa-color-brand-900)',
          fontFamily: 'inherit',
          fontWeight: 600,
          fontSize: '1rem',
          '&:hover': {
            color: 'primary.main',
          },
        }}
      >
        {item.label}
      </Box>
      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
        transformOrigin={{ vertical: 'top', horizontal: 'left' }}
        slotProps={{
          paper: {
            sx: {
              mt: 1,
              minWidth: 200,
              borderRadius: 'var(--fa-border-radius-md, 8px)',
              boxShadow: '0 8px 24px rgba(0,0,0,0.08)',
            },
          },
        }}
      >
        {item.children?.map((child) => (
          <MenuItem
            key={child.label}
            component="a"
            href={child.href}
            onClick={(e: React.MouseEvent) => {
              if (child.onClick) {
                e.preventDefault();
                child.onClick();
              }
              handleClose();
            }}
            sx={{
              color: 'var(--fa-color-brand-900)',
              fontWeight: 500,
              py: 1.25,
              '&:hover': {
                bgcolor: 'var(--fa-color-brand-100)',
                color: 'primary.main',
              },
            }}
          >
            {child.label}
          </MenuItem>
        ))}
      </Menu>
    </>
  );
};

// ─── Mobile collapsible item ─────────────────────────────────────────────────

interface MobileCollapsibleProps {
  item: NavItem;
  onItemClick: () => void;
}

const MobileCollapsible: React.FC<MobileCollapsibleProps> = ({ item, onItemClick }) => {
  const [open, setOpen] = React.useState(false);

  return (
    <>
      <ListItemButton
        onClick={() => setOpen((prev) => !prev)}
        aria-expanded={open}
        sx={{
          py: 1.5,
          px: 3,
          minHeight: 44,
          '&:hover': {
            bgcolor: 'var(--fa-color-brand-100)',
          },
        }}
      >
        <ListItemText
          primary={item.label}
          primaryTypographyProps={{
            fontWeight: 500,
            fontSize: '1rem',
          }}
        />
        {open ? <ExpandLessIcon /> : <ExpandMoreIcon />}
      </ListItemButton>
      <Collapse in={open} timeout="auto" unmountOnExit>
        <List component="div" disablePadding>
          {item.children?.map((child) => (
            <ListItemButton
              key={child.label}
              component="a"
              href={child.href}
              onClick={(e: React.MouseEvent) => {
                if (child.onClick) {
                  e.preventDefault();
                  child.onClick();
                }
                onItemClick();
              }}
              sx={{
                py: 1.25,
                pl: 5,
                pr: 3,
                minHeight: 44,
                '&:hover': {
                  bgcolor: 'var(--fa-color-brand-100)',
                },
              }}
            >
              <ListItemText
                primary={child.label}
                primaryTypographyProps={{
                  fontWeight: 400,
                  fontSize: '0.9375rem',
                  color: 'text.secondary',
                }}
              />
            </ListItemButton>
          ))}
        </List>
      </Collapse>
    </>
  );
};

// ─── Component ───────────────────────────────────────────────────────────────

/**
 * Site header navigation for the FA design system.
 *
 * Responsive header with logo, navigation links, and optional CTA.
 * Desktop shows links inline; mobile collapses to hamburger + drawer.
 * Items with `children` render as a dropdown (desktop) or collapsible
 * section (mobile).
 *
 * Maps to Figma "Main Nav" (14:108) desktop and "Mobile Header"
 * (2391:41508) mobile patterns.
 *
 * Composes AppBar + Link + IconButton + Button + Divider + Drawer + Menu.
 */
export const Navigation = React.forwardRef<HTMLDivElement, NavigationProps>(
  ({ logo, onLogoClick, items = [], ctaLabel, onCtaClick, sx }, ref) => {
    const [drawerOpen, setDrawerOpen] = React.useState(false);
    const isMobile = useMediaQuery((theme: Theme) => theme.breakpoints.down('md'));

    const handleDrawerToggle = () => setDrawerOpen((prev) => !prev);
    const closeDrawer = () => setDrawerOpen(false);

    return (
      <>
        <AppBar
          ref={ref}
          position="sticky"
          elevation={0}
          sx={[
            {
              bgcolor: 'var(--fa-color-surface-subtle)',
              color: 'text.primary',
              borderBottom: '1px solid',
              borderColor: 'divider',
            },
            ...(Array.isArray(sx) ? sx : [sx]),
          ]}
        >
          <Toolbar
            sx={{
              minHeight: { xs: 56, md: 80 },
              px: { xs: 2, md: 4 },
              justifyContent: 'space-between',
            }}
          >
            {/* Left: hamburger (mobile) + logo */}
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
              {isMobile && (
                <IconButton
                  aria-label={drawerOpen ? 'Close menu' : 'Open menu'}
                  onClick={handleDrawerToggle}
                  size="medium"
                  edge="start"
                  sx={{ minWidth: 44, minHeight: 44 }}
                >
                  <MenuIcon />
                </IconButton>
              )}

              <Box
                component={onLogoClick ? 'a' : 'div'}
                href={onLogoClick ? '#' : undefined}
                onClick={
                  onLogoClick
                    ? (e: React.MouseEvent) => {
                        e.preventDefault();
                        onLogoClick();
                      }
                    : undefined
                }
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  cursor: onLogoClick ? 'pointer' : 'default',
                  textDecoration: 'none',
                  color: 'inherit',
                }}
                aria-label={onLogoClick ? 'Home' : undefined}
              >
                {logo}
              </Box>
            </Box>

            {/* Right: nav links (desktop) or trailing content (mobile) */}
            {!isMobile ? (
              <Box
                component="nav"
                aria-label="Main navigation"
                sx={{ display: 'flex', alignItems: 'center', gap: 3.5 }}
              >
                {items.map((item) =>
                  item.children && item.children.length > 0 ? (
                    <DesktopDropdown key={item.label} item={item} />
                  ) : (
                    <Link
                      key={item.label}
                      href={item.href}
                      onClick={item.onClick}
                      underline="hover"
                      sx={{
                        color: 'var(--fa-color-brand-900)',
                        fontWeight: 600,
                        fontSize: '1rem',
                        '&:hover': {
                          color: 'primary.main',
                        },
                      }}
                    >
                      {item.label}
                    </Link>
                  ),
                )}

                {ctaLabel && (
                  <Button variant="contained" size="medium" onClick={onCtaClick}>
                    {ctaLabel}
                  </Button>
                )}
              </Box>
            ) : null}
          </Toolbar>
        </AppBar>

        {/* Mobile drawer */}
        {isMobile && (
          <Drawer
            anchor="left"
            open={drawerOpen}
            onClose={handleDrawerToggle}
            PaperProps={{
              sx: {
                width: 300,
                bgcolor: 'background.default',
              },
            }}
          >
            {/* Drawer header */}
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                px: 2,
                py: 1.5,
                bgcolor: 'var(--fa-color-surface-subtle)',
              }}
            >
              <Box sx={{ display: 'flex', alignItems: 'center' }}>{logo}</Box>
              <IconButton aria-label="Close menu" onClick={handleDrawerToggle} size="small">
                <CloseIcon />
              </IconButton>
            </Box>

            <Divider />

            {/* Nav items */}
            <List component="nav" aria-label="Main navigation">
              {items.map((item) =>
                item.children && item.children.length > 0 ? (
                  <MobileCollapsible key={item.label} item={item} onItemClick={closeDrawer} />
                ) : (
                  <ListItemButton
                    key={item.label}
                    component="a"
                    href={item.href}
                    onClick={(e: React.MouseEvent) => {
                      if (item.onClick) {
                        e.preventDefault();
                        item.onClick();
                      }
                      closeDrawer();
                    }}
                    sx={{
                      py: 1.5,
                      px: 3,
                      minHeight: 44,
                      '&:hover': {
                        bgcolor: 'var(--fa-color-brand-100)',
                      },
                    }}
                  >
                    <ListItemText
                      primary={item.label}
                      primaryTypographyProps={{
                        fontWeight: 500,
                        fontSize: '1rem',
                      }}
                    />
                  </ListItemButton>
                ),
              )}
            </List>

            {ctaLabel && (
              <Box sx={{ px: 3, py: 2 }}>
                <Button
                  variant="contained"
                  size="large"
                  fullWidth
                  onClick={() => {
                    if (onCtaClick) onCtaClick();
                    closeDrawer();
                  }}
                >
                  {ctaLabel}
                </Button>
              </Box>
            )}

            {/* Footer */}
            <Box sx={{ mt: 'auto' }}>
              <Divider />
              <Box sx={{ px: 3, py: 2, bgcolor: 'var(--fa-color-surface-subtle)' }}>
                <Typography variant="body2" color="text.secondary">
                  Need help? Call us on
                </Typography>
                <Link
                  href="tel:1800987888"
                  sx={{
                    fontWeight: 600,
                    fontSize: '1rem',
                  }}
                >
                  1800 987 888
                </Link>
              </Box>
            </Box>
          </Drawer>
        )}
      </>
    );
  },
);

Navigation.displayName = 'Navigation';
export default Navigation;
