'use client'

import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { MessageCircle } from 'lucide-react'

interface Props {
  projectId: string
}

export function MentorConversationCard({ projectId }: Props) {
  const { data, isLoading } = trpc.applicant.getMentorConversationPreview.useQuery(
    { projectId, limit: 3 },
    { refetchInterval: 30_000 },
  )

  if (isLoading) return <Skeleton className="h-44 w-full rounded-md" />
  if (!data || !data.mentor) return null // No mentor assigned — render nothing

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center justify-between gap-2 text-base">
          <span className="flex items-center gap-2">
            <MessageCircle className="h-4 w-4" /> Conversation with{' '}
            {data.mentor.name ?? data.mentor.email}
          </span>
          {data.unreadCount > 0 && <Badge variant="default">{data.unreadCount} new</Badge>}
        </CardTitle>
      </CardHeader>
      <CardContent>
        {data.messages.length === 0 ? (
          <p className="text-muted-foreground text-sm">
            Say hi to your mentor — they&apos;re here to help you sharpen your project.
          </p>
        ) : (
          <ul className="space-y-2">
            {data.messages.map((m) => (
              <li key={m.id} className="bg-muted/20 rounded-md border p-2.5">
                <div className="text-muted-foreground text-xs">
                  {m.sender.name ?? m.sender.email}
                </div>
                <div className="mt-0.5 line-clamp-2 text-sm">{m.message}</div>
              </li>
            ))}
          </ul>
        )}
        <div className="mt-3 flex justify-end">
          <Button asChild size="sm">
            <Link href="/applicant/mentor">Open chat</Link>
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
