'use client';

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

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

interface AffiliateDialogProps {
  ref?: React.Ref<AffiliateDialogRef>;
}

export const AffiliateDialog = ({ ref }: AffiliateDialogProps) => {
  const [open, setOpen] = useState(false);
  const [sum, setSum] = useState<number>();
  const t = useTranslations('affiliate');

  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('inviteRecords')}</DialogTitle>
        </DialogHeader>

        <div className='mt-6'>
          <ProList<API.UserAffiliate, Record<string, unknown>>
            request={async (pagination, filter) => {
              const response = await queryUserAffiliateList({ ...pagination, ...filter });
              setSum(response.data.data?.sum);
              return {
                list: response.data.data?.list || [],
                total: response.data.data?.total || 0,
              };
            }}
            renderItem={(invite) => {
              return (
                <div className='flex flex-wrap justify-between gap-2 rounded-[20px] bg-white px-6 py-2 text-[10px] shadow-[0_0_4.5px_0_rgba(0,0,0,0.25)] sm:text-base'>
                  <div>
                    <div className={'text-sm text-[#225BA9]'}>{t('userIdentifier')}</div>
                    <div className={'font-bold text-[#091B33]'}>{invite.identifier}</div>
                  </div>
                  <div>
                    <div className={'text-sm text-[#225BA9]'}>{t('time')}</div>
                    <div className={'font-bold text-[#091B33]'}>
                      {formatDate(invite.registered_at)}
                    </div>
                  </div>
                </div>
              );
            }}
            empty={<Empty />}
          />
        </div>
      </DialogContent>
    </Dialog>
  );
};
