import { useCallback, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import { CheckIcon, CloseIcon } from '@/icons';
import { ProjectInviteSchema } from '@/state/projectStore';
import { formatDateStringWTime } from '@/utils/utils';

const InviteList = ({
  invites,
  onAcceptInvite,
  onRejectInvite,
}: {
  invites: ProjectInviteSchema[];
  onAcceptInvite: (inviteId: string) => void;
  onRejectInvite: (inviteId: string) => void;
}) => {
  const { project: projectStore } = useStores();

  if (projectStore.loadingInvitedProjects) {
    return (
      <div className='flex items-center justify-center py-8'>
        <div className='text-foreground-secondary'>Loading invites...</div>
      </div>
    );
  }

  if (invites.length === 0) {
    return (
      <div className='flex items-center justify-center py-8'>
        <div className='text-foreground-secondary'>No invites found.</div>
      </div>
    );
  }

  return (
    <div className='flex flex-col gap-2 px-4 pb-4'>
      {invites.map((invite) => (
        <InviteRow
          key={invite.id}
          invite={invite}
          onAccept={onAcceptInvite}
          onReject={onRejectInvite}
        />
      ))}
    </div>
  );
};

const InviteRow = ({
  invite,
  onAccept,
  onReject,
}: {
  invite: ProjectInviteSchema;
  onAccept: (inviteId: string) => void;
  onReject: (inviteId: string) => void;
}) => {
  const [isLoading, setIsLoading] = useState(false);

  const handleAccept = useCallback(
    async (e: React.MouseEvent) => {
      e.stopPropagation();
      if (isLoading) return;

      setIsLoading(true);
      try {
        await onAccept(invite.id);
      } finally {
        setIsLoading(false);
      }
    },
    [invite.id, onAccept, isLoading]
  );

  const handleReject = useCallback(
    async (e: React.MouseEvent) => {
      e.stopPropagation();
      if (isLoading) return;

      setIsLoading(true);
      try {
        await onReject(invite.id);
      } finally {
        setIsLoading(false);
      }
    },
    [invite.id, onReject, isLoading]
  );

  return (
    <div className='w-full overflow-hidden rounded-[16px] px-[16px] py-[12px] font-medium transition-colors'>
      <div className='flex items-center justify-between'>
        <div className='flex items-center gap-4'>
          <div className='relative flex-[0_0_100px]'>
            <ImageWithFallback
              src={`https://cdn1.suno.ai/sAura${(parseInt(invite.project.id.split('-')[0], 16) % 16) + 1}.jpg`}
              alt={`Cover image for ${invite.project.name}`}
              className='h-[78px] w-[100px] rounded-[8px] object-cover'
              fallbackSrc='https://cdn-o.suno.com/auras/Aura-01.png'
            />
            <div className='absolute right-1 bottom-1 rounded-full bg-[var(--color-background-smoke-thick)] px-2 py-1 text-xs text-[var(--color-foreground-primary-on-dark)] backdrop-blur-[12px]'>
              {invite.project.clip_count} Songs
            </div>
          </div>
          <div className='flex flex-col'>
            <div className='text-[16px] font-semibold text-[var(--color-foreground-primary)]'>
              {invite.project.name}
            </div>
            <div className='text-[12px] font-normal text-[var(--color-foreground-secondary)]'>
              Invited by{' '}
              {invite.invited_by_user_display_name ||
                invite.invited_by_user_handle}
            </div>
            <div className='text-[12px] font-normal text-[var(--color-foreground-secondary)]'>
              {invite.created_at
                ? formatDateStringWTime(invite.created_at, undefined, true)
                : ''}
            </div>
          </div>
        </div>
        <div className='flex gap-2'>
          <Button
            onClick={handleAccept}
            disabled={isLoading}
            title='Accept invite'
            variant={ButtonVariant.Primary}
            shape={ButtonShape.Pill}
            size={ButtonSize.Small}
            icon={<CheckIcon />}
          ></Button>
          <Button
            onClick={handleReject}
            disabled={isLoading}
            title='Reject invite'
            variant={ButtonVariant.Secondary}
            shape={ButtonShape.Pill}
            size={ButtonSize.Small}
            icon={<CloseIcon />}
          ></Button>
        </div>
      </div>
    </div>
  );
};

export default InviteList;
