"use client";

import { useEffect, Suspense, Component, ReactNode } from "react";
import { useRouter } from "next/navigation";
import Dashboard from "@/components/dashboard/dashboard";
import { MessageCircle, AlertCircle, RefreshCw } from "lucide-react";
import dynamic from "next/dynamic";
import { Skeleton } from "@/components/common/skeleton";
import { Card, CardContent, CardHeader } from "@/components/common/card";
import { Alert, AlertDescription, AlertTitle } from "@/components/common/alert";
import { Button } from "@/components/common/button";

// Error Boundary Component
interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
}

interface ErrorBoundaryProps {
  children: ReactNode;
  componentName?: string;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  private retryCount = 0;
  private maxRetries = 2;

  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error(`Error loading ${this.props.componentName || 'component'}:`, error, errorInfo);
  }

  handleRetry = () => {
    if (this.retryCount < this.maxRetries) {
      this.retryCount++;
      this.setState({ hasError: false, error: null });
    } else {
      window.location.reload();
    }
  };

  render() {
    if (this.state.hasError) {
      return (
        <Alert variant="destructive" className="animate-in fade-in duration-300">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Failed to load {this.props.componentName || 'component'}</AlertTitle>
          <AlertDescription className="mt-2">
            <p className="mb-3">
              {this.state.error?.message || 'An unexpected error occurred while loading this component.'}
            </p>
            {this.retryCount < this.maxRetries && (
              <p className="text-xs text-muted-foreground mb-3">
                Retry attempt {this.retryCount + 1} of {this.maxRetries + 1}
              </p>
            )}
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={this.handleRetry}
              >
                <RefreshCw className="h-3 w-3 mr-2" />
                {this.retryCount < this.maxRetries ? 'Try Again' : 'Reload Page'}
              </Button>
            </div>
          </AlertDescription>
        </Alert>
      );
    }

    return this.props.children;
  }
}

// Lazy load the ChatTable component with error handling
const ChatTable = dynamic(() => import("@/components/dashboard/ChatTable").catch((err) => {
  console.error("Failed to load ChatTable:", err);
  throw err;
}), {
  loading: () => <ChatTableSkeleton />
});

// Loading skeleton for the chat table
function ChatTableSkeleton() {
  return (
    <Card className="animate-in fade-in duration-500 relative">
      {/* Subtle loading indicator */}
      <div className="absolute top-0 left-0 right-0 h-1 bg-muted overflow-hidden rounded-t-lg">
        <div className="h-full bg-primary w-1/3"
          style={{
            background: 'linear-gradient(90deg, transparent, hsl(var(--primary)), transparent)',
            backgroundSize: '200% 100%',
            animation: 'shimmer 2s ease-in-out infinite',
          }}
        />
      </div>

      <CardHeader>
        <div className="flex items-center justify-between">
          <Skeleton className="h-6 w-32" />
          <Skeleton className="h-9 w-24 rounded-md" />
        </div>
      </CardHeader>
      <CardContent>
        <div className="border rounded-lg">
          <div className="border-b p-4">
            <div className="flex items-center gap-4">
              {['Customer', 'Last Message', 'Date', 'Status', 'Actions'].map((header, i) => (
                <Skeleton
                  key={i}
                  className="h-4 w-20 flex-1 animate-in fade-in"
                  style={{
                    animationDelay: `${i * 50}ms`,
                    animationDuration: '300ms',
                    animationFillMode: 'both',
                  }}
                />
              ))}
            </div>
          </div>

          {[...Array(6)].map((_, i) => (
            <div
              key={i}
              className="border-b last:border-b-0 p-4 animate-in fade-in"
              style={{
                animationDelay: `${300 + i * 50}ms`,
                animationDuration: '300ms',
                animationFillMode: 'both',
              }}
            >
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-3 flex-1">
                  <Skeleton className="h-10 w-10 rounded-full" />
                  <div className="space-y-1">
                    <Skeleton className="h-4 w-32" />
                    <Skeleton className="h-3 w-24" />
                  </div>
                </div>
                <Skeleton className="h-4 w-40 flex-1" />
                <Skeleton className="h-4 w-20 flex-1" />
                <Skeleton className="h-6 w-16 flex-1 rounded-full" />
                <div className="flex gap-2 flex-1">
                  <Skeleton className="h-8 w-16 rounded-md" />
                  <Skeleton className="h-8 w-16 rounded-md" />
                </div>
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

export default function ChatsPage() {
  return (
    <Dashboard>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-semibold text-gray-900 dark:text-white flex items-center">
            <MessageCircle className="mr-2 h-6 w-6" />
            Customer Chats
          </h1>
        </div>

        <ErrorBoundary componentName="Chat Table">
          <Suspense fallback={<ChatTableSkeleton />}>
            <ChatTable />
          </Suspense>
        </ErrorBoundary>
      </div>
    </Dashboard>
  );
} 
