/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useRef, useEffect } from "react";
import React from "react";
import {
  MessageCircle,
  X,
  Calendar,
  Images,
  Minimize2,
  Maximize2,
  Plane,
  Hotel,
  Expand,
  Map,
} from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkBreaks from "remark-breaks";
import remarkGfm from "remark-gfm";
import type {
  UnifiedMessage,
  UserMessage,
  AIUnifiedMessage,
  Itinerary,
  Marker,
  HotelImage,
} from "../types";
import toast from "react-hot-toast";
import MapSection from "./MapSection";
import { ItinerarySection } from "./ItinerarySection";
import { InclusionSection } from "./InclusionSection";
import { HotelImagesSection } from "./HotelImagesSection";
import { ChatInput } from "./ChatInput";
import { v4 as uuidv4 } from "uuid";

interface HotelChatWidgetProps {
  config?: {
    apiKey?: string;
    baseUrl?: string;
    theme?: "light" | "dark";
    position?: "bottom-right" | "bottom-left";
    googleMapsApiKey?: string;
  };
}

const useAuth = () => {
  const isConnected = true;
  const userId = localStorage.getItem("userId");
  if (userId) {
    return { isConnected, userId };
  }
  const code = uuidv4();
  localStorage.setItem("userId", code);
  return { isConnected, userId };
};


