"use client";

import { useEffect, Suspense } from "react";
import { useRouter } from "next/navigation";
import Dashboard from "@/components/dashboard/dashboard";
import { MessageCircle } from "lucide-react";
import dynamic from "next/dynamic";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent, CardHeader } from "@/components/ui/card";

// Lazy load the ChatTable component
const ChatTable = dynamic(() => import("@/components/dashboard/ChatTable"), {
  loading: () => <ChatTableSkeleton />
});

// Loading skeleton for the chat table
function ChatTableSkeleton() {
  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <Skeleton className="h-6 w-32" />
          <Skeleton className="h-9 w-24" />
        </div>
      </CardHeader>
      <CardContent>
        <div className="border rounded-lg">
          <div className="border-b p-4">
            <div className="flex items-center gap-4">
              {['Customer', 'Last Message', 'Date', 'Status', 'Actions'].map((header, i) => (
                <Skeleton key={i} className="h-4 w-20 flex-1" />
              ))}
            </div>
          </div>
          
          {[...Array(6)].map((_, i) => (
            <div key={i} className="border-b last:border-b-0 p-4">
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-3 flex-1">
                  <Skeleton className="h-10 w-10 rounded-full" />
                  <div className="space-y-1">
                    <Skeleton className="h-4 w-32" />
                    <Skeleton className="h-3 w-24" />
                  </div>
                </div>
                <Skeleton className="h-4 w-40 flex-1" />
                <Skeleton className="h-4 w-20 flex-1" />
                <Skeleton className="h-6 w-16 flex-1" />
                <div className="flex gap-2 flex-1">
                  <Skeleton className="h-8 w-16" />
                  <Skeleton className="h-8 w-16" />
                </div>
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

export default function ChatsPage() {
  const router = useRouter();

  useEffect(() => {
    const authToken = document.cookie
      .split("; ")
      .find((row) => row.startsWith("Authorization="))
      ?.split("=")[1];

    if (!authToken) {
      router.push("/login");
    }
  }, [router]);

  return (
    <Dashboard>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-semibold text-gray-900 dark:text-white flex items-center">
            <MessageCircle className="mr-2 h-6 w-6" />
            Customer Chats
          </h1>
        </div>
        
        <Suspense fallback={<ChatTableSkeleton />}>
          <ChatTable />
        </Suspense>
      </div>
    </Dashboard>
  );
} 