'use client';

import { Chat } from '@prisma/client';
import React from 'react';
import {
  SelectItem,
  Select,
  SelectTrigger,
  SelectContent,
  SelectIcon,
  SelectGroup,
  SelectSeparator,
} from './ui/Select';
import Img from './ui/Img';
import { format } from 'date-fns';
import { useParams, useRouter } from 'next/navigation';
import { IconPlus } from './ui/Icons';

export interface ChatSelectProps {
  chat: Chat;
}

const ChatSelectItem: React.FC<ChatSelectProps> = ({ chat }) => {
  const { id, title, mediaUrl, updatedAt } = chat;
  return (
    <SelectItem value={id} className="size-full cursor-pointer">
      <div className="overflow-hidden flex items-center size-full group">
        <div className="size-[36px] relative m-1">
          <Img
            src={mediaUrl}
            alt={`chat-${id}-card-image`}
            className="object-cover size-full"
          />
        </div>
        <div className="flex items-start flex-col h-full ml-3">
          <p className="text-sm mb-1">{title ?? '(no title)'}</p>
          <p className="text-xs text-gray-500">
            {updatedAt ? format(Number(updatedAt), 'yyyy-MM-dd') : '-'}
          </p>
        </div>
      </div>
    </SelectItem>
  );
};

const ChatSelect: React.FC<{ myChats: Chat[] }> = ({ myChats }) => {
  const { id: chatIdFromParam } = useParams();

  const currentChat = myChats.find(chat => chat.id === chatIdFromParam);
  const router = useRouter();
  return (
    <Select
      defaultValue={currentChat?.id}
      value={currentChat?.id}
      onValueChange={id => router.push(`/chat${id === 'new' ? '' : '/' + id}`)}
    >
      <SelectTrigger className="w-[240px]">
        {currentChat?.title ?? 'Select a conversation'}
      </SelectTrigger>
      <SelectContent className="w-[320px]">
        <SelectGroup>
          <SelectItem value="new">
            <div className="flex items-center justify-start">
              <SelectIcon asChild>
                <IconPlus className="size-4 opacity-50" />
              </SelectIcon>
              <div className="ml-4">New conversion</div>
            </div>
          </SelectItem>
          {!!myChats.length && <SelectSeparator />}
          {myChats.map(chat => (
            <ChatSelectItem key={chat.id} chat={chat} />
          ))}
        </SelectGroup>
      </SelectContent>
    </Select>
  );
};

export default ChatSelect;
