


// "use client";
// import TitleCard from "@/components/TitleCard/TitleCard";
// import CustomMarkdownRenderer from "@/components/ui/MarkDown";
// import { Tabs } from "@/components/ui/Tab";
// import { Toast } from "@/components/ui/Toast";
// import { AIAssistantContent } from "@/types/staticContent/ai-assistant.content.type";
// import { formatUtcToIst } from "@/utils/Functions";
// import { getClientDictionary } from "@/utils/getClientDictionary";
// import { useDebounce } from "@/utils/Hooks/useDebounce";
// import { useAuthStore } from "@/zustand/auth/useAuthStore";
// import { useDocumentStore } from "@/zustand/documentManagement/useDocumentStore";
// import dynamic from "next/dynamic";
// import Image from "next/image";
// import { useEffect, useRef, useState } from "react";


// type Props = {};

// const TailwindSelect = dynamic(() => import("@/components/ui/Select"), {
//   ssr: false,
// });

// function Page({ }: Props) {
//   const { language } = useAuthStore();
//   const { AI_ASSISTANT } = getClientDictionary(language, "ai-assistant") as AIAssistantContent;

//   const [question, setQuestion] = useState("");
//   const [tempMessage, setTempMessage] = useState<any | null>(null);
//   const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
//   const [activeType, setActiveType] = useState<"regulatory" | "company_policy">("regulatory");

//   // Track feedback state for each message
//   const [messageFeedback, setMessageFeedback] = useState<Record<string, boolean>>({});

//   const { documents, isLoading, listDocuments, sendMessage, getChatHistory, messages, clearMessages, dislikeMsg } =
//     useDocumentStore();
//   const { profileDetails, viewProfile } = useAuthStore();

//   const [document, setDocument] = useState<{
//     document_name: string;
//     id: string;
//   } | null>(null);

//   const chatRef = useRef<HTMLUListElement>(null);
//   const bottomRef = useRef<HTMLDivElement>(null);

//   // Load documents when tab / type changes
//   useEffect(() => {
//     listDocuments({ params: { document_type: activeType } }, undefined, false);
//     viewProfile();
//     return () => {
//       clearMessages();
//     };
//   }, [listDocuments, activeType, clearMessages, viewProfile]);

//   const handleKeyPress = (e: React.KeyboardEvent) => {
//     if (e.key === "Enter" && !e.shiftKey) {
//       e.preventDefault();
//       handleMessageSend();
//     }
//   };

//   const handleMessageSend = async () => {
//     if (question.trim() === "") return;
//     if (document == null) {
//       Toast("error", "Please select a document");
//       return;
//     }

//     const payload = {
//       question,
//       document_id: document?.id || null,
//       document_type: activeType,
//     };

//     setTempMessage({
//       type: "user",
//       message: question,
//       timestamp: new Date().toISOString(),
//       isTemp: true,
//     });

//     setQuestion("");
//     setIsWaitingForResponse(true);

//     await sendMessage(payload);
//     setIsWaitingForResponse(false);
//   };

//   useEffect(() => {
//     if (messages.length > 0) {
//       setTempMessage(null);
//       setIsWaitingForResponse(false);
//     }
//   }, [messages]);

//   useEffect(() => {
//     bottomRef.current?.scrollIntoView({
//       behavior: "smooth",
//       block: "end",
//     });
//   }, [tempMessage, isWaitingForResponse, document]);
//   const handleDocumentChange = (option: any) => {
//     getChatHistory({ document_id: option?.id || null }, () => { setDocument(option); });

//   };
//   const handleFeedback = (messageId: string, currentIsDisliked: boolean) => {
//     const newIsDisliked = !currentIsDisliked;

//     dislikeMsg(
//       {
//         message_id: messageId,
//         is_disliked: newIsDisliked,
//       },
//       // Success callback — only here we update local messages
//       (success) => {
//         success && useDocumentStore.setState((state) => ({
//           messages: state.messages.map((msg) =>
//             msg.message_id === messageId
//               ? { ...msg, is_disliked: newIsDisliked }
//               : msg
//           ),
//         }));

