
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import ToyList from '@/components/toys/ToyList';
import { mockToys } from '@/lib/mockData';
import type { Toy } from '@/types';
import { getI18n, getStaticParams as getLocaleStaticParams } from '@/locales/server';
import { Home, UserCircle } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { ToyBrick } from 'lucide-react';
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";

interface OwnerToysPageProps {
  params: { ownerId: string; locale: string };
}

// Mock owner profiles - can be expanded or moved to a data file later
const mockOwnerProfiles: Record<string, { avatarUrl: string; bio: string; name?: string }> = {
  'user1': { // Alice Wonderland
    name: 'Alice W.', // Can be different from toy.ownerName for display
    avatarUrl: 'https://placehold.co/100x100.png?text=AW',
    bio: "Lover of imaginative play and sharing joy. I have a collection of classic storybooks and dress-up costumes that my kids have outgrown but still have lots of life left in them!"
  },
  'user2': { // Bob The Builder
    name: 'Bob T.B.',
    avatarUrl: 'https://placehold.co/100x100.png?text=BT',
    bio: "Can we fix it? Yes, we can! Sharing my collection of construction toys, tools, and playsets. Always happy to help another budding builder."
  },
  'user3': { // Carol Danvers
    name: 'Captain C.',
    avatarUrl: 'https://placehold.co/100x100.png?text=CD',
    bio: "Higher, further, faster. Sharing toys that inspire adventure, courage, and exploration. My collection includes superhero action figures and space-themed playsets."
  }
};


async function getOwnerToys(ownerId: string): Promise<Toy[]> {
  await new Promise(resolve => setTimeout(resolve, 100)); // Simulate fetch
  return mockToys.filter(toy => toy.ownerId === ownerId);
}

export default async function OwnerToysPage({ params }: OwnerToysPageProps) {
  const t = await getI18n();
  const ownerToys = await getOwnerToys(params.ownerId);
  
  const ownerProfile = mockOwnerProfiles[params.ownerId];
  const ownerNameFromToys = ownerToys.length > 0 ? ownerToys[0].ownerName : undefined;

  let displayOwnerName = ownerProfile?.name || ownerNameFromToys || t('owner_toys.unknown_owner');
  
  const pageTitle = displayOwnerName !== t('owner_toys.unknown_owner')
    ? t('owner_toys.title_specific', { ownerName: displayOwnerName })
    : t('owner_toys.title_generic');

  return (
    <div className="space-y-8">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <h1 className="text-3xl font-bold font-headline text-primary">{pageTitle}</h1>
        <Link href={`/${params.locale}/`} passHref>
          <Button variant="outline" className="w-full sm:w-auto">
            <Home className="mr-2 h-4 w-4" />
            {t('owner_toys.back_to_home')}
          </Button>
        </Link>
      </div>

      {ownerProfile && (
        <Card className="mb-8 shadow-lg border-accent/30">
          <CardHeader>
            <div className="flex flex-col sm:flex-row items-center gap-4">
              <Avatar className="h-20 w-20 sm:h-24 sm:w-24 border-2 border-accent">
                <AvatarImage src={ownerProfile.avatarUrl} alt={displayOwnerName} data-ai-hint="owner avatar" />
                <AvatarFallback className="text-3xl bg-muted">
                  {displayOwnerName ? displayOwnerName.split(' ').map(n => n[0]).join('').toUpperCase() : <UserCircle />}
                </AvatarFallback>
              </Avatar>
              <div className="text-center sm:text-left">
                <CardTitle className="text-2xl font-headline text-accent">
                  {t('owner_toys.about_owner', { ownerName: displayOwnerName })}
                </CardTitle>
                {/* Display the original ownerName from toy data if it's different and available */}
                {ownerNameFromToys && ownerNameFromToys !== displayOwnerName && (
                   <CardDescription>{t('toy_details.owner')}: {ownerNameFromToys}</CardDescription>
                )}
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <p className="text-foreground/80 leading-relaxed">{ownerProfile.bio}</p>
          </CardContent>
        </Card>
      )}

      {ownerToys.length > 0 ? (
        <ToyList toys={ownerToys.map(toy => ({...toy, dataAiHint: toy.category.toLowerCase()}))} />
      ) : (
        <Card className="text-center py-12 shadow-md">
          <CardHeader>
            <ToyBrick className="h-16 w-16 mx-auto text-muted-foreground mb-4" />
            <CardTitle>
              {displayOwnerName !== t('owner_toys.unknown_owner') 
                ? t('owner_toys.no_toys_listed_by', { ownerName: displayOwnerName }) 
                : t('owner_toys.owner_not_found')}
            </CardTitle>
            {displayOwnerName !== t('owner_toys.unknown_owner') && <CardDescription>{t('home.explore_toys')}</CardDescription>}
          </CardHeader>
          <CardContent>
            <Link href={`/${params.locale}/`} passHref>
              <Button size="lg">
                {t('home.explore_toys')}
              </Button>
            </Link>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

export async function generateStaticParams() {
  const localeParams = getLocaleStaticParams(); 
  
  const ownerIds = Array.from(new Set(mockToys.map(toy => toy.ownerId)));
  const ownerParams = ownerIds.map(id => ({ ownerId: id }));

  return localeParams.flatMap(lang => 
    ownerParams.map(owner => ({ ...lang, ...owner }))
  );
}
