import { AlertCircle, ChevronDown, ChevronUp, Flag, Home, RefreshCcw, WifiOff } from 'lucide-react';
import React from 'react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { ScrollArea } from '@/components/ui/scroll-area';

/**
 * ENTEGRASYON KILAVUZU:
 * 1. Bu bileşeni uygulamanın en üst seviyesinde (App.tsx veya main.tsx) kullanın.
 * 2. Örnek Kullanım:
 *    <ErrorBoundary>
 *      <App />
 *    </ErrorBoundary>
 * 3. Ağ hataları, çalışma zamanı hataları ve render hataları otomatik olarak yakalanır.
 * 4. Geliştirme modunda (import.meta.env.DEV) hata detayları her zaman görünür.
 */

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
  errorInfo: React.ErrorInfo | null;
  isExpanded: boolean;
}

/**
 * ErrorBoundary bileşeni, uygulama genelindeki yakalanamayan hataları yakalar
 * ve kullanıcıya anlamlı bir hata ekranı sunar.
 */
class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  ErrorBoundaryState
> {
  constructor(props: { children: React.ReactNode }) {
    super(props);
    this.state = { 
      hasError: false, 
      error: null, 
      errorInfo: null,
      isExpanded: false 
    };
  }

  static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    // Hata günlüğe kaydetme (Sentry veya kendi log servisiniz buraya gelebilir)
    console.error('ErrorBoundary yakaladı:', error, errorInfo);
    this.setState({ errorInfo });
    
    // Örnek: Log servisine gönder
    this.logErrorToService(error, errorInfo);
  }

  logErrorToService(error: Error, errorInfo: React.ErrorInfo) {
    // Burada API çağrısı yapılabilir
    // fetch('/api/logs/error', { method: 'POST', body: JSON.stringify({ error, errorInfo }) });
    console.log('Hata raporu servise gönderildi (simülasyon)');
  }

  handleRetry = () => {
    this.setState({ hasError: false, error: null, errorInfo: null });
    window.location.reload();
  };

  handleGoHome = () => {
    window.location.href = '/';
  };

  handleReport = () => {
    // Raporlama işlemi simülasyonu
    alert('Hata raporu başarıyla gönderildi. Teşekkür ederiz!');
  };

  isNetworkError(error: Error | null): boolean {
    if (!error) return false;
    const networkKeywords = ['network', 'fetch', 'failed to fetch', 'load', 'cors', 'timeout'];
    return networkKeywords.some(keyword => 
      error.message.toLowerCase().includes(keyword) || 
      (error.stack && error.stack.toLowerCase().includes(keyword))
    );
  }

  render() {
    if (this.state.hasError) {
      const isDev = import.meta.env.DEV;
      const isNetworkError = this.isNetworkError(this.state.error);

      return (
        <div className="flex items-center justify-center min-h-screen p-4 bg-background text-foreground transition-colors duration-300">
          <Card className="w-full max-w-2xl shadow-xl border-destructive/20 overflow-hidden">
            <CardHeader className="bg-destructive/5 border-b border-destructive/10">
              <div className="flex items-center gap-4">
                <div className="p-3 rounded-full bg-destructive/10">
                  {isNetworkError ? (
                    <WifiOff className="w-8 h-8 text-destructive" />
                  ) : (
                    <AlertCircle className="w-8 h-8 text-destructive" />
                  )}
                </div>
                <div>
                  <CardTitle className="text-2xl font-bold tracking-tight">
                    {isNetworkError ? 'Bağlantı Hatası' : 'Bir Şeyler Yanlış Gitti'}
                  </CardTitle>
                  <CardDescription className="text-muted-foreground mt-1">
                    {isNetworkError 
                      ? 'Sunucuyla bağlantı kurulamadı. Lütfen internetinizi kontrol edin.'
                      : 'Uygulamada beklenmedik bir sorun oluştu.'}
                  </CardDescription>
                </div>
              </div>
            </CardHeader>

            <CardContent className="pt-6 space-y-4">
              <Alert variant="destructive" className="bg-destructive/10 border-destructive/20">
                <AlertTitle className="font-semibold">Hata Mesajı</AlertTitle>
                <AlertDescription className="mt-1 font-mono text-sm opacity-90">
                  {this.state.error?.message || 'Bilinmeyen bir hata oluştu.'}
                </AlertDescription>
              </Alert>

              {/* Teknik Detaylar (Geliştirme Modunda veya Genişletildiğinde) */}
              {(isDev || this.state.isExpanded) && (
                <Collapsible
                  open={this.state.isExpanded}
                  onOpenChange={(open) => this.setState({ isExpanded: open })}
                  className="w-full space-y-2"
                >
                  <div className="flex items-center justify-between">
                    <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                      Teknik Detaylar
                    </h4>
                    <CollapsibleTrigger asChild>
                      <Button variant="ghost" size="sm" className="h-8 px-2">
                        {this.state.isExpanded ? (
                          <ChevronUp className="h-4 w-4" />
                        ) : (
                          <ChevronDown className="h-4 w-4" />
                        )}
                        <span className="sr-only">Toggle</span>
                      </Button>
                    </CollapsibleTrigger>
                  </div>
                  <CollapsibleContent className="space-y-2">
                    <ScrollArea className="h-[250px] w-full rounded-md border bg-muted/50 p-4">
                      <pre className="text-xs font-mono leading-relaxed text-muted-foreground whitespace-pre-wrap break-all">
                        {this.state.error?.stack}
                        {"\n\nComponent Stack:\n"}
                        {this.state.errorInfo?.componentStack}
                      </pre>
                    </ScrollArea>
                  </CollapsibleContent>
                </Collapsible>
              )}
            </CardContent>

            <CardFooter className="bg-muted/30 border-t border-border p-6 flex flex-col sm:flex-row gap-3">
              <Button 
                onClick={this.handleRetry} 
                className="w-full sm:flex-1 gap-2"
                variant="default"
              >
                <RefreshCcw className="w-4 h-4" />
                Tekrar Dene
              </Button>
              <Button 
                onClick={this.handleGoHome} 
                variant="outline" 
                className="w-full sm:flex-1 gap-2"
              >
                <Home className="w-4 h-4" />
                Ana Sayfaya Dön
              </Button>
              <Button 
                onClick={this.handleReport} 
                variant="ghost" 
                className="w-full sm:w-auto gap-2 text-muted-foreground hover:text-destructive transition-colors"
              >
                <Flag className="w-4 h-4" />
                Sorunu Bildir
              </Button>
            </CardFooter>
          </Card>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