//         // Optional: small toast / visual feedback
//         // Toast("success", newIsDisliked ? "Disliked" : "Dislike removed");
//       },
//       true // keep your third param as is
//     );
//   };
//   const debouncedFeedback = useDebounce(handleFeedback, 300);

//   return (
//     <>
//       <TitleCard
//         title={AI_ASSISTANT.TITLE}
//         description={AI_ASSISTANT.SETUP_TITLE}
//         iconName="icon-ai-magic"
//         tagSpanIcon="icon-building"
//         tagSpanText="hi"
//       />

//       <Tabs
//         defaultActive="regulatory"
//         onTabChange={(key) => {
//           setActiveType(key as "regulatory" | "company_policy");
//           setDocument(null);
//         }}
//         tabs={[
//           {
//             key: "regulatory",
//             label: AI_ASSISTANT.DOCUMENT_TYPES.REGULATORY,
//             content: (
//               <>
//                 <TailwindSelect
//                   options={documents}
//                   value={document}
//                   onChange={(option: any) => handleDocumentChange(option)}
//                   placeholder={AI_ASSISTANT.SELECT_DOCUMENT}
//                   getOptionLabel={(option: any) => option.document_name}
//                   getOptionValue={(option: any) => option.id}
//                 />

//                 <div className="mt-4 sm:mt-5 lg:mt-6 relative">
//                   <ul
//                     ref={chatRef}
//                     className="overflow-y-auto overflow-x-hidden pb-5 h-[calc(100dvh-440px)] sm:h-[calc(100dvh-390px)] md:h-[calc(100dvh-410px)] lg:h-[calc(100dvh-455px)] 2xl:h-[calc(100dvh-550px)] [-ms-overflow-style:'none'] [scrollbar-width:'none'] [&::-webkit-scrollbar]:hidden flex flex-col gap-5"
//                   >
//                     {[...messages, ...(tempMessage ? [tempMessage] : [])].map((msg: any, index: number) => {

//                       return (
//                         <li
//                           className={`flex gap-3 md:gap-4 text-sm md:text-base md:w-1/2 
//                             ${language === "en"
//                               ? `${msg.type === "user" ? "ml-auto flex-row-reverse" : ""}`
//                               : `${msg.type === "ai" ? "mr-auto flex-row-reverse" : ""}`
//                             }
//                           `
//                           }
//                           key={index}
//                         >
//                           <span className="bg-dark-green3c rounded-xl shrink-0 w-10 h-10 sm:w-12 sm:h-12 lg:w-14 lg:h-14 flex items-center justify-center">
//                             {msg.type === "ai" ? (
//                               <i className="icon icon-chat-bot w-4 h-4 sm:w-5 sm:h-5 lg:w-6 lg:h-6 bg-primary"></i>
//                             ) : profileDetails?.profile_picture ? (
//                               <Image
//                                 src={profileDetails.profile_picture}
//                                 alt="User"
//                                 width={48}
//                                 height={48}
//                                 className="w-full h-full rounded-full object-cover"
//                               />
//                             ) : (
//                               <i className="icon icon-user w-4 h-4 sm:w-5 sm:h-5 lg:w-6 lg:h-6 bg-primary"></i>
//                             )}
//                           </span>

//                           <span
//                             className={`flex [&>a]:text-primary [&>a]:hover:underline! [&>span]:block [&>span]:break-word [&>span]:whitespace-normal text-light flex-col gap-3 sm:gap-4 2xl:gap-6 w-fit bg-theme-bg rounded-xl 2xl:rounded-2xl lg:rounded-[20px] p-4 2xl:p-5 `}
//                           >
//                             <CustomMarkdownRenderer markdown={msg.message} textAlign={msg.type === "ai" && !msg.isTemp && msg.language === "Arabic" ? "right" : "left"} />



//                             <div className="flex items-center justify-between gap-3">
//                               <span className="text-grey99">{formatUtcToIst(msg.timestamp)}</span>

