"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth";
import { useChatStore } from "@/store/chat";
import ChatInterface from "@/components/chat/chat-interface";
import Sidebar from "@/components/chat/sidebar";
import MobileNav from "@/components/layout/mobile-nav";
import LoadingSpinner from "@/components/ui/loading-spinner";
import { Button } from "@/components/ui/button";
import { PanelLeftClose, PanelLeftOpen } from "lucide-react";

export default function ChatPage() {
  const router = useRouter();
  const { isAuthenticated, user, isLoading: authLoading } = useAuthStore();
  const { loadSessions, sessions } = useChatStore();
  const [isInitialized, setIsInitialized] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [initialLoading, setInitialLoading] = useState(true);

  useEffect(() => {
    if (!authLoading && !isAuthenticated) {
      router.push("/login");
      return;
    }

    if (isAuthenticated && !isInitialized) {
      loadSessions().then(() => setInitialLoading(false));
      setIsInitialized(true);
    }
  }, [isAuthenticated, authLoading, isInitialized, router, loadSessions]);

  if (authLoading || initialLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div className="h-[calc(100vh-4rem)] bg-background">
      <div className="h-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex gap-4 py-4">
        {/* Mobile overlay */}
        {sidebarOpen && (
          <div
            className="fixed inset-0 bg-black/30 z-30 md:hidden"
            onClick={() => setSidebarOpen(false)}
          />
        )}

        {/* Sidebar — persistent on desktop, overlay on mobile */}
        <div className={`
          shrink-0 z-40
          w-[260px] rounded-xl border border-border/40 bg-card shadow-sm
          transition-all duration-200 ease-in-out overflow-hidden
          fixed md:relative md:top-auto md:left-auto md:bottom-auto
          ${sidebarOpen ? 'translate-x-0' : '-translate-x-full md:hidden'}
        `}>
          <Sidebar onClose={() => setSidebarOpen(false)} />
        </div>

        {/* Main chat area */}
        <div className="flex-1 flex flex-col min-w-0 relative rounded-xl border border-border/40 bg-card shadow-sm overflow-hidden">
          {/* Toggle button */}
          {!sidebarOpen && (
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setSidebarOpen(true)}
              className="absolute top-3 left-3 z-10 h-9 w-9 text-muted-foreground hover:text-foreground hover:bg-muted/50"
            >
              <PanelLeftOpen className="w-5 h-5" />
            </Button>
          )}

          <ChatInterface />
        </div>
      </div>

      <MobileNav />
    </div>
  );
}
