'use client';

import { useState, useEffect } from 'react';
import { createBrowserClient } from '@supabase/ssr';
import { useRouter } from 'next/navigation';
import TokenPurchaseModal from '@/components/TokenPurchaseModal';
import { ensureProfile } from '@/lib/ensure-profile';

interface Props {
  children: React.ReactNode;
}

export default function TojeongDetailUnlock({ children }: Props) {
  const [isUnlocked, setIsUnlocked] = useState(false);
  const [user, setUser] = useState<any>(null);
  const [credits, setCredits] = useState(0);
  const [showModal, setShowModal] = useState(false);
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const supabase = createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  );

  useEffect(() => {
    const init = async () => {
      const { data: { user } } = await supabase.auth.getUser();
      if (user) {
        setUser(user);
        const currentCredits = await ensureProfile(supabase, user);
        setCredits(currentCredits);
      }
    };
    init();
  }, []);

  const handleUnlock = async () => {
    if (!user) {
      if (confirm('로그인이 필요합니다. 로그인 페이지로 이동하시겠습니까?')) {
        router.push('/login');
      }
      return;
    }

    if (credits < 1) {
      setShowModal(true);
      return;
    }

    setLoading(true);
    const { error } = await supabase
      .from('profiles')
      .update({ credits: credits - 1 })
      .eq('id', user.id);

    if (error) {
      alert('토큰 차감에 실패했습니다. 다시 시도해주세요.');
      setLoading(false);
      return;
    }

    setCredits(credits - 1);
    setIsUnlocked(true);
    setLoading(false);
  };

  const handlePurchaseComplete = async () => {
    setShowModal(false);
    if (user) {
      const { data: profile } = await supabase
        .from('profiles')
        .select('credits')
        .eq('id', user.id)
        .single();
      if (profile) setCredits(profile.credits || 0);
    }
  };

  if (isUnlocked) {
    return <>{children}</>;
  }

  return (
    <>
      <div className="relative mb-8">
        {/* 블러 처리된 미리보기 */}
        <div className="filter blur-sm select-none pointer-events-none opacity-60">
          <div className="bg-white rounded-2xl shadow-lg p-8">
            <h3 className="text-2xl font-bold text-gray-900 mb-6 flex items-center">
              <span className="text-3xl mr-3">💡</span>
              한 해를 위한 조언
            </h3>
            <div className="space-y-3">
              <div className="h-4 bg-gray-200 rounded w-full"></div>
              <div className="h-4 bg-gray-200 rounded w-5/6"></div>
              <div className="h-4 bg-gray-200 rounded w-4/6"></div>
              <div className="h-4 bg-gray-200 rounded w-full"></div>
            </div>
          </div>
        </div>

        {/* 잠금 오버레이 */}
        <div className="absolute inset-0 flex items-center justify-center bg-white/40 backdrop-blur-[2px] rounded-2xl">
          <div className="text-center p-8 bg-white/95 backdrop-blur-md rounded-2xl shadow-xl border border-amber-100 max-w-sm mx-auto">
            <div className="text-4xl mb-4">🔐</div>
            <h3 className="text-2xl font-bold text-gray-900 mb-2">상세 조언 잠금해제</h3>
            <p className="text-gray-600 mb-2">
              토정비결의 상세한 조언과 해석을 확인하세요.
            </p>
            <p className="text-sm text-gray-500 mb-4">
              토큰 1개 사용 | 보유: <span className="font-bold text-amber-600">{credits}개</span>
            </p>
            <button
              onClick={handleUnlock}
              disabled={loading}
              className="w-full bg-gradient-to-r from-amber-600 to-orange-600 text-white font-bold py-3 px-6 rounded-xl hover:shadow-lg hover:scale-105 transition transform disabled:opacity-50"
            >
              {loading ? '처리 중...' : credits >= 1 ? '토큰 1개로 잠금해제' : '토큰 충전하기'}
            </button>
          </div>
        </div>
      </div>

      <TokenPurchaseModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onPurchaseComplete={handlePurchaseComplete}
        user={user}
        supabase={supabase}
      />
    </>
  );
}
