import { Layout, Menu, theme, Avatar, Dropdown, Breadcrumb, App, FloatButton } from 'antd';
import { LogoutOutlined, UserOutlined, HomeOutlined, RightOutlined } from '@ant-design/icons';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useState, useMemo } from 'react';
import { setAuthToken } from '../api/axiosInstance';
import { sidebarMenuItems } from '../config/menuConstants';
import { Footer } from 'antd/es/layout/layout';
import { LOGO_URL } from '../config/env'

import { useAppDispatch, useAppSelector } from '../redux/hooks';
import { logout } from '../redux/slices/authSlice';
import TamilInput from '../components/GoogleTranslate/GoogleTranslate';

const { Header, Sider, Content } = Layout;

export default function AuthLayout() {
  const { message } = App.useApp();
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useAppDispatch();
  const user = useAppSelector((state) => state.auth.user);
  const logo = LOGO_URL;
  const {
    token: { colorBgContainer },
  } = theme.useToken();
  const [collapsed, setCollapsed] = useState(false);

  // Get root-level submenu keys (groups that have children)
  const rootSubmenuKeys = useMemo(() => {
    return sidebarMenuItems
      .filter((item: any) => item?.children)
      .map((item: any) => item.key as string);
  }, []);

  // Compute which parent submenus should be open based on the current path
  const getOpenKeysForPath = useMemo(() => {
    const openKeys: string[] = [];
    const findOpenKeys = (items: any[], parents: string[] = []): boolean => {
      for (const item of items) {
        if (!item) continue;
        if ((item as any).children) {
          const newParents = [...parents, (item as any).key as string];
          if (findOpenKeys((item as any).children, newParents)) {
            openKeys.push(...newParents);
            return true;
          }
        } else if ((item as any).key === location.pathname) {
          openKeys.push(...parents);
          return true;
        }
      }
      return false;
    };
    findOpenKeys(sidebarMenuItems);
    return [...new Set(openKeys)];
  }, [location.pathname]);

  const [openKeys, setOpenKeys] = useState<string[]>(getOpenKeysForPath);

  // Accordion behavior: only one root-level submenu open at a time
  const onOpenChange = (keys: string[]) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (latestOpenKey && rootSubmenuKeys.includes(latestOpenKey)) {
      // Close other root-level submenus, keep nested ones
      setOpenKeys(
        keys.filter((key) => !rootSubmenuKeys.includes(key) || key === latestOpenKey)
      );
    } else {
      setOpenKeys(keys);
    }
  };

  const handleLogout = () => {
    setAuthToken(null);
    dispatch(logout());
    navigate('/login', { replace: true });
    message.success('Logged out successfully');
  };

  const getBreadcrumbTitle = (pathUrl: string, segment: string) => {

    const findTitle = (items: any[], key: string): string | null => {
      for (const item of items) {
        if (!item) continue;
        if (item.key === key && item.title) return item.title;
        if (item.children) {
          const found = findTitle(item.children, key);
          if (found) return found;
        }
      }
      return null;
    };

    const title = findTitle(sidebarMenuItems, pathUrl) || findTitle(sidebarMenuItems, segment);
    if (title) return title;

    return segment
      .split("-")
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(" ");
  };

  const breadcrumbItems = location.pathname
    .split("/")
    .filter(Boolean)
    .map((_, index, arr) => {
      const url = "/" + arr.slice(0, index + 1).join("/");

      return {
        title: getBreadcrumbTitle(url, arr[index]),
      };
    });

  return (
    <Layout style={{ height: "100vh", overflow: "hidden" }}>
      {/* Sidebar */}
      <Sider
        width={240}
        theme="light"
        collapsible
        collapsed={collapsed}
        breakpoint="lg"
        onCollapse={setCollapsed}
        className="border-r border-gray-200"
        style={{
          position: "fixed",
          left: 0,
          top: 0,
          bottom: 0,
          overflow: "hidden",
        }}
      >
        <div className="flex h-full flex-col ">
          <div className="flex-1 overflow-y-auto">
            <div className="bg-white">
              <img
                src={logo}
                className="w-22.5 h-auto object-cover mx-auto pb-2 pt-1 cursor-pointer"
                alt="AVS Enterprise"
                onClick={() => navigate("/")}
              />
            </div>

            <Menu
              mode="inline"
              theme="light"
              selectedKeys={[location.pathname]}
              openKeys={openKeys}
              onOpenChange={onOpenChange}
              items={sidebarMenuItems}
              onClick={(e) => navigate(e.key)}
              className="border-0"
            />
          </div>
        </div>
      </Sider>

      {/* Main Layout */}
      <Layout
        style={{
          marginLeft: collapsed ? 80 : 240,
          height: "100vh",
        }}
      >
        {/* Fixed Header */}
        <Header
          className="flex items-center justify-between bg-white shadow-sm px-6"
          style={{
            position: "fixed",
            top: 0,
            left: collapsed ? 80 : 240,
            right: 0,
            height: 64,
            zIndex: 1000,
            background: colorBgContainer,
          }}
        >
          {/* <h1 className="text-xl font-semibold text-gray-800">
            Vegetable Management
          </h1> */}
          <div>
            <Breadcrumb
              separator={<RightOutlined className="text-gray-400 text-xs" />}
              items={[
                {
                  title: (
                    <div className="w-8 h-6 rounded-full border border-gray-300 bg-white flex items-center justify-center">
                      <HomeOutlined className="text-green-600" onClick={() => navigate("/")} />
                    </div>
                  ),
                },
                ...breadcrumbItems.map((item, index) => ({
                  title:
                    index === breadcrumbItems.length - 1 ? (
                      <span className="px-2 py-1 rounded-full bg-green-600 text-white font-sm text-sm">
                        {item.title}
                      </span>
                    ) : (
                      <span className="text-gray-600 font-medium text-sm">{item.title}</span>
                    ),
                })),
              ]}
            />
          </div>
          <div className='flex items-center'>
            <TamilInput />
            <Dropdown
              trigger={["hover"]}
              placement="bottomRight"
              popupRender={() => (
                <div className="bg-white rounded-xl shadow-lg border border-gray-100 w-48 overflow-hidden">
                  <div className="py-1">
                    <div
                      className="flex items-center gap-2 px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 cursor-pointer"
                      onClick={() => navigate("/profile")}
                    >
                      <UserOutlined />
                      My Profile
                    </div>
                  </div>

                  <div className="border-t border-gray-100 py-1">
                    <div
                      className="flex items-center gap-2 px-4 py-2.5 text-sm text-red-500 hover:bg-red-50 cursor-pointer"
                      onClick={handleLogout}
                    >
                      <LogoutOutlined />
                      Logout
                    </div>
                  </div>
                </div>
              )}
            >
              <div className="flex items-center gap-3 cursor-pointer px-2 py-1.5 rounded-lg hover:bg-gray-50">
                <Avatar
                  src={user?.profileUrl}
                  size={40}
                  icon={<UserOutlined />}
                  className="bg-green-600"
                />
                <div className="border-l-4 border-green-600 pl-3 hidden lg:block">
                  <p className="text-sm font-semibold">{user?.name}</p>
                  <p className="text-xs text-gray-500">{user?.role}</p>
                </div>
              </div>
            </Dropdown>
          </div>
        </Header>

        {/* Scrollable Area */}
        <Layout
          style={{
            marginTop: 64,
            height: "calc(100vh - 64px)",
          }}
        >
          <Content
            id="scrollable-content"
            style={{
              overflowY: "auto",
              padding: 16,
              flex: 1,
            }}
          >
            <Outlet />
          </Content>

          {/* Fixed Footer */}
          <Footer
            style={{
              textAlign: "center",
              background: colorBgContainer,
              borderTop: "1px solid #f0f0f0",
              flexShrink: 0,
            }}
          >
            AVS Enterprise ©{new Date().getFullYear()} Created by <a href="https://techcmantix.com/" target="_blank" rel="noopener noreferrer">Techcmantix pvt ltd</a>
          </Footer>
        </Layout>
        <FloatButton.BackTop
          target={() => document.getElementById('scrollable-content') || window}
          style={{ insetInlineEnd: 24, bottom: 24 }}
          shape="circle"
          showProgress={true}
          visibilityHeight={0}
        />
      </Layout>
    </Layout>
  );
}