//                               {/* {msg.type === "ai" && !msg.isTemp && (
//                                 <div className="flex items-center gap-2">
//                                   <button
//                                     onClick={() => handleFeedback(msg.timestamp, "like")}
//                                     className={`cursor-pointer transition-all duration-200 hover:scale-110 ${messageFeedback[msg.timestamp] === "like" ? "scale-110" : ""
//                                       }`}
//                                     aria-label="Like this message"
//                                     title={messageFeedback[msg.timestamp] === "like" ? "Remove like" : "Like"}
//                                   >
//                                     <i
//                                       className={`icon icon-like w-3.5 h-3.5 lg:w-4.5 lg:h-4.5 transition-colors text-gray-400 ${messageFeedback[msg.timestamp] === "like"
//                                         ? "bg-green-500"
//                                         : "bg-light"
//                                         }`}
//                                     ></i>
//                                   </button>

//                                   <button
//                                     onClick={() => handleFeedback(msg.message_id, !msg.is_disliked)}
//                                     className={`cursor-pointer transition-all duration-200 hover:scale-110 ${messageFeedback[msg.is_disliked] === true ? "scale-110" : ""
//                                       }`}
//                                     aria-label="Dislike this message"
//                                     title={messageFeedback[msg.is_disliked] === true ? "Remove dislike" : "Dislike"}
//                                   >
//                                     <i
//                                       className={`icon icon-dislike w-3.5 h-3.5 lg:w-4.5 lg:h-4.5 transition-colors text-gray-400 ${messageFeedback[msg.is_disliked] === true
//                                         ? "bg-red-500"
//                                         : "bg-light"
//                                         }`}
//                                     ></i>
//                                   </button>
//                                 </div>
//                               )} */}
//                               {msg.type === "ai" && !msg.isTemp && (
//                                 <div className="flex items-center gap-2 justify-end"> {/* or justify-start depending on direction */}

//                                   <button
//                                     onClick={() => debouncedFeedback(msg.message_id, msg.is_disliked)}
//                                     className={`cursor-pointer transition-all duration-200 hover:scale-110 ${msg.is_disliked ? "scale-110" : ""
//                                       }`}
//                                     aria-label={msg.is_disliked ? "Remove dislike" : "Dislike this message"}
//                                     title={msg.is_disliked ? "Remove dislike" : "Dislike"}

//                                   >
//                                     <i
//                                       className={`icon icon-dislike w-3.5 h-3.5 lg:w-4.5 lg:h-4.5 transition-colors ${msg.is_disliked
//                                         ? "bg-red-500"
//                                         : "text-gray-400 bg-light"  // or just "bg-light" depending on your icon styling
//                                         }`}
//                                     ></i>
//                                   </button>
//                                 </div>
//                               )}
//                             </div>
//                           </span>
//                         </li>
//                       )
//                     })}

//                     {isWaitingForResponse && (
//                       <li className="flex gap-3 md:gap-4 text-sm md:text-base md:w-1/2">
//                         <span className="bg-dark-green3c rounded-xl shrink-0 w-10 h-10 sm:w-12 sm:h-12 lg:w-14 lg:h-14 flex items-center justify-center">
//                           <i className="icon icon-chat-bot w-4 h-4 sm:w-5 sm:h-5 lg:w-6 lg:h-6 bg-primary"></i>
//                         </span>

//                         <span className="flex text-light flex-col gap-3 sm:gap-4 2xl:gap-6 w-fit bg-theme-bg rounded-xl 2xl:rounded-2xl lg:rounded-[20px] p-4 2xl:p-5">
//                           <div className="flex items-center gap-2">
//                             <div
//                               className="w-2 h-2 bg-primary rounded-full animate-bounce"
//                               style={{ animationDelay: "0ms" }}
//                             ></div>
//                             <div
//                               className="w-2 h-2 bg-primary rounded-full animate-bounce"
//                               style={{ animationDelay: "150ms" }}
//                             ></div>
//                             <div
//                               className="w-2 h-2 bg-primary rounded-full animate-bounce"
//                               style={{ animationDelay: "300ms" }}
//                             ></div>
//                           </div>
//                         </span>
//                       </li>
//                     )}

