
import React, { useEffect, useState } from 'react';

// 연결된 소셜 계정 정보를 저장하는 localStorage 키
const SOCIAL_CONNECTED_KEY = 'castad_social_connected';

interface ConnectedSocialAccount {
  platform: string;
  account_id: string;
  channel_name: string;
  profile_image: string | null;
  connected_at: string;
}

const SocialConnectSuccess: React.FC = () => {
  const [countdown, setCountdown] = useState(3);

  // URL 파라미터 파싱
  const searchParams = new URLSearchParams(window.location.search);
  const platform = searchParams.get('platform') || 'unknown';
  const accountId = searchParams.get('account_id') || '';
  const channelName = searchParams.get('channel_name') || '';
  const profileImage = searchParams.get('profile_image') || null;

  const platformName = platform === 'youtube' ? 'YouTube' :
                       platform === 'instagram' ? 'Instagram' :
                       platform === 'facebook' ? 'Facebook' : platform;

  // 연결된 계정 정보를 localStorage에 저장
  useEffect(() => {
    if (platform && accountId) {
      const connectedAccount: ConnectedSocialAccount = {
        platform,
        account_id: accountId,
        channel_name: channelName,
        profile_image: profileImage,
        connected_at: new Date().toISOString(),
      };
      localStorage.setItem(SOCIAL_CONNECTED_KEY, JSON.stringify(connectedAccount));
      console.log('[Social Connect] Account saved:', connectedAccount);
    }
  }, [platform, accountId, channelName, profileImage]);

  const navigateToHome = () => {
    // URL을 루트로 변경하고 페이지 새로고침하여 generation_flow로 이동
    window.location.href = '/';
  };

  useEffect(() => {
    const timer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          navigateToHome();
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  return (
    <div className="social-connect-page">
      <div className="social-connect-card success">
        {/* 프로필 이미지가 있으면 표시 */}
        {profileImage ? (
          <img
            src={profileImage}
            alt={channelName || platformName}
            className="social-connect-profile-image"
          />
        ) : (
          <div className="social-connect-icon success">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
              <polyline points="22 4 12 14.01 9 11.01" />
            </svg>
          </div>
        )}

        <h1 className="social-connect-title">
          {channelName || platformName} 연결 완료
        </h1>

        <p className="social-connect-message">
          {channelName ? (
            <>{platformName} 계정이 성공적으로 연결되었습니다.</>
          ) : (
            <>계정이 성공적으로 연결되었습니다.</>
          )}
        </p>

        {channelName && (
          <div className="social-connect-account-info">
            <span className="social-connect-channel-badge">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polyline points="20 6 9 17 4 12" />
              </svg>
              인증됨
            </span>
          </div>
        )}

        <p className="social-connect-countdown">
          {countdown}초 후 자동으로 이동합니다...
        </p>

        <button
          onClick={navigateToHome}
          className="social-connect-button"
        >
          지금 이동
        </button>
      </div>
    </div>
  );
};

export default SocialConnectSuccess;