export default function HotelChatWidget({ config = {} }: HotelChatWidgetProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [isMinimized, setIsMinimized] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);
  const [activeTab, setActiveTab] = useState<
    "chat" | "itinerary" | "gallery" | "map" | "inclusion"
  >("chat");
  const [expandedRightPanel, setExpandedRightPanel] = useState<
    "itinerary" | "gallery" | "map" | "inclusion"
  >("itinerary");
  const [unifiedMessages, setUnifiedMessages] = useState<UnifiedMessage[]>([]);
  const [inputValue, setInputValue] = useState("");
  const [isStreaming, setIsStreaming] = useState(false);
  const [itinerary, setItinerary] = useState<Itinerary>();
  const [hotelImagesData, setHotelImagesData] = useState<HotelImage[]>();
  const [chunks, setChunks] = useState<any[][]>([]);
  const [markers, setMarkers] = useState<Marker[]>([]);
  const [hoveredMarker, setHoveredMarker] = useState<Marker>();
  const [selectedImageLink, setSelectedImageLink] = useState<HotelImage | null>(
    null
  );
  const [agent, setAgent] = useState<"itinerary-agent" | "hotel-agent">();

  console.log("unifiedMessages", unifiedMessages);

  console.log("Debug hoveredMarker", hoveredMarker);
  console.log("isStreaming", isStreaming);

  // Use config values
  const CHAT_BASE_URL = config.baseUrl || "https://trib-api.bukprotocol.ai";
  const position = config.position || "bottom-right";
  const theme = config.theme || "light";

  // Authentication and session
  const { isConnected,userId } = useAuth();
 // const { currentSession, setCurrentSession } = useSession();

  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Auto-resize textarea
  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto";
      textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
    }
  }, [inputValue]);

  // Auto-scroll to bottom
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  // Auto-scroll when messages change or streaming updates
  useEffect(() => {
    scrollToBottom();
  }, [unifiedMessages, isStreaming, chunks]);

  // Process chunks into unified message structure
  useEffect(() => {
    if (chunks.length === 0) return;

    const flattenedParts = chunks.flat();
    if (flattenedParts.length === 0) return;

    const unifiedMessage: AIUnifiedMessage = {
      id: `unified-${Date.now()}`,
      timestamp: Date.now(),
      statusContent: "",
      mainContent: "",
      places: [],
      itineraryData: null,
      hotelImagesData: [] as HotelImage[],
      isStreaming: true,
      type: "ai_unified",
    };

    const newHotelImages: HotelImage[] = [];

    flattenedParts.forEach((part) => {
      // if (part?.metadata?.messageType === "completion") {
      //   return;
      // }

      if (part?.metadata?.agent) {
        setAgent(part?.metadata?.agent);
      }

      console.log("part", part);

      const isStatusUpdate = part?.metadata?.category === "status_update";
      const isText = part?.type === "text";
      const isPlace = part?.type === "place";
      const isData = part?.type === "data";

      if (isText) {
        if (isStatusUpdate) {
          unifiedMessage.statusContent += part.text || "";
        } else {
          unifiedMessage.mainContent += part.text || "";
        }
      } else if (isPlace) {
        unifiedMessage.places.push(part.place);
      } else if (isData) {
        if (part.metadata?.agent === "hotel-agent") {
          const image = {
            ...part.data?.image,
            kind: part.data?.kind,
            section: part.data?.section,
          };
          unifiedMessage.hotelImagesData = [
            ...unifiedMessage.hotelImagesData,
            image,
          ];
          newHotelImages.push(image);
        } else {
          unifiedMessage.itineraryData = part;
          setItinerary(part);
        }
      }
    });

    // Only update hotel images if there are new ones
    if (newHotelImages.length > 0) {
      setHotelImagesData(newHotelImages);
    }

    setUnifiedMessages((prev) => {
      const existingIndex = prev.findIndex(
        (msg) => msg.type === "ai_unified" && msg.isStreaming
      );

      if (existingIndex !== -1) {
        const updated = [...prev];
        updated[existingIndex] = unifiedMessage;
        return updated;
      } else {
        return [...prev, unifiedMessage];
      }
    });
  }, [chunks]);

  // Mark streaming as complete
  useEffect(() => {
    if (!isStreaming) {
      setUnifiedMessages((prev) => {
        const updated = prev.map((msg) =>
          msg.type === "ai_unified" && msg.isStreaming
            ? { ...msg, isStreaming: false }
            : msg
        );
        return updated;
      });
    }
  }, [isStreaming]);

  // Integrated handleSend function with your API logic
  const handleSend = async (userInput: string) => {
    if (!isConnected) {
      toast.error("Please login to send messages.");
      return;
    }

    const trimmedInput = userInput.trim();
    setInputValue("");
    if (!trimmedInput) return;

    // Add user message to unified messages
    const newUserMessage: UserMessage = {
      id: `user-${Date.now()}`,
      type: "user",
      content: trimmedInput,
      timestamp: Date.now(),
    };

    setUnifiedMessages((prev) => [...prev, newUserMessage]);

    // Clear chunks for new AI response
    setChunks([]);
    setIsStreaming(true);

    let sessionId = localStorage.getItem('sessionId') 

    try {
      const response = await fetch(`${CHAT_BASE_URL}/route`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(
          sessionId
            ? {
                message: trimmedInput,
                userId: userId,
                sessionId: sessionId,
              }
            : {
                message: trimmedInput,
                userId: userId,
              }
        ),
      });

      if (!response.ok || !response.body) {
        console.error("❌ Invalid response");
        toast.error("Failed to get response from server");
        setIsStreaming(false);
        return;
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder("utf-8");

      while (true) {
        const { value, done } = await reader.read();
        if (done) {
          break;
        }

        const chunk = decoder.decode(value, { stream: true });
        const lines = chunk.split(/\r?\n/);

        for (let line of lines) {
          line = line.trim();
          if (!line) continue;
          if (line.startsWith("data:")) line = line.replace(/^data:\s*/, "");

          try {
            const parsed = JSON.parse(line);
            console.log("parsed", parsed);

            if (parsed.sessionId && !sessionId) {
              localStorage.setItem("sessionId",parsed.sessionId)
              sessionId=parsed.sessionId
            }
            if (parsed?.status?.message?.parts) {
              const parts = parsed.status.message.parts;
              const newParts = parts.map((part: any) => ({
                ...part,
                metadata: parsed.status.metadata,
                sender: "ai",
              }));

              setChunks((prev) => [...prev, newParts]);

              // Process markers for map
              const newMarkers = newParts
                .filter((p: any) => p.type === "place")
                .map((p: any, i: number) => ({
                  id: Date.now() + i,
                  lat: p.place.latitude,
                  lng: p.place.longitude,
                  label: p.place.name,
                }));

              setMarkers((prev) => [...prev, ...newMarkers]);

              const typeData = newParts.find((p: any) => p.type === "data");
              if (typeData && typeData.metadata?.agent !== "hotel-agent") {
                console.log("🔍 Type data found:", typeData);
                setItinerary(typeData);
                // Auto-switch to itinerary tab when itinerary data is received
                // if (!isExpanded) {
                //   setActiveTab("itinerary");
                // } else {
                //   setExpandedRightPanel("itinerary");
                // }
              }

              if (typeData && typeData.metadata?.agent === "hotel-agent") {
                console.log("🏨 Hotel images data found:", typeData);
                setHotelImagesData(typeData);
                // Auto-switch to gallery tab when hotel images are received
                // if (!isExpanded) {
                //   setActiveTab("gallery");
                // } else {
                //   setExpandedRightPanel("gallery");
                // }
              }
            }
          } catch (error) {
            console.error("❌ Error parsing chunk:", chunk, error);
          }
        }
      }
    } catch (error) {
      console.error("❌ Error in handleSend:", error);
      toast.error("Failed to send message");
    } finally {
      console.log("🛑 Streaming ended");
      setIsStreaming(false);
      // Unified messages will be marked as complete in the useEffect above
    }
  };

  const handleSendMessage = async () => {
    if (!inputValue.trim()) return;
    await handleSend(inputValue);
  };

  const hasMarkdownContent = (text: string): boolean => {
    const cleanText = text.replace(/\\\\n/g, "\n").replace(/\\n/g, "\n");
    const markdownPatterns = [
      /^#{1,6}\s+/m,
      /\*\*[^*]+\*\*/,
      /\*[^*]+\*/,
      /`[^`]+`/,
      /```[\s\S]*?```/,
      /^\s*[-*+]\s+/m,
      /^\s*\d+\.\s+/m,
      /^\s*\|.*\|.*$/m,
      /^\s*>\s+/m,
      /\[([^\]]+)\]$$([^)]+)$$/,
      /!\[([^\]]*)\]$$([^)]+)$$/,
      /^\s*---+\s*$/m,
      /\n\s*\n/,
    ];

    return markdownPatterns.some((pattern) => pattern.test(cleanText));
  };

  const createMarkdownComponents = (
    places: any[],
    hotelImages: HotelImage[]
  ) => ({
    p: ({ children }: any) => (
      <p className="markdown-paragraph">
        {processMarkdownChildren(children, places, hotelImages)}
      </p>
    ),
    strong: ({ children }: any) => (
      <strong className="markdown-strong">
        {processMarkdownChildren(children, places, hotelImages)}
      </strong>
    ),
    em: ({ children }: any) => (
      <em className="markdown-em">
        {processMarkdownChildren(children, places, hotelImages)}
      </em>
    ),
    code: ({ children }: any) => (
      <code className="markdown-code">
        {processMarkdownChildren(children, places, hotelImages)}
      </code>
    ),
    pre: ({ children }: any) => (
      <pre className="markdown-pre">
        <code className="markdown-pre-code">
          {processMarkdownChildren(children, places, hotelImages)}
        </code>
      </pre>
    ),
    ul: ({ children }: any) => (
      <ul className="markdown-ul">
        {processMarkdownChildren(children, places, hotelImages)}
      </ul>
    ),
    ol: ({ children }: any) => (
      <ol className="markdown-ol">
        {processMarkdownChildren(children, places, hotelImages)}
      </ol>
    ),
    li: ({ children }: any) => (
      <li className="markdown-li">
        {processMarkdownChildren(children, places, hotelImages)}
      </li>
    ),
    a: ({ href, children }: any) => (
      <a href={href} className="markdown-link">
        {processMarkdownChildren(children, places, hotelImages)}
      </a>
    ),
    br: () => <br />,
    div: ({ children }: any) => (
      <div>{processMarkdownChildren(children, places, hotelImages)}</div>
    ),
    h1: ({ children }: any) => (
      <p className="markdown-h1">
        {processMarkdownChildren(children, places, hotelImages)}
      </p>
    ),
    h2: ({ children }: any) => (
      <p className="markdown-h2">
        {processMarkdownChildren(children, places, hotelImages)}
      </p>
    ),
    h3: ({ children }: any) => (
      <p className="markdown-h3">
        {processMarkdownChildren(children, places, hotelImages)}
      </p>
    ),
    h4: ({ children }: any) => (
      <h4 className="markdown-h4">
        {processMarkdownChildren(children, places, hotelImages)}
      </h4>
    ),
    h5: ({ children }: any) => (
      <h5 className="markdown-h5">
        {processMarkdownChildren(children, places, hotelImages)}
      </h5>
    ),
    h6: ({ children }: any) => (
      <h6 className="markdown-h6">
        {processMarkdownChildren(children, places, hotelImages)}
      </h6>
    ),
    blockquote: ({ children }: any) => (
      <blockquote className="markdown-blockquote">
        {processMarkdownChildren(children, places, hotelImages)}
      </blockquote>
    ),
    hr: () => <hr className="markdown-hr" />,
    table: ({ children }: any) => (
      <div className="markdown-table-wrapper">
        <table className="markdown-table">
          {processMarkdownChildren(children, places, hotelImages)}
        </table>
      </div>
    ),
    thead: ({ children }: any) => (
      <thead className="markdown-thead">
        {processMarkdownChildren(children, places, hotelImages)}
      </thead>
    ),
    tbody: ({ children }: any) => (
      <tbody>{processMarkdownChildren(children, places, hotelImages)}</tbody>
    ),
    tr: ({ children }: any) => (
      <tr className="markdown-tr">
        {processMarkdownChildren(children, places, hotelImages)}
      </tr>
    ),
    th: ({ children }: any) => (
      <th className="markdown-th">
        {processMarkdownChildren(children, places, hotelImages)}
      </th>
    ),
    td: ({ children }: any) => (
      <td className="markdown-td">
        {processMarkdownChildren(children, places, hotelImages)}
      </td>
    ),
  });

  const renderUnifiedMessage = (
    message: AIUnifiedMessage,
    hotelImages: HotelImage[]
  ) => {
    return (
      <div key={message.id}>
        {message.statusContent.trim() && (
          <div className="status-content">
            <div className="status-content-text">
              {message.statusContent.trim()}
            </div>
          </div>
        )}
        {message.mainContent.trim() && (
          <div className="main-content">
            {hasMarkdownContent(message.mainContent.trim()) ? (
              <ReactMarkdown
                components={createMarkdownComponents(
                  message.places || [],
                  hotelImages || []
                )}
                remarkPlugins={[remarkBreaks, remarkGfm]}
              >
                {message.mainContent.trim()}
              </ReactMarkdown>
            ) : (
              <div className="main-content-text">
                {message.mainContent.trim()}
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // Helper function to convert text with inline place links
  const renderTextWithPlaceLinks = (text: string, places: any[]) => {
    if (!places || places.length === 0) {
      return text;
    }

    // Sort places by name length (longest first) to handle overlapping names correctly
    const sortedPlaces = [...places].sort(
      (a, b) => b.name.length - a.name.length
    );

    // Find all place mentions in the text
    const placeMatches: Array<{
      start: number;
      end: number;
      place: any;
      matchedText: string;
    }> = [];

    sortedPlaces.forEach((place) => {
      // Create multiple regex patterns to catch different variations
      const patterns = [
        // Exact match with word boundaries
        new RegExp(
          `\\b${place.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`,
          "gi"
        ),
        // Match without strict word boundaries (for places with special characters)
        new RegExp(
          `${place.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
          "gi"
        ),
        // Match with flexible spacing/punctuation
        new RegExp(
          `${place.name
            .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
            .replace(/\s+/g, "\\s*")}`,
          "gi"
        ),
      ];

      patterns.forEach((regex) => {
        let match;
        // Reset regex lastIndex for each pattern
        regex.lastIndex = 0;
        while ((match = regex.exec(text)) !== null) {
          const matchStart = match.index;
          const matchEnd = match.index + match[0].length;

          // Check if this match overlaps with existing matches
          const overlaps = placeMatches.some((existing) => {
            return (
              (matchStart >= existing.start && matchStart < existing.end) ||
              (matchEnd > existing.start && matchEnd <= existing.end) ||
              (matchStart <= existing.start && matchEnd >= existing.end)
            );
          });

          if (!overlaps) {
            placeMatches.push({
              start: matchStart,
              end: matchEnd,
              place: place,
              matchedText: match[0],
            });
          }

          // Prevent infinite loop
          if (regex.lastIndex === match.index) {
            regex.lastIndex++;
          }
        }
      });
    });

    // Sort matches by start position
    placeMatches.sort((a, b) => a.start - b.start);

    // Remove overlapping matches, keeping the longest ones
    const filteredMatches: Array<{
      start: number;
      end: number;
      place: any;
      matchedText: string;
    }> = [];
    for (const match of placeMatches) {
      const hasOverlap = filteredMatches.some((existing) => {
        return (
          (match.start >= existing.start && match.start < existing.end) ||
          (match.end > existing.start && existing.end) ||
          (match.start <= existing.start && match.end >= existing.end)
        );
      });

      if (!hasOverlap) {
        filteredMatches.push(match);
      }
    }

    // If no matches found, return original text
    if (filteredMatches.length === 0) {
      return text;
    }

    // Build the final JSX with clickable place links
    const parts: React.ReactNode[] = [];
    let lastIndex = 0;

    filteredMatches.forEach((match, index) => {
      // Add text before this match
      if (match.start > lastIndex) {
        parts.push(text.slice(lastIndex, match.start));
      }

      // Add clickable place link
      parts.push(
        <span
          key={`place-link-${index}-${match.start}`}
          className="place-link"
          title={match.place.description || match.place.name}
          onMouseEnter={() => {
            setHoveredMarker({
              id: index,
              label: match?.place?.name,
              lat: match?.place?.latitude,
              lng: match?.place?.longitude,
            });
            setActiveTab("map");
            setExpandedRightPanel("map");
            setMarkers((prev) => {
              const alreadyExists = prev.some(
                (marker) =>
                  marker.lat === match?.place?.latitude &&
                  marker.lng === match?.place?.longitude
              );

              if (alreadyExists) return prev;

              return [
                ...prev,
                {
                  id: index,
                  label: match?.place?.name,
                  lat: match?.place?.latitude,
                  lng: match?.place?.longitude,
                },
              ];
            });
          }}
          onMouseLeave={() => setHoveredMarker(undefined)}
          onClick={() => {
            const lat = match?.place?.latitude;
            const lng = match?.place?.longitude;
            const url = `https://www.google.com/maps?q=${lat},${lng}`;
            window.open(url, "_blank");
          }}
        >
          <span style={{ fontSize: "14px" }}>📍</span>
          {match.matchedText} <span style={{ fontSize: "10px" }}>↗</span>
        </span>
      );

      lastIndex = match.end;
    });

    // Add remaining text after last match
    if (lastIndex < text.length) {
      parts.push(text.slice(lastIndex));
    }

    return <>{parts}</>;
  };

  const renderTextWithHotelImageLinks = (
    text: string,
    hotelImages: HotelImage[]
  ) => {
    if (!hotelImages || hotelImages.length === 0) return text;

    // Extract all unique sections
    const uniqueSections = Array.from(
      new Set(hotelImages.map((img) => img.section).filter(Boolean))
    );

    // Sort by length to avoid partial matches (e.g., 'Room' before 'Room Deluxe')
    const sortedSections = [...uniqueSections].sort(
      (a, b) => b.length - a.length
    );

    const sectionMatches: Array<{
      start: number;
      end: number;
      matchedText: string;
      section: string;
    }> = [];

    sortedSections.forEach((section) => {
      const pattern = new RegExp(
        `\\b${section.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`,
        "gi"
      );
      let match;
      while ((match = pattern.exec(text)) !== null) {
        const start = match.index;
        const end = match.index + match[0].length;

        // Avoid overlapping matches
        const overlaps = sectionMatches.some(
          (m) =>
            (start >= m.start && start < m.end) ||
            (end > m.start && end <= m.end)
        );

        if (!overlaps) {
          sectionMatches.push({
            start,
            end,
            matchedText: match[0],
            section,
          });
        }

        // Prevent infinite loop
        if (pattern.lastIndex === match.index) pattern.lastIndex++;
      }
    });

    // If no match, return original text
    if (sectionMatches.length === 0) return text;

    // Now build final JSX
    const parts: React.ReactNode[] = [];
    let lastIndex = 0;

    sectionMatches.sort((a, b) => a.start - b.start);
    sectionMatches.forEach((match, index) => {
      if (match.start > lastIndex) {
        parts.push(text.slice(lastIndex, match.start));
      }

      parts.push(
        <span
          key={`hotel-img-${index}`}
          className="image-text-hyperlink"
          title={`Show images of ${match.section}`}
          onClick={() => {
            const filtered = hotelImages.filter(
              (img) => img.section.toLowerCase() === match.section.toLowerCase()
            );
            console.log("Matched section:", match.section);
            console.log("Filtered hotel images:", filtered);
            // Call any handler here like setHotelImagesData(filtered);
            //alert(`📸 Showing ${filtered.length} image(s) of ${match.section}`);
            setSelectedImageLink(filtered[0]);
            setHotelImagesData(hotelImages);
            setActiveTab("gallery");
            setExpandedRightPanel("gallery");
          }}
          // onMouseEnter={() => {
          //   const filtered = hotelImages.filter(
          //     (img) => img.section.toLowerCase() === match.section.toLowerCase()
          //   );
          //   const img = filtered[0];
          //   const imgElement = document.getElementById(img.image_url);

          //   if (imgElement) {
          //     imgElement.scrollIntoView({
          //       behavior: "smooth",
          //       block: "center",
          //     });
          //     imgElement.classList.add(
          //       "shadow-xl",
          //       "shadow-gray-400",
          //       "transition-shadow",
          //       "scale-105"
          //     );
          //   }

          //   setHoveredImageLink(img || null);
          // }}
          // onMouseLeave={() => {
          //   const filtered = hotelImages.filter(
          //     (img) => img.section.toLowerCase() === match.section.toLowerCase()
          //   );
          //   const img = filtered[0];
          //   const imgElement = document.getElementById(img.image_url);
          //   setHoveredImageLink(null);
          //   if (imgElement) {
          //     imgElement.classList.remove(
          //       "shadow-xl",
          //       "shadow-gray-400",
          //       "transition-shadow",
          //       "scale-105"
          //     );
          //   }
          // }}
        >
          <span style={{ fontSize: "14px" }}>🖼️</span>
          {match.matchedText} <span style={{ fontSize: "10px" }}>↗</span>
        </span>
      );

      lastIndex = match.end;
    });

    if (lastIndex < text.length) {
      parts.push(text.slice(lastIndex));
    }

    return <>{parts}</>;
  };

  const renderSmartText = (
    text: string,
    places: any[],
    hotelImages: HotelImage[]
  ) => {
    const withImgLinks = renderTextWithHotelImageLinks(text, hotelImages);
    if (typeof withImgLinks === "string") {
      return renderTextWithPlaceLinks(withImgLinks, places);
    }
    return withImgLinks;
  };

  // Helper function to process markdown children and apply place linking
  const processMarkdownChildren = (
    children: any,
    places: any[],
    hotelImages: HotelImage[]
  ) => {
    if (typeof children === "string") {
      return renderSmartText(children, places, hotelImages);
    }

    if (Array.isArray(children)) {
      return children.map((child, index) => {
        if (typeof child === "string") {
          return (
            <React.Fragment key={index}>
              {renderSmartText(child, places, hotelImages)}
            </React.Fragment>
          );
        }
        return child;
      });
    }

    return children;
  };

  const VISIBLE_TABS = agent
    ? agent === "hotel-agent"
      ? [
          { id: "chat", label: "Chat", icon: MessageCircle },
          { id: "map", label: "Map", icon: Map },
          { id: "gallery", label: "Gallery", icon: Images },
        ]
      : agent === "itinerary-agent"
      ? [
          { id: "chat", label: "Chat", icon: MessageCircle },
          { id: "map", label: "Map", icon: Map },
          { id: "itinerary", label: "Itinerary", icon: Calendar },
          { id: "inclusion", label: "Inclusion", icon: Hotel },
        ]
      : HOTEL_ASSISTANT_TABS
    : HOTEL_ASSISTANT_TABS;

  // Chat Messages Component
  const ChatMessages = () => (
    <div className="chat-messages">
      {unifiedMessages.length === 0 && !isStreaming && (
        <div className="welcome-message">
          <p className="welcome-title">Where to today?</p>
          <div className="welcome-content">
            <Plane className="welcome-icon" />
            <p className="welcome-text">
              Hey there! I'm here to assist you in planning your experience. Ask
              me anything travel related.
            </p>
          </div>
        </div>
      )}
      {unifiedMessages
        .sort((a, b) => a.timestamp - b.timestamp)
        .map((message) => {
          if (message.type === "user") {
            return (
              <div key={message.id} className="user-message-container">
                <div className="user-message">
                  <p className="user-message-text">{message.content}</p>
                </div>
              </div>
            );
          } else {
            return renderUnifiedMessage(message, message.hotelImagesData);
          }
        })}
      {isStreaming && (
        <div className="streaming-indicator">
          <span className="streaming-dot">●</span>
          <span className="streaming-dot streaming-dot-delay-1">●</span>
          <span className="streaming-dot streaming-dot-delay-2">●</span>
        </div>
      )}
      <div ref={messagesEndRef} className="messages-end" />
    </div>
  );

  if (!isOpen) {
    return (
      <div className={`chat-widget ${position} ${theme}`}>
        <button onClick={() => setIsOpen(true)} className="chat-open-button">
          <MessageCircle className="chat-open-icon" />
        </button>
      </div>
    );
  }

  // Expanded Modal View
  if (isExpanded) {
    return (
      <div className="modal-overlay">
        <div className="modal-container">
          {/* Modal Header */}
          <div className="chat-header">
            <div className="header-title">
              <MessageCircle className="header-icon" />
              <p className="header-text">Hotel Assistant</p>
            </div>
            <div className="header-actions">
              <button
                onClick={() => setIsExpanded(false)}
                className="header-button"
              >
                <Minimize2 className="header-button-icon" />
              </button>
              <button
                onClick={() => {
                  setIsExpanded(false);
                  setIsOpen(false);
                }}
                className="header-button"
              >
                <X className="header-button-icon" />
              </button>
            </div>
          </div>

          {/* Modal Content */}
          <div className="modal-content">
            {/* Left Panel - Chat */}
            <div className="modal-left-panel">
              <div className="modal-panel-header">
                <p className="modal-panel-title">Chat</p>
              </div>
              <div className="modal-chat-messages">
                <ChatMessages />
              </div>
              <ChatInput
                handleKeyDown={handleKeyDown}
                handleSendMessage={handleSendMessage}
                inputValue={inputValue}
                isStreaming={isStreaming}
                setInputValue={setInputValue}
                textareaRef={textareaRef}
              />
            </div>

            {/* Right Panel - Itinerary/Gallery/Map/Inclusion */}
            <div className="modal-right-panel">
              {/* Right Panel Header */}
              <div className="modal-right-panel-header">
                <div className="modal-right-panel-tabs">
                  {VISIBLE_TABS.map(({ id, label, icon: Icon }) => {
                    const isActive = expandedRightPanel === id;
                    return (
                      <button
                        key={id}
                        onClick={() =>
                          setExpandedRightPanel(
                            id as "itinerary" | "gallery" | "map" | "inclusion"
                          )
                        }
                        className={`modal-right-panel-tab ${
                          isActive ? "active" : ""
                        }`}
                        aria-pressed={isActive}
                      >
                        <Icon className="modal-right-panel-tab-icon" />
                        {label}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Right Panel Content */}
              {expandedRightPanel === "itinerary" ? (
                <ItinerarySection
                  isStreaming={isStreaming}
                  itinerary={itinerary}
                />
              ) : expandedRightPanel === "gallery" ? (
                <HotelImagesSection
                  hotelImagesData={hotelImagesData}
                  isStreaming={isStreaming}
                  selectedImageLink={selectedImageLink}
                  setSelectedImageLink={setSelectedImageLink}
                />
              ) : expandedRightPanel === "map" ? (
                <MapSection markers={markers} hoveredMarker={hoveredMarker} />
              ) : (
                <InclusionSection
                  isStreaming={isStreaming}
                  itinerary={itinerary}
                />
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Regular Widget View
  return (
    <div className={`chat-widget-container ${position} ${theme}`}>
      <div className={`chat-widget-main ${isMinimized ? "minimized" : ""}`}>
        {/* Header */}
        <div className="widget-header">
          <div className="widget-header-title">
            <MessageCircle className="widget-header-icon" />
            <p className="widget-header-text">Hotel Assistant</p>
          </div>
          <div className="widget-header-actions">
            <button
              onClick={() => setIsExpanded(true)}
              className="widget-header-button"
              title="Expand"
            >
              <Expand className="widget-header-button-icon" />
            </button>
            <button
              onClick={() => setIsMinimized(!isMinimized)}
              className="widget-header-button"
            >
              {isMinimized ? (
                <Maximize2 className="widget-header-button-icon" />
              ) : (
                <Minimize2 className="widget-header-button-icon" />
              )}
            </button>
            <button
              onClick={() => setIsOpen(false)}
              className="widget-header-button"
            >
              <X className="widget-header-button-icon" />
            </button>
          </div>
        </div>

        {!isMinimized && (
          <>
            {/* Tab Navigation */}
            <div className="widget-tabs">
              {VISIBLE_TABS.map(({ id, label, icon: Icon }) => (
                <button
                  key={id}
                  onClick={() =>
                    setActiveTab(
                      id as
                        | "chat"
                        | "itinerary"
                        | "gallery"
                        | "map"
                        | "inclusion"
                    )
                  }
                  className={`widget-tab ${activeTab === id ? "active" : ""}`}
                >
                  <Icon className="widget-tab-icon" />
                  {label}
                </button>
              ))}
            </div>

            <div className="widget-content">
              {/* Chat Tab */}
              {activeTab === "chat" && (
                <>
                  <div className="widget-chat-container">
                    <ChatMessages />
                  </div>
                  <ChatInput
                    handleKeyDown={handleKeyDown}
                    handleSendMessage={handleSendMessage}
                    inputValue={inputValue}
                    isStreaming={isStreaming}
                    setInputValue={setInputValue}
                    textareaRef={textareaRef}
                  />
                </>
              )}

              {/* Itinerary Tab */}
              {activeTab === "itinerary" && (
                <ItinerarySection
                  isStreaming={isStreaming}
                  itinerary={itinerary}
                />
              )}

              {/* Gallery Tab */}
              {activeTab === "gallery" && (
                <HotelImagesSection
                  hotelImagesData={hotelImagesData}
                  isStreaming={isStreaming}
                  selectedImageLink={selectedImageLink}
                  setSelectedImageLink={setSelectedImageLink}
                />
              )}

              {/* Map Tab */}
              {activeTab === "map" && (
                <MapSection markers={markers} hoveredMarker={hoveredMarker} />
              )}

              {/* Inclusion Tab */}
              {activeTab === "inclusion" && (
                <InclusionSection
                  isStreaming={isStreaming}
                  itinerary={itinerary}
                />
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

const HOTEL_ASSISTANT_TABS = [
  { id: "chat", label: "Chat", icon: MessageCircle },
  { id: "map", label: "Map", icon: Map },
  { id: "itinerary", label: "Itinerary", icon: Calendar },
  { id: "inclusion", label: "Inclusion", icon: Hotel },
  { id: "gallery", label: "Gallery", icon: Images },
];