//                     <div ref={bottomRef} />
//                   </ul>

//                   <div className="border-t border-grey2b pt-4 w-full 2xl:pt-6 bg-secondary">
//                     <form className="sticky z-1 mb-3 lg:mb-4 bottom-0 left-0 w-full flex gap-2.5 items-center">
//                       <input
//                         type="text"
//                         placeholder={AI_ASSISTANT.CHAT.PLACEHOLDER}
//                         className="w-full text-sm md:text-base font-normal leading-tight outline-none pr-8 px-4 md:px-5 py-3 md:py-4 rounded-xl 2xl:rounded-2xl border border-grey32 bg-secondary25 focus:border-light"
//                         value={question}
//                         onChange={(e) => setQuestion(e.target.value)}
//                         onKeyDown={handleKeyPress}
//                       />

//                       <button
//                         className="bg-primary cursor-pointer transition-all duration-300 hover:bg-primary-c1 rounded-xl shrink-0 w-10 h-10 sm:w-12 sm:h-12 lg:w-14 lg:h-14 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed"
//                         type="button"
//                         disabled={isLoading || question.trim() === "" || isWaitingForResponse}
//                         onClick={handleMessageSend}
//                       >
//                         <i className="icon icon-sent w-4 h-4 sm:w-5 sm:h-5 lg:w-6 lg:h-6 bg-secondary11"></i>
//                       </button>
//                     </form>

//                     <p className="text-center text-grey92 text-sm md:text-base">
//                       {AI_ASSISTANT.CHAT.SEND_HINT} • {AI_ASSISTANT.CHAT.GUIDANCE}
//                     </p>
//                   </div>
//                 </div>
//               </>
//             ),
//           },
//           {
//             key: "company",
//             label: AI_ASSISTANT.DOCUMENT_TYPES.COMPANY_POLICY,
//             content: (
//               <div className="text-light">
//                 {AI_ASSISTANT.DOCUMENT_TYPES.COMPANY_POLICY_COMING_SOON}
//               </div>
//             ),
//           },
//         ]}
//       />
//     </>
//   );
// }

// export default Page;
"use client";
import TitleCard from "@/components/TitleCard/TitleCard";
import { Tabs } from "@/components/ui/Tab";
import { AIAssistantContent } from "@/types/staticContent/ai-assistant.content.type";
import { getClientDictionary } from "@/utils/getClientDictionary";
import { useAuthStore } from "@/zustand/auth/useAuthStore";
import { useDocumentStore } from "@/zustand/documentManagement/useDocumentStore";
import { useEffect, useState } from "react";
import RegulatoryChat from "./_components/RegulatoryChat";
import CompanyPolicyChat from "./_components/CompanyPolicyChat";



type Props = {};

function Page({ }: Props) {
  const { language } = useAuthStore();
  const { AI_ASSISTANT } = getClientDictionary(language, "ai-assistant") as AIAssistantContent;

  const [activeType, setActiveType] = useState<"regulatory" | "company_policy">("regulatory");

  return (
    <>
      <TitleCard
        title={AI_ASSISTANT.TITLE}
        description={AI_ASSISTANT.SETUP_TITLE}
        iconName="icon-ai-magic"
        tagSpanIcon="icon-building"
        tagSpanText="hi"
      />

      <Tabs
        defaultActive="regulatory"
        onTabChange={(key) => setActiveType(key as "regulatory" | "company_policy")}
        tabs={[
          {
            key: "regulatory",
            label: AI_ASSISTANT.DOCUMENT_TYPES.REGULATORY,
            content: <RegulatoryChat />,
          },
          {
            key: "company_policy  ",
            label: AI_ASSISTANT.DOCUMENT_TYPES.COMPANY_POLICY,
            content: <CompanyPolicyChat />,
          },
        ]}
      />
    </>
  );
}

export default Page;