import React, { useEffect, useState } from "react";
    import withRouter from "../Common/withRouter";
 
    import BrandLogo from "../assets/images/oodles-light-updated-logo.png";
    import BrandlightLogo from "../assets/images/logo.png";
    import BrandSmLogo from "../assets/images/logo-sm.png";
    import { Menu, Tooltip } from "antd";
    import { updateCreaditCard } from "../helpers/backend_helper.js";
    import {  Activity, BarChart, ClockIcon, SettingsIcon } from 'lucide-react';
    import { AreaChart, Bot, Calendar, CalendarCheck, CheckCheck, CheckCheckIcon,   CreditCard, DollarSign,  LayoutDashboard, LineChartIcon, LayoutDashboardIcon, MessageSquareMore, MessagesSquare,  PlusCircle, Send, Settings, Star, User, UserCheck2, UserPlus, Vibrate,  Wallet,  FileTextIcon, } from "lucide-react";
    import { themecolor } from "../config.js";
    import {
      StyleSimpleBar,
      StyleBrandLogo,
      StyleSider,
    } from "../Common/SidebarStyle";
    import { Link, useLocation } from "react-router-dom";
    import googleLogo from './././././../assets/images/brands/google-color-icon (1).png'
    import {  AreaChartOutlined,  CloudSyncOutlined, FacebookFilled,  InfoCircleFilled,  SmileOutlined, TransactionOutlined,   } from "@ant-design/icons";
    import axios from "axios";
    const SidebarLayout = ({ theme }) => {
      const baseUrl = process.env.REACT_APP_BASE_URL;
      const [userRole, setUserRole] = useState(null);
      const [collapsed, setCollapsed] = useState(false);
      const [permissionList	, setPermissions] = useState([]);
      const location = useLocation();
    const handleClick = async () => {
      const mt = JSON.parse(localStorage.getItem('authUser'));
      const pk = mt?.public_key;
      const email = mt?.username;
      try {
        const response = await updateCreaditCard(pk);
        console.log("Response", response)
        console.log('Redirecting to:', response);
        // Step 5: Redirect the user to the portal URL
        window.location.href = response;
     
      } catch (error) {
        console.error('Error during GET request:', error);
      }
    };
  //    useEffect(() => {
  //     const mt = JSON.parse(localStorage.getItem('authUser'));
  //     const pk = mt?.public_key;
  //     const role = mt?.role || "";
  //     const email = mt?.username || "";

  //       if (role.toLowerCase() === "admin") {
  //   console.log("Admin detected. Skipping API call.");
  //   return;
  // }
  //     axios
  //       .get(`${baseUrl}/v1/account/getStaffMember?pk=${pk}&email=${email}`)
  //       .then((response) => {
  //         const responseData = response;
     
  //         console.log("Raw Axios response:", responseData);
  //          const user = responseData[0].role;
  //          console.log(user); // Outputs: USER
  //          setUserRole(user);
  //         if (Array.isArray(responseData) && responseData.length > 0) {
  //           const user = responseData[0];
  //           if (Array.isArray(user.permissions)) {
  //             const permissionNames = user.permissions.map((p) =>
  //               p.name.toLowerCase()
  //             );
  //             console.log("Resolved Permissions:", permissionNames);
  //             setPermissions(permissionNames);
  //           } else {
  //             console.warn("Permissions not found on user");
  //           }
  //         } else {
  //           console.warn("Response is not a valid user array");
  //         }
  //       })
  //       .catch((error) => console.error("Error fetching user data:", error));
  //   }, []);
// useEffect(() => {
//   const authUser = JSON.parse(localStorage.getItem("authUser"));
//   const role = authUser?.role || "";
  
//   // Skip API call if role is admin
//   if (role.toLowerCase() === "admin") {
//     console.log("Admin detected. Skipping API call.");
//     return;
//   }

//   const pk = authUser?.public_key || '';

//   axios
//     .get(`https://api.oodlesai.com/v1/account/getStaffByPk?pk=${pk}`)
//     .then((response) => {
//       const responseData = response?.data;

//       console.log("Raw Axios response:", responseData);

//       const user = responseData[0]?.role;
//       console.log(user); // Outputs: USER
//       setUserRole(user);

//       if (Array.isArray(responseData) && responseData.length > 0) {
//         const user = responseData[0];
//         if (Array.isArray(user.permissions)) {
//           const permissionNames = user.permissions.map((p) =>
//             p.name.toLowerCase()
//           );
//           console.log("Resolved Permissions:", permissionNames);
//           setPermissions(permissionNames);
//         } else {
//           console.warn("Permissions not found on user");
//         }
//       } else {
//         console.warn("Response is not a valid user array");
//       }
//     })
//     .catch((error) => console.error("Error fetching user data:", error));
// }, []);

  useEffect(() => {
  const storedUser = localStorage.getItem('authUser');
  const mt = storedUser ? JSON.parse(storedUser) : {};
  const pk = mt?.pk || mt?.public_key;
  const localRole = mt?.role || "";
  const email = mt?.email || mt?.username || "";

  if (localRole.toLowerCase() === "admin") {
    console.log("Admin detected. Skipping API call.");
    return;
  }

  if (!pk || !email) {
    console.warn("Missing pk or email in localStorage user.");
    return;
  }

  axios
    .get(`${baseUrl}/v1/account/getStaffMember?pk=${pk}&email=${email}`)
    .then((response) => {
      console.log("Full Axios Response:", response);

      const user = response; // updated: it's a single object, not an array

      if (user && typeof user === 'object') {
        const roleFromResponse = user?.role || "";
        console.log("User Role from API:", roleFromResponse);
        setUserRole(roleFromResponse);

        if (Array.isArray(user.permissionList	)) {
          const permissionNames = user.permissionList	
            .filter(p => p?.name)
            .map(p => p.name.toLowerCase());
          console.log("Resolved Permissions:", permissionNames);  
          setPermissions(permissionNames);
        } else {
          console.warn("Permissions not found or invalid format.");
        }
      } else {
        console.warn("User object not valid in response.");
      }
    })
    .catch((error) => {
      console.error("Error fetching user data:", error);
    });
}, []);
     
      function getItem(label, key, icon, children, type, tooltipTitle) {
        return {
          key,
          icon,
          children,
          label: <Tooltip title={tooltipTitle}>{label}</Tooltip>,
          type,
        };
      }
     
         const items = [
            getItem(
              <Tooltip title="Overview of your business performance and AI Agent activities.">
                <Link id="dashboard" to="/dashboard">Dashboard</Link>
              </Tooltip>,
              "managesettings",
              <LayoutDashboard size={16} />,
              []
            ),
         
            getItem(
              <Tooltip title="Engage website visitors with live chat and AI-driven support in real-time.">
                <Link id="webchat">Customer Engagement</Link>
              </Tooltip>,
              "webchat service",
              <MessagesSquare size={22} />,
              [
                getItem(
                  <Tooltip title="Instantly engages visitors, answers questions, and captures leads 24/7.">
                    <Link id="webchat">Webchat Agent</Link>
                  </Tooltip>,
                  "managewebchat",
                  <Bot size={22} />,
                  [
                    getItem(
                      <Link id="chatInbox" to="/app-chat">Chat Inbox</Link>,
                      "managewebchat",
                      <MessagesSquare size={16} />,
                      null,
                      null,
                      "Instantly engages visitors, answers questions, and captures leads 24/7."
                    ),
                    getItem(
                      <Link id="chatAnalytics" to="/chatAnalytics">Chat Analytics</Link>,
                      "chat analytics",
                      <LineChartIcon size={16} />,
                      null,
                      null,
                      "Metrics such as response times and customer satisfaction scores."
                    ),
                  ]
                ),
                getItem(
                  <Tooltip title="Runs automated SMS campaigns to drive customer engagement and repeat visits.">
                    <Link id="smsMarketing" to="">
                      SMS Agent
                      {" "}
                    </Link>
                  </Tooltip>,
                  "managesms",
                  <MessageSquareMore size={16} />,
                  [
                    getItem(
                      <Link id="customer" to="/customersTable">
                        Customers
                      </Link>,
                      "Customer table",
                      <User size={16} />,
                      null,
                      null,
                      " View, add, and manage customer records used for campaigns and outreach. "
                    ),
                    getItem(
                      <Link id="campaigns" to="/sendMessage">
                        Campaigns
                      </Link>,
                      " sms campaigns ",
                      <CheckCheckIcon size={16} />,
                      null,
                      null,
                      "  Create, manage, and track SMS marketing campaigns. "
                    ),
                    getItem(
                      <Link id="campaign-history" to="/campaignHistory">
                        Campaign History
                      </Link>,
                      "sms campaign history",
                      <ClockIcon size={16} />, // use appropriate icon for history
                      null,
                      null,
                      "View logs and analytics of past SMS campaigns."
                    ),
         
         
                    getItem(
                      <Link id="analytics" to="/smsAnalytics">
                        Analytics
                      </Link>,
                      " analytics",
                      <AreaChart size={16} />,
                      null,
                      null,
                      "  Insights on delivery rates, open rates, and conversion rates. "
                    ),
         
                  ]
                ),
                getItem(
                  <Tooltip title="Answers customer calls, schedules appointments, and manages inquiries automatically.">
                    <Link id="voice" to="/#">Voice Agent</Link>
                  </Tooltip>,
                  "managevoice",
                  <UserCheck2 size={16} />,
                  [
                    getItem(
                      <Link id="configuration" to="/voice-agent-settings">
                        Enable Voice Service
                      </Link>,
                      "configuration setup",
                      <LayoutDashboardIcon size={16} />,
                      null,
                      null,
                      "Configure phone number and activate voice services for your business."
                    ),
                    getItem(
                      <Link id="configuration" to="/voice-agent-call">
                        Call Summaries
                      </Link>,
                      "configuration setup",
                      <FileTextIcon size={16} />,
                      null,
                      null,
                      "View transcriptions and summaries of handled voice calls."
                    ),
                    
                    // getItem(
                    //   <Link id="configuration" to="/voice-agent-overview">
                    //     Voice Agent Analytics
                    //   </Link>,
                    //   "configuration setup",
                    //   <BarChartIcon size={16} />,
                    //   null,
                    //   null,
                    //   "Monitor call volume, success rate, and performance metrics of your Voice Agent."
                    // ),
                  ]
                ),
              ],
            ),
            getItem(
              <Tooltip title="Automatically qualifies, nurtures, and converts leads into customers.">
                <Link id="sales $ Reputation" to="">Sales & Reputation</Link>
              </Tooltip>,
              "sales $ Repu",
              <UserCheck2 size={16} />,
              [
                getItem(
                  <Tooltip title="Automatically qualifies, nurtures, and converts leads into customers.">
                    <Link id="leads" to="/leadDashboard">Lead Agent</Link>
                  </Tooltip>,
                  "manageleads",
                  <UserCheck2 size={16} />,
                  []
                ),
                getItem(
                  <Tooltip title="Collects and manages Google & Facebook reviews, auto-responding to boost your reputation.">
                    <Link id="reviews" to="/">
                      Review Agent{" "}
                    </Link>
                  </Tooltip>,
                  "managereviews",
                  <Star size={16} />,
                  [
                    getItem(
                      <Link id="request" to="/add-account">
                        Request Reviews
                      </Link>,
                      "facebook",
                      <Send size={16} />,
                      null,
                      null,
                      "Collect and manage reviews from Facebook."
                    ),
                    getItem(
                      <Link id="write-reviews" to="/reviews-management">
                        Google Reviews
                      </Link>,
                      "google revirews",
                      <img
                        src={googleLogo}
                        alt="Google"
                        style={{ width: "1.0rem", height: "1.0rem" }}
                      />,
                      null,
                      null,
                      "Send requests to customers to leave a review."
                    ),
                    getItem(
                      <Link id="write-reviews" to="/facebook-reviews">
                        Facebook Reviews
                      </Link>,
                      "facebook revirews",
                      <FacebookFilled style={{ color: '#6babff', }} size={16} />,
                      null,
                      null,
                      "Write Comment and Reply  to customers write comment and reply"
                    ),
         
                    getItem(
                      <Link id="reviewAnalytics" to="/LineChart">
                        Review Analytics
                      </Link>,
                      "reviews analytics",
                      <AreaChartOutlined size={16} />,
                      null,
                      null,
                      "Average ratings, review volume over time."
                    ),
                  ]
                ),
                getItem(
                  <Tooltip title="Gathers customer feedback (NPS, CSAT, CES), providing real-time actionable insights.">
                    <Link id="feedback agent" to="/SMSEngagement">
                      Feedback Agent
                      {" "}
                    </Link>
                  </Tooltip>,
                  "managefeedback",
                  <Vibrate size={16} />,
                  [
         
                    getItem(
         
                      <Link id="survey-create" to="/survey-template">
                        Create Surveys
                      </Link>,
                      "survey",
                      <PlusCircle size={16} />,
                      null,
                      null,
                      "Design custom surveys or use templates. "
                    ),
                    getItem(
         
                      <Link id="survey-create" to="/feedback-reply">
                        Recieved Survey
                      </Link>,
                      "recieved survey",
                      <SmileOutlined size={16} />,
                      null,
                      null,
                      "Design custom surveys or use templates. "
                    ),
                    getItem(
         
                      <Link id="survey-create" to="/feedback-recieved">
                        Recieved Feedback
                      </Link>,
                      "managefeedback",
                      <SmileOutlined size={16} />,
                      null,
                      null,
                      "Design custom surveys or use templates. "
                    ),
         
                    getItem(
                      <Link id="feedback-analytics" to="/FeedbackDistribution">
                        Feedback Analytics
                      </Link>,
                      "feedback analytics",
                      <AreaChartOutlined size={16} />,
                      null,
                      null,
                      "Analysis of response rates and trends over time."
                    ),
         
         
                  ]
                ),
         
              ]
            ),
         
            getItem(
              <Tooltip title="Autonomously books appointments, sends reminders, and manages schedules.">
                <Link id="Operations & Automation" to="/">Operations & Automation</Link>
              </Tooltip>,
              "Operations & Automation",
              <Calendar size={16} />,
              [
                getItem(
                  <Tooltip title="Autonomously books appointments, sends reminders, and manages schedules.">
                    <Link id="customerTableLink8" to="/">Appointment Agent</Link>
                  </Tooltip>,
                  "manageappointments",
                  <Calendar size={16} />,
                  [
                    getItem(
                      <Link id="abc19" to="/calendar">Calendar View</Link>,
                      "calendar view",
                      <CalendarCheck size={16} />,
                      null,
                      null,
                      "Visual representation of scheduled appointments."
                    ),
                    getItem(
                      <Link id="abc19" to="/CreateResource">Customer Booking Portal</Link>,
                      "create service",
                      <UserPlus size={16} />,
                      null,
                      null,
                      "Interface for customers to book appointments online."
                    ),
                    getItem(
                      <Link id="abc19" to="/serviceTable">Appointment Analytics</Link>,
                      "service visualize",
                      <AreaChartOutlined size={16} />,
                      null,
                      null,
                      "Metrics on booking rates, cancellations, and no-shows."
                    )
                  ]
                ),
                getItem(
                  <Tooltip title="Automatically invoices customers, securely tracks payments, and ensures timely collections.">
                    <Link id="customerTableLink8" to="/stripe_connect">Payments Agent
                    </Link>
                  </Tooltip>,
                  "managepayments",
                  <DollarSign size={16} />,
         
                  [
         
                    getItem(
                      <Link id="abc19" to="/stripe_connect">
                        Setup New Account
                      </Link>,
                      "managepayments",
                      <UserPlus size={16} />,
                      null,
                      null,
                      "Guide for setting up a new Stripe account or integrating an existing one."
                    ),
                    getItem(
                      <Link id="defabc19" to="/chargeTable">
                        Transactions
                      </Link>,
                      "transactions",
                      <TransactionOutlined size={16} />,
                      null,
                      null,
                      "Detailed transaction history and processing status"
                    ),
                    getItem(
                      <Link id="abc19" to="/Network-value">
                        Payment Analytics
                      </Link>,
                      "payment analytics",
                      <AreaChartOutlined size={16} />,
                      null,
                      null,
                      "Reports on revenue, transaction volumes, and other financial metrics."
                    ),
                  ]
                ),
                getItem(
                  <Tooltip title="Manage and configure your AI Agents' settings, preferences, and automations.">
                    <Link id="assistant" to="/">AI Agent (Central Settings)</Link>
                  </Tooltip>,
                  "manageai assistant",
         
                  <Bot size={16} />,
         
                  [
                    getItem(
                      <Link id="AutomationSettings:" to="/ai-training">
                        AI Training Prompts
                      </Link>,
                      "ai training",
                      <CloudSyncOutlined size={16} />,
                      null,
                      null,
                      "Configure automated responses and customization."
                    ),
                    getItem(
                      <Link id="AutomationsaSettings:" to="/setup-answer">
                        Automation Rules
         
         
                      </Link>,
                      "automation save settings",
                      <Settings size={16} />,
                      null,
                      null,
                      "Configure automated responses and customization."
                    ),
                    // getItem(
                    //   <Link id="AutomationSettingscheck:" to="/setup-answer">
                    //     Agent Performance Overview
         
                    //   </Link>,
                    //   "automation rule settings",
                    //   <Settings size={16} />,
                    //   null,
                    //   null,
                    //   "Configure automated responses and customization."
                    // ),
                  ]
                ),
         
              ]
            ),
            getItem(
              <Tooltip title="Configure your business hours and availability to control when your Oodles platform is active.">
                <Link id="ManagingBusinessHourssave" to="/userChatBoat">Settings</Link>
              </Tooltip>,
              "manage business",
              <Settings size={16} />,
              [
                getItem(
                  <Tooltip title="Monitor and manage your credit usage across all services and campaigns.">
                    <Link id="creditManagement" to="">
                      Usages Credit
                    </Link>
                  </Tooltip>,
                  "managesettings",
                  <CreditCard size={16} />,
                  [
                    getItem(
                      <Link id="creditUsage" to="/track-credits">
                        Track Credits
                      </Link>,
                      "Credit Usage",
                      <Activity size={16} />,
                      null,
                      null,
                      "View and monitor credit consumption across all services and features."
                    ),
                    getItem(
                      <Link id="creditAnalytics" to="/credit-analytics">
                        Credit Analytics
                      </Link>,
                      "credit analytics",
                      <BarChart size={16} />,
                      null,
                      null,
                      "Analyze credit usage patterns and optimize your spending efficiency."
                    ),
                  ]
                ),
                getItem(
                  <span
                    id="ManagingBusinessHoursupdate"
                    // onClick={() => (window.location.href = '/GooglePay')}
                    onClick={handleClick}
                    style={{ cursor: 'pointer', }}
                  >
                    Update Credit Card
                  </span>,
                  "managesettings",
                  <Wallet size={16} />,
                  null,
                  null,
                  "Manage and update your credit card details for seamless payments.."
                ),
                getItem(
                  <Link id="Setting hours" to="/business-hours">
                    Manage Hours
         
                  </Link>,
                  "managesettings",
                  <CreditCard size={16} />,
                  null,
                  null,
                  "Set your business hours, manage availability, and ensure your Oodles platform responds only during working times."
                ),
                getItem(
                  <Link id="manage-campaign" to="/userTable">
                    Manage Staff
                  </Link>,
                  "staff",
                  <CheckCheck size={16} />,
                  null,
                  null,
                  "Manage The Staff Member"
                ),
                getItem(
                  <Link id="BusinessHours" to="/Billing-Invoice">
                    Billing History
                  </Link>,
                  "managesettings",
                  <CreditCard size={16} />,
                  null,
                  null,
                  "Metrics on booking rates, cancellations, and no-shows."
                ),
         
                getItem(
                  <Link id="review-settings" to="/reviewSettings">
                    Review Settings
                  </Link>,
                  "managesettings",
                  <SettingsIcon size={16} />,
                  null,
                  null,
                  "Automate how customer reviews are requested, filtered, and showcased."
                ),

                  getItem(
                  <Link id="review-settings" to="/healthcare-campaign">
                 Healthcare Campaign
                  </Link>,
                  "managesettings",
                  <SettingsIcon size={16} />,
                  null,
                  null,
                  "Our healthcare campaign sends appointment reminders, prescription refill notifications, and important health alerts to patients who have opted in."
                ),
         
              ]
            )
          ];
     
      // const filteredItems = items.filter(
      //   (item) =>
      //     permissions.includes(item.key) ||
      //     (item.children &&
      //       item.children.some((child) => permissions.includes(child.key)))
      // );
    const filteredItems =
  userRole === "USER"
    ? items
        .map((item) => {
          if (permissionList.includes(item.key)) {
            return item;
          } else if (item.children) {
            const filteredChildren = item.children.filter((child) =>
              permissionList.includes(child.key)
            );
            if (filteredChildren.length > 0) {
              return { ...item, children: filteredChildren };
            }
          }
          return null;
        })
        .filter(Boolean)
    : items; // <-- Show all if role is not 'ROLE'

     
     
      const toggleCollapsed = () => {
        setCollapsed(!collapsed);
        const antHeaderMain = document.getElementById("antHeaderMain");
        const antLayoutContent = document.getElementById("antLayoutContent");
        const antFooterLayout = document.getElementById("antFooterLayout");
     
        if (antHeaderMain) antHeaderMain.style.left = !collapsed ? "0px" : "260px";
        if (antLayoutContent) antLayoutContent.style.marginLeft = !collapsed ? "0px" : "260px";
        if (antFooterLayout) antFooterLayout.style.marginLeft = !collapsed ? "0px" : "260px";
      };
     
      const [activatedItem, setActivatedItem] = useState(() => {
        const currentPath = location.pathname.replace("/", "");
        return currentPath || "dashboard";
      });
     
      const toggleActivation = (key) => {
        setActivatedItem((prev) => (prev === key ? null : key));
      };
     
      if (location.pathname === "/app-chat" || location.pathname === "/appchat") {
        return null;
      }
     
      return (
        <React.Fragment>
          <StyleSider
            id="sidebar-layout"
            width={themecolor.components.Menu.verticalSidebarWidth}
            collapsed={collapsed}
            collapsedWidth="100"
            breakpoint="lg"
          >
            <StyleBrandLogo className="demo-logo ant-mx-auto">
              <img
                alt="Brand logo"
                src={theme === "dark" ? BrandlightLogo : BrandLogo}
                height={30}
                style={{ lineHeight: "24px" }}
                className="brand-dark-logo ant-mx-auto"
              />
              <img
                alt="Brand sm logo"
                src={BrandSmLogo}
                height={24}
                style={{ lineHeight: "24px" }}
                className="brand-sm-logo ant-mx-auto"
              />
              {/* <StyledCollapsedButton
                themecolor={themecolor}
                type="link"
                onClick={toggleCollapsed}
              >
                {collapsed ? <ChevronRight /> : <ChevronLeft />}
              </StyledCollapsedButton> */}
            </StyleBrandLogo>
            <div>
              <StyleSimpleBar>
                <Menu
                  selectedKeys={[activatedItem]}
                  mode="inline"
                  theme="light"
                  items={filteredItems}
                  collapsedWidth="100"
                  onClick={({ key }) => toggleActivation(key)}
                  className="custom-menu"
                />
              </StyleSimpleBar>
            </div>
          </StyleSider>
        </React.Fragment>
      );
    };
     
    export default withRouter(SidebarLayout);