
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { mockRentalRequests } from "@/lib/mockData";
import type { RentalRequest, MessageEntry } from "@/types";
import { getI18n } from "@/locales/server";
import type { Locale } from "@/locales/server";
import Link from "next/link";
import { MessageSquareQuote, ToyBrick } from "lucide-react";
import { format } from 'date-fns';

const currentUserId = 1; // Assume this is the logged-in user's ID

// Helper function to get the other participant in a conversation
const getOtherParticipant = (request: RentalRequest, currentUserId: number) => {
  if (request.toy.ownerId === currentUserId) {
    return { id: request.requesterId, name: request.requesterName };
  }
  return { id: request.toy.ownerId, name: request.toy.ownerName };
};

export default async function MessagesPage({ params }: { params: { locale: Locale } }) {
  const t = await getI18n();
  const locale = params.locale;

  const userConversations = mockRentalRequests.filter(req => 
    (req.toy.ownerId === currentUserId || req.requesterId === currentUserId) && 
    req.messages && req.messages.length > 0
  );

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-3xl font-bold font-headline text-primary">{t('dashboard.messages.title')}</h1>
        <p className="text-muted-foreground">{t('dashboard.messages.description')}</p>
      </div>

      {userConversations.length === 0 ? (
        <Card className="text-center py-12 shadow-md">
          <CardHeader>
            <MessageSquareQuote className="h-16 w-16 mx-auto text-muted-foreground mb-4" />
            <CardTitle>{t('dashboard.messages.no_messages_title')}</CardTitle>
            <CardDescription>{t('dashboard.messages.no_messages_description')}</CardDescription>
          </CardHeader>
          <CardContent>
            <Link href={`/${locale}/`} passHref>
              <Button size="lg">
                <ToyBrick className="mr-2 h-5 w-5" />
                {t('dashboard.messages.go_find_toys')}
              </Button>
            </Link>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-6">
          {userConversations.map(request => {
            const otherParticipant = getOtherParticipant(request, currentUserId);
            const lastMessage = request.messages![request.messages!.length - 1];
            const formattedTimestamp = lastMessage ? format(new Date(lastMessage.timestamp), 'PPp') : '';

            return (
              <Card key={request.id} className="shadow-md hover:shadow-lg transition-shadow">
                <CardHeader>
                  <CardTitle className="text-xl font-headline">
                    {t('dashboard.messages.conversation_with', { name: otherParticipant.name })}
                  </CardTitle>
                  <CardDescription>
                    {t('dashboard.messages.about_toy', { toyName: request.toy.name })}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  {lastMessage && (
                    <div className="text-sm text-muted-foreground">
                      <p className="font-medium text-foreground line-clamp-2">
                        {t('dashboard.messages.last_message_from', { senderName: lastMessage.senderName, text: lastMessage.text })}
                      </p>
                      <p className="text-xs mt-1">{formattedTimestamp}</p>
                    </div>
                  )}
                </CardContent>
                <CardFooter>
                  <Link href={`/${locale}/dashboard/messages/${request.id}`} passHref>
                    <Button variant="outline">{t('dashboard.messages.view_conversation_button')}</Button>
                  </Link>
                </CardFooter>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
