'use client';

/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */
import Image from 'next/image';
import { useCallback, useEffect, useState } from 'react';

import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import CloseButton from '@/components/button/CloseButton';
import ProfileLink from '@/components/link/ProfileLink';
import { useApiClient } from '@/lib/apiClient';

import StudioLogo from './StudioLogo';

interface StudioAccessStatus {
  user_id: string;
  user_handle: string;
  can_use_studio: boolean;
  is_on_waitlist: boolean;
  waitlist_rank: number | null;
  owned_invite_code: string | null;
  owned_invite_code_count: number | null;
  owned_invite_code_redeemed_count: number | null;
  invited_by: string | null;
  invitations?: [string, string][];
}

interface UserProfile {
  user_id: string;
  handle: string;
  display_name: string;
  avatar_image_url: string;
}

interface StudioInvitesModalProps {
  onClose: () => void;
}

export default function StudioInvitesModal({
  onClose,
}: StudioInvitesModalProps) {
  const [userStatus, setUserStatus] = useState<StudioAccessStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [invitations, setInvitations] = useState<[string, string][]>([]);
  const [userProfiles, setUserProfiles] = useState<Record<string, UserProfile>>(
    {}
  );
  const [copied, setCopied] = useState(false);

  const apiClient = useApiClient();

  const fetchUserProfiles = useCallback(
    async (handles: string[]) => {
      // console.log('fetchUserProfiles called with handles:', handles);
      try {
        const profiles: Record<string, UserProfile> = {};

        // Fetch profile for each unique handle
        for (const handle of handles) {
          if (handle && !userProfiles[handle]) {
            // console.log(`Fetching profile for handle: ${handle}`);
            try {
              const { data, error } = await apiClient.GET(
                '/api/profiles/{handle}',
                {
                  params: {
                    path: { handle },
                    query: {
                      playlists_sort_by: 'created_at',
                      clips_sort_by: 'created_at',
                      include_hooks: false,
                      include_artist_profile: false,
                    },
                  },
                }
              );

              // console.log(`Profile API response for ${handle}:`, {
              //   data,
              //   error,
              // });

              if (
                !error &&
                data &&
                typeof data === 'object' &&
                'user_id' in data
              ) {
                profiles[handle] = {
                  user_id: data.user_id as string,
                  handle: data.handle as string,
                  display_name:
                    (data.display_name as string) || (data.handle as string),
                  avatar_image_url: data.avatar_image_url as string,
                };
                // console.log(
                //   `Profile data set for ${handle}:`,
                //   profiles[handle]
                // );
              } else {
                // console.log(`Invalid profile data for ${handle}:`, data);
              }
            } catch (err) {
              console.error(`Failed to fetch profile for ${handle}:`, err);
            }
          } else {
            // console.log(
            //   `Skipping profile fetch for ${handle} - already exists or empty`
            // );
          }
        }

        if (Object.keys(profiles).length > 0) {
          // console.log('Setting new profiles:', profiles);
          setUserProfiles((prev) => ({ ...prev, ...profiles }));
        } else {
          // console.log('No new profiles to set');
        }
      } catch (err) {
        console.error('Failed to fetch user profiles:', err);
      }
    },
    [apiClient]
  ); // Removed userProfiles dependency

  useEffect(() => {
    const fetchUserStatus = async () => {
      try {
        setLoading(true);
        const { data, error } = await apiClient.GET(
          '/api/studio/access-status',
          {
            params: {
              query: {},
            },
          }
        );

        if (error) {
          throw new Error('Failed to fetch user status');
        }

        const userStatusData = data as StudioAccessStatus & {
          invitations?: [string, string][];
        };
        setUserStatus(userStatusData);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Something went wrong');
      } finally {
        setLoading(false);
      }
    };

    fetchUserStatus();
  }, [apiClient]);

  // Fetch invitations after userStatus is available
  useEffect(() => {
    if (!userStatus?.user_id) return;

    const fetchInvitations = async () => {
      try {
        const { data, error } = await apiClient.GET(
          '/api/studio/access-invitations',
          {
            params: {
              query: {
                limit: 100, // Get more invitations to show in the modal
              },
            },
          }
        );

        if (error) {
          throw new Error('Failed to fetch invitations');
        }

        // unknown required here because we had to break the schema type to fix iOS build
        const invitationsData = data as unknown as {
          invitations: [string, string][];
        };
        const allInvitations = invitationsData.invitations || [];

        // console.log('All invitations received:', allInvitations);
        // console.log('Current user ID:', userStatus.user_id);

        // Filter to only show invitations where current user is the inviter
        const userInvitations = allInvitations.filter(
          ([inviter]) => inviter === userStatus.user_handle
        );

        // console.log('Filtered user invitations:', userInvitations);

        setInvitations(userInvitations);

        // Fetch user profiles for the filtered invitations
        if (userInvitations.length > 0) {
          const inviteeHandles = userInvitations
            .map(([, invitee]) => invitee)
            .filter(Boolean);
          // console.log('Invitee handles to fetch profiles for:', inviteeHandles);
          fetchUserProfiles(inviteeHandles);
        } else {
          // console.log('No user invitations found, skipping profile fetch');
        }
      } catch (err) {
        console.error('Failed to fetch invitations:', err);
        // Don't set error state for invitations failure, just log it
      }
    };

    fetchInvitations();
  }, [apiClient, userStatus?.user_id]);

  const handleCopyLink = async () => {
    const inviteLink = userStatus?.owned_invite_code
      ? `https://www.suno.com/studio-waitlist?code=${userStatus.owned_invite_code}`
      : 'Error: No invite code found';

    const fullText = `${inviteLink}`;

    try {
      await navigator.clipboard.writeText(fullText);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error('Failed to copy link:', err);
      // Fallback for older browsers
      const textArea = document.createElement('textarea');
      textArea.value = fullText;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand('copy');
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      } catch (fallbackErr) {
        console.error('Fallback copy failed:', fallbackErr);
      }
      document.body.removeChild(textArea);
    }
  };

  if (loading) {
    return (
      <div className='fixed inset-0 z-50 flex items-center justify-center bg-black/60'>
        <div className='h-[652px] w-[894px] rounded-[50px] border border-white/10 bg-[#101012] p-11 shadow-[0px_10px_40px_rgba(0,0,0,0.5)]'>
          <div className='animate-pulse'>
            <div className='mb-4 h-8 rounded bg-white/10'></div>
            <div className='mb-2 h-4 rounded bg-white/10'></div>
            <div className='h-4 w-3/4 rounded bg-white/10'></div>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className='fixed inset-0 z-50 flex items-center justify-center bg-black/60'>
        <div className='h-[652px] w-[894px] rounded-[50px] border border-white/10 bg-[#101012] p-11 shadow-[0px_10px_40px_rgba(0,0,0,0.5)]'>
          <div className='text-center'>
            <h2 className='mb-4 text-xl font-medium text-white'>Error</h2>
            <p className='mb-6 text-white/50'>{error}</p>
            <button
              onClick={onClose}
              className='rounded-lg bg-white/10 px-6 py-2 text-white transition-colors hover:bg-white/20'
            >
              Close
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
      className='fixed inset-0 z-50 flex items-center justify-center bg-black/60'
      onClick={onClose}
    >
      <div
        className='h-[652px] w-[894px] overflow-hidden rounded-[50px] border border-white/10 bg-cover bg-center bg-no-repeat shadow-[0px_10px_40px_rgba(0,0,0,0.5)]'
        style={{
          backgroundImage:
            'url(https://cdn-o.suno.com/auras-v2/studio-invite-aura.png)',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Main Container */}
        <div className='relative flex h-full w-full flex-col items-center justify-center gap-[22px] py-11'>
          {/* Top Section - Header */}
          <div className='flex w-full flex-col items-start gap-[44px] px-11'>
            {/* Header Row */}
            <div className='flex w-full flex-row items-start justify-between'>
              {/* Left Content */}
              <div className='flex w-[451px] flex-col items-start gap-3'>
                <div className='text-base leading-5 font-normal text-[#C2C2C1]'>
                  Invite to
                </div>
                <div className='flex w-[332.81px] flex-col items-start gap-[22px]'>
                  <div className='flex h-[40px] w-[332.81px] items-start text-white'>
                    <div className='origin-left scale-150 transform'>
                      <StudioLogo />
                    </div>
                  </div>
                </div>
                <p className='w-[451px] text-base leading-5 font-normal text-[#C2C2C1]'>
                  Thank you for being an early adopter!
                  <br />
                  <br />
                  Share early access to Suno Studio, plus 3 months of Suno
                  Premier for free with your friends and collaborators.
                </p>
              </div>
            </div>

            {/* Close Button - Positioned absolutely relative to modal edge */}
            <CloseButton
              onClick={onClose}
              className='absolute top-11 right-11 h-11 w-11 bg-white/5 backdrop-blur-[25px] transition-colors hover:bg-white/10'
            />

            {/* Benefits Section */}
            <div className='flex w-full flex-row items-end gap-2'>
              {/* Benefits Cards */}
              <div className='flex flex-row gap-2'>
                <div className='flex h-[69px] w-[205px] flex-col items-center justify-center rounded-[18px] border border-white/15 bg-white/5 px-6 py-1'>
                  <div className='text-[28px] leading-8 font-medium whitespace-nowrap text-[#F9F8F6]'>
                    Early Access
                  </div>
                </div>
                <div className='flex h-[69px] w-[24px] flex-col items-center justify-center px-6 py-1'>
                  <div className='text-2xl font-bold text-[#F7F4EF]'>+</div>
                </div>
                <div className='flex h-[69px] w-[334px] flex-col items-center justify-center rounded-[18px] border border-white/15 bg-white/5 px-6 py-1'>
                  <div className='text-[28px] leading-8 font-medium whitespace-nowrap text-[#F9F8F6]'>
                    3 Months All Access
                  </div>
                </div>
              </div>

              {/* Stats Cards */}
              <div className='ml-auto flex flex-row gap-2'>
                <div className='flex h-[97px] w-[69px] flex-col items-center gap-2'>
                  <div className='text-center text-sm font-medium text-white/50'>
                    My Invites
                  </div>
                  <div className='flex h-[69px] w-[69px] flex-col items-center justify-center rounded-[18px] border border-white/15 bg-white/5 px-6 py-1'>
                    <div className='text-[28px] leading-8 font-medium text-[#F9F8F6]'>
                      {userStatus?.owned_invite_code_count || 0}
                    </div>
                  </div>
                </div>

                <div className='flex h-[97px] w-[69px] flex-col items-center gap-2'>
                  <div className='text-center text-sm font-medium text-white/50'>
                    Claimed
                  </div>
                  <div className='flex h-[69px] w-[69px] flex-col items-center justify-center rounded-[18px] border border-white/15 bg-white/5 px-6 py-1'>
                    <div className='text-[28px] leading-8 font-medium text-[#F9F8F6]'>
                      {userStatus?.owned_invite_code_redeemed_count || 0}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Divider */}
          <div className='h-0 w-full rounded-[10px] border border-white/15'></div>

          {/* Invited Users Section */}
          <div className='flex w-full flex-col items-start justify-end gap-[22px] px-11'>
            <div className='text-center text-sm font-medium text-white/50'>
              Invited by you
            </div>
            <div className='flex h-[97px] w-[385px] flex-row items-start justify-start gap-[10px]'>
              {loading ? (
                // Loading state with 5 placeholder avatars
                Array.from({ length: 5 }).map((_, index) => (
                  <div
                    key={index}
                    className='flex h-[97px] w-[69px] flex-col items-center gap-2'
                  >
                    <div className='flex h-[69px] w-[69px] animate-pulse flex-col items-center justify-center gap-1 rounded-[100px] border border-white/15 bg-white/5 px-6 py-1'>
                      <div className='h-8 w-8 rounded-full bg-white/10'></div>
                    </div>
                    <div className='h-5 w-[52px] text-center text-sm leading-5 font-medium text-white/50'>
                      Loading...
                    </div>
                  </div>
                ))
              ) : error ? (
                <div className='py-8 text-center'>
                  <p className='mb-4 text-sm text-white/50'>
                    Failed to load invitations
                  </p>
                  <button
                    onClick={() => window.location.reload()}
                    className='rounded-lg bg-white/10 px-4 py-2 text-sm text-white transition-colors hover:bg-white/20'
                  >
                    Retry
                  </button>
                </div>
              ) : invitations.length > 0 ? (
                invitations.slice(0, 5).map(([_inviter, invitee], index) => {
                  const profile = userProfiles[invitee];
                  return (
                    <div
                      key={index}
                      className='flex h-[97px] w-[69px] flex-col items-center gap-2'
                    >
                      <ProfileLink
                        handle={profile?.handle || invitee}
                        className='flex h-[69px] w-[69px] cursor-pointer items-center justify-center overflow-hidden rounded-[100px] border border-white/15 bg-white/5 transition-colors hover:bg-white/10'
                        target='_blank'
                        rel='noopener noreferrer'
                      >
                        {profile?.avatar_image_url ? (
                          <Image
                            src={profile.avatar_image_url}
                            alt={`${profile.display_name}'s profile`}
                            width={69}
                            height={69}
                            className='h-full w-full object-cover'
                          />
                        ) : (
                          <div className='h-full w-full bg-white/10'></div>
                        )}
                      </ProfileLink>
                      <div className='h-5 w-[69px] truncate text-center text-xs leading-4 font-medium text-white/50'>
                        {profile?.display_name || invitee}
                      </div>
                    </div>
                  );
                })
              ) : (
                // Show 5 empty avatar slots when no invitations
                Array.from({ length: 5 }).map((_, index) => (
                  <div
                    key={index}
                    className='flex h-[97px] w-[69px] flex-col items-center gap-2'
                  >
                    <div className='flex h-[69px] w-[69px] flex-col items-center justify-center gap-1 rounded-[100px] border border-white/15 bg-white/5 px-6 py-1'>
                      <div className='h-8 w-8 rounded-full bg-white/10'></div>
                    </div>
                    <div className='h-5 w-[80px] text-center text-xs leading-4 font-medium text-white/50'>
                      {index === 0 ? 'No invites yet' : ''}
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Bottom Section - Footer and Copy Button */}
          <div className='flex w-full flex-row items-end justify-between gap-[22px] px-11'>
            {/* Contact Info */}
            <div className='h-8 w-[376px] text-xs leading-4 font-normal text-white/75'>
              For any questions or requesting extra invites, email{' '}
              <a
                href='mailto:suno-studio@suno.com?subject=VIP%20Invite%20Code%20Request'
                className='text-white underline transition-colors hover:text-white/80'
              >
                suno-studio@suno.com
              </a>{' '}
              with subject line &ldquo;VIP Invite Code Request&rdquo;.
            </div>

            {/* Copy Button */}
            <Button
              variant={ButtonVariant.Secondary}
              size={ButtonSize.Small}
              shape={ButtonShape.Pill}
              icon={
                <div className='h-7 w-7'>
                  <svg
                    className='h-7 w-7 text-white'
                    fill='none'
                    stroke='currentColor'
                    viewBox='0 0 24 24'
                    xmlns='http://www.w3.org/2000/svg'
                  >
                    <path
                      strokeLinecap='round'
                      strokeLinejoin='round'
                      strokeWidth={2}
                      d='M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z'
                    />
                  </svg>
                </div>
              }
              onClick={handleCopyLink}
              className='py-3 text-lg font-medium'
              style={{
                backgroundImage:
                  'url(https://cdn-o.suno.com/auras/pro_aura.jpg)',
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                backgroundRepeat: 'no-repeat',
              }}
            >
              {copied ? 'Copied!' : 'Copy Invite Link'}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
