'use client';

import { useEffect } from 'react';
import Link from 'next/link';
import { AlertCircle, Home, RotateCcw, Shield } from 'lucide-react';
import { reportErrorToSlack } from '@/lib/error-reporting';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';

/**
 * Protected Group Error Boundary
 *
 * 특징:
 * - AuthenticatedLayout 자동 적용 (사이드바, 헤더 포함)
 * - 보호된 경로 내 에러만 포착
 * - 인증된 사용자를 위한 친근한 에러 UI
 */
export default function ProtectedError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    console.error('🔴 Protected Route Error:', error);
    reportErrorToSlack({
      errorType: 'ERROR_BOUNDARY',
      message: error.message,
      pageUrl: typeof window !== 'undefined' ? window.location.href : '',
      timestamp: new Date().toISOString(),
      digest: error.digest,
      stack: error.stack?.slice(0, 500),
      userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : undefined,
    });
  }, [error]);

  return (
    <div className="flex items-center justify-center min-h-[calc(100vh-200px)] p-4">
      <Card className="w-full max-w-2xl border border-destructive/20 bg-card/50 backdrop-blur">
        <CardHeader className="text-center pb-4">
          <div className="flex justify-center mb-6">
            <div className="relative">
              <div className="w-24 h-24 bg-gradient-to-br from-orange-500/20 to-red-500/20 rounded-2xl flex items-center justify-center">
                <AlertCircle className="w-12 h-12 text-orange-600 dark:text-orange-500" strokeWidth={2} />
              </div>
              <div className="absolute -top-1 -right-1 w-8 h-8 bg-orange-500 rounded-full flex items-center justify-center shadow-lg">
                <Shield className="w-4 h-4 text-white" />
              </div>
            </div>
          </div>
          <CardTitle className="text-2xl md:text-3xl font-bold text-foreground mb-2">
            일시적인 오류가 발생했습니다
          </CardTitle>
          <p className="text-muted-foreground">
            페이지를 불러오는 중 문제가 발생했습니다.
          </p>
        </CardHeader>

        <CardContent className="space-y-6">
          {/* 에러 상세 정보 (개발 환경에서만) */}
          {process.env.NODE_ENV === 'development' && (
            <div className="bg-destructive/10 border border-destructive/30 rounded-xl p-4 space-y-2">
              <p className="text-xs font-mono text-destructive font-semibold">
                🐛 개발 모드 - 에러 정보:
              </p>
              <p className="text-xs font-mono text-destructive break-all">
                {error.message}
              </p>
              {error.digest && (
                <p className="text-xs font-mono text-muted-foreground">
                  Digest: {error.digest}
                </p>
              )}
              {error.stack && (
                <details className="text-xs font-mono text-muted-foreground mt-2">
                  <summary className="cursor-pointer hover:text-foreground">
                    Stack Trace
                  </summary>
                  <pre className="mt-2 overflow-auto max-h-40 text-[10px]">
                    {error.stack}
                  </pre>
                </details>
              )}
            </div>
          )}

          {/* 안내 메시지 */}
          <div className="bg-muted/50 rounded-xl p-6 space-y-3">
            <p className="text-sm text-foreground font-medium">
              다음 방법을 시도해보세요:
            </p>
            <ul className="text-sm text-muted-foreground space-y-1 list-disc list-inside">
              <li>다시 시도 버튼을 클릭하세요</li>
              <li>다른 메뉴를 선택해보세요</li>
              <li>페이지를 새로고침 해보세요</li>
              <li>문제가 지속되면 관리자에게 문의하세요</li>
            </ul>
          </div>

          {/* 액션 버튼 */}
          <div className="flex flex-col sm:flex-row gap-3 pt-4">
            <Button
              variant="outline"
              onClick={reset}
              className="flex-1 rounded-xl"
            >
              <RotateCcw className="w-4 h-4 mr-2" />
              다시 시도
            </Button>

            <Button
              asChild
              className="flex-1 rounded-xl bg-primary hover:bg-primary/90"
            >
              <Link href="/dashboard">
                <Home className="w-4 h-4 mr-2" />
                대시보드로 이동
              </Link>
            </Button>
          </div>

          {/* 도움말 */}
          <div className="pt-6 border-t border-border/20 text-center">
            <p className="text-xs text-muted-foreground">
              💡 좌측 메뉴에서 다른 페이지를 이용하실 수 있습니다.
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}