'use client';

import { Empty } from '@/components/empty';
import { ProList } from '@/components/pro-list';
import { queryAnnouncement } from '@/services/user/announcement';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@workspace/airo-ui/components/dialog';
import { useTranslations } from 'next-intl';
import { useImperativeHandle, useRef, useState } from 'react';
import { Popup } from './Popup';

export interface AnnouncementDialogRef {
  open: () => void;
  close: () => void;
}

interface AnnouncementDialogProps {
  ref?: React.Ref<AnnouncementDialogRef>;
}

export const AnnouncementDialog = ({ ref }: AnnouncementDialogProps) => {
  const [open, setOpen] = useState(false);
  const t = useTranslations('dashboard');
  const popupRef = useRef(null);

  useImperativeHandle(ref, () => ({
    open: () => {
      setOpen(true);
    },
    close: () => {
      setOpen(false);
    },
  }));

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className='overflow-y-auto sm:max-w-[800px]'>
        <DialogHeader>
          <DialogTitle className='text-left text-2xl sm:text-4xl'>
            {t('announcementTitle')}
          </DialogTitle>
        </DialogHeader>

        <div className='mt-6'>
          <ProList<API.Announcement, Record<string, unknown>>
            request={async (pagination, filter) => {
              const response = await queryAnnouncement({
                ...pagination,
                ...filter,
                // pinned: false,
                // popup: false,
              });
              return {
                list: response.data.data?.announcements || [],
                total: response.data.data?.total || 0,
              };
            }}
            renderItem={(item) => {
              return (
                <div
                  className={`${item.pinned ? 'bg-[#B5C9E2]' : 'bg-white'} flex items-center rounded-[20px] px-4 py-1.5 shadow-[0_0_4.5px_0_rgba(0,0,0,0.25)]`}
                >
                  <p
                    className={`${item.pinned ? 'text-white' : 'text-[#4D4D4D]'} line-clamp-2 flex-1 text-[10px] sm:text-sm`}
                  >
                    {item.pinned && (
                      <span className={'text-[#225BA9]'}>{t('pinnedAnnouncement')}</span>
                    )}
                    <span>{item.content}</span>
                  </p>
                  <div className='ml-2 w-[65px] text-right'>
                    <span
                      className='cursor-pointer text-xs text-[#225BA9] sm:text-sm'
                      onClick={() => popupRef.current?.open(item)}
                    >
                      {t('viewDetails')}
                    </span>
                  </div>
                </div>
              );
            }}
            empty={<Empty />}
          />
        </div>
        <Popup ref={popupRef} />
      </DialogContent>
    </Dialog>
  );
};
